blob: a70bece3e892af4518a10f961f91b2f68c336262 [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);
1965 else if (isa<AlignedAttr>(Attr))
1966 // AlignedAttrs are handled separately, because we need to handle all
1967 // such attributes on a declaration at the same time.
1968 NewAttr = 0;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001969 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001970 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001971
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001972 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001973 NewAttr->setInherited(true);
1974 D->addAttr(NewAttr);
1975 return true;
1976 }
1977
1978 return false;
1979}
1980
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001981static const Decl *getDefinition(const Decl *D) {
1982 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001983 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001984 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1985 const VarDecl *Def = VD->getDefinition();
1986 if (Def)
1987 return Def;
1988 return VD->getActingDefinition();
1989 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001990 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001991 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001992 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001993 return Def;
1994 }
1995 return NULL;
1996}
1997
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001998static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1999 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2000 I != E; ++I) {
2001 Attr *Attribute = *I;
2002 if (Attribute->getKind() == Kind)
2003 return true;
2004 }
2005 return false;
2006}
2007
2008/// checkNewAttributesAfterDef - If we already have a definition, check that
2009/// there are no new attributes in this declaration.
2010static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2011 if (!New->hasAttrs())
2012 return;
2013
2014 const Decl *Def = getDefinition(Old);
2015 if (!Def || Def == New)
2016 return;
2017
2018 AttrVec &NewAttributes = New->getAttrs();
2019 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2020 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002021
2022 if (isa<AliasAttr>(NewAttribute)) {
2023 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2024 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2025 else {
2026 VarDecl *VD = cast<VarDecl>(New);
2027 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2028 VarDecl::TentativeDefinition
2029 ? diag::err_alias_after_tentative
2030 : diag::err_redefinition;
2031 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2032 S.Diag(Def->getLocation(), diag::note_previous_definition);
2033 VD->setInvalidDecl();
2034 }
2035 ++I;
2036 continue;
2037 }
2038
2039 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2040 // Tentative definitions are only interesting for the alias check above.
2041 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2042 ++I;
2043 continue;
2044 }
2045 }
2046
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002047 if (hasAttribute(Def, NewAttribute->getKind())) {
2048 ++I;
2049 continue; // regular attr merging will take care of validating this.
2050 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002051
Richard Smithdebc59d2013-01-30 05:45:05 +00002052 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002053 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002054 ++I;
2055 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002056 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2057 if (AA->isAlignas()) {
2058 // C++11 [dcl.align]p6:
2059 // if any declaration of an entity has an alignment-specifier,
2060 // every defining declaration of that entity shall specify an
2061 // equivalent alignment.
2062 // C11 6.7.5/7:
2063 // If the definition of an object does not have an alignment
2064 // specifier, any other declaration of that object shall also
2065 // have no alignment specifier.
2066 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002067 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002068 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002069 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002070 NewAttributes.erase(NewAttributes.begin() + I);
2071 --E;
2072 continue;
2073 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002074 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002075
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002076 S.Diag(NewAttribute->getLocation(),
2077 diag::warn_attribute_precede_definition);
2078 S.Diag(Def->getLocation(), diag::note_previous_definition);
2079 NewAttributes.erase(NewAttributes.begin() + I);
2080 --E;
2081 }
2082}
2083
John McCallf79e87d2011-03-02 04:00:57 +00002084/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002085void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002086 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002087 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2088 UsedAttr *NewAttr = OldAttr->clone(Context);
2089 NewAttr->setInherited(true);
2090 New->addAttr(NewAttr);
2091 }
2092
Richard Smithe233fbf2013-01-28 22:42:45 +00002093 if (!Old->hasAttrs() && !New->hasAttrs())
2094 return;
2095
Rafael Espindola36191042012-05-18 01:47:00 +00002096 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002097 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002098
Douglas Gregor32c17572012-01-01 20:30:41 +00002099 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002100 return;
John McCallf79e87d2011-03-02 04:00:57 +00002101
Douglas Gregor32c17572012-01-01 20:30:41 +00002102 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002103
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002104 // Ensure that any moving of objects within the allocated map is done before
2105 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002106 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002107
Peter Collingbourneab8bc062011-01-21 02:08:36 +00002108 for (specific_attr_iterator<InheritableAttr>
Douglas Gregor32c17572012-01-01 20:30:41 +00002109 i = Old->specific_attr_begin<InheritableAttr>(),
2110 e = Old->specific_attr_end<InheritableAttr>();
2111 i != e; ++i) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002112 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002113 // Ignore deprecated/unavailable/availability attributes if requested.
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002114 if (isa<DeprecatedAttr>(*i) ||
2115 isa<UnavailableAttr>(*i) ||
2116 isa<AvailabilityAttr>(*i)) {
2117 switch (AMK) {
2118 case AMK_None:
2119 continue;
John McCalld2930c22011-07-22 02:45:48 +00002120
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002121 case AMK_Redeclaration:
2122 break;
2123
2124 case AMK_Override:
2125 Override = true;
2126 break;
2127 }
2128 }
2129
Rafael Espindolab0938852013-10-25 01:28:12 +00002130 // Already handled.
2131 if (isa<UsedAttr>(*i))
2132 continue;
2133
Richard Smithbc8caaf2013-02-22 04:55:39 +00002134 if (mergeDeclAttribute(*this, New, *i, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002135 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002136 }
John McCallf79e87d2011-03-02 04:00:57 +00002137
Richard Smithbc8caaf2013-02-22 04:55:39 +00002138 if (mergeAlignedAttrs(*this, New, Old))
2139 foundAny = true;
2140
Douglas Gregor32c17572012-01-01 20:30:41 +00002141 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002142}
2143
2144/// mergeParamDeclAttributes - Copy attributes from the old parameter
2145/// to the new one.
2146static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2147 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002148 Sema &S) {
2149 // C++11 [dcl.attr.depend]p2:
2150 // The first declaration of a function shall specify the
2151 // carries_dependency attribute for its declarator-id if any declaration
2152 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002153 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2154 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2155 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002156 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2157 // Find the first declaration of the parameter.
2158 // FIXME: Should we build redeclaration chains for function parameters?
2159 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002160 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002161 const ParmVarDecl *FirstVD =
2162 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2163 S.Diag(FirstVD->getLocation(),
2164 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2165 }
2166
John McCallf79e87d2011-03-02 04:00:57 +00002167 if (!oldDecl->hasAttrs())
2168 return;
2169
2170 bool foundAny = newDecl->hasAttrs();
2171
2172 // Ensure that any moving of objects within the allocated map is
2173 // done before we process them.
2174 if (!foundAny) newDecl->setAttrs(AttrVec());
2175
2176 for (specific_attr_iterator<InheritableParamAttr>
2177 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2178 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2179 if (!DeclHasAttr(newDecl, *i)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002180 InheritableAttr *newAttr =
2181 cast<InheritableParamAttr>((*i)->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002182 newAttr->setInherited(true);
2183 newDecl->addAttr(newAttr);
2184 foundAny = true;
2185 }
2186 }
2187
2188 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002189}
2190
Dan Gohman28ade552010-07-26 21:25:24 +00002191namespace {
2192
Douglas Gregora74a2972009-03-06 22:43:54 +00002193/// Used in MergeFunctionDecl to keep track of function parameters in
2194/// C.
2195struct GNUCompatibleParamWarning {
2196 ParmVarDecl *OldParm;
2197 ParmVarDecl *NewParm;
2198 QualType PromotedType;
2199};
2200
Dan Gohman28ade552010-07-26 21:25:24 +00002201}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002202
2203/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002204Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002205 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002206 if (Ctor->isDefaultConstructor())
2207 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002208
2209 if (Ctor->isCopyConstructor())
2210 return Sema::CXXCopyConstructor;
2211
2212 if (Ctor->isMoveConstructor())
2213 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002214 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002215 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002216 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002217 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002218 } else if (MD->isMoveAssignmentOperator()) {
2219 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002220 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002221
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002222 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002223}
2224
Sebastian Redl243d9052010-06-09 21:17:41 +00002225/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002226/// only extern inline functions can be redefined, and even then only in
2227/// GNU89 mode.
2228static bool canRedefineFunction(const FunctionDecl *FD,
2229 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002230 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2231 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002232 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002233 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002234}
2235
Reid Kleckner78af0702013-08-27 23:08:25 +00002236const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2237 const AttributedType *AT = T->getAs<AttributedType>();
2238 while (AT && !AT->isCallingConv())
2239 AT = AT->getModifiedType()->getAs<AttributedType>();
2240 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002241}
2242
Benjamin Kramer3e350262013-02-15 12:30:38 +00002243template <typename T>
2244static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002245 const DeclContext *DC = Old->getDeclContext();
2246 if (DC->isRecord())
2247 return false;
2248
2249 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002250 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002251 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002252 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002253 return true;
2254 return false;
2255}
2256
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002257/// MergeFunctionDecl - We just parsed a function 'New' from
2258/// declarator D which has the same name and scope as a previous
2259/// declaration 'Old'. Figure out how to resolve this situation,
2260/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002261///
2262/// In C++, New and Old must be declarations that are not
2263/// overloaded. Use IsOverload to determine whether New and Old are
2264/// overloaded, and to select the Old declaration that New should be
2265/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002266///
2267/// Returns true if there was an error, false otherwise.
Richard Smith1c34fb72013-08-13 18:18:50 +00002268bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2269 bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002270 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002271 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002272 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002273 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002274 if (New->getFriendObjectKind()) {
2275 Diag(New->getLocation(), diag::err_using_decl_friend);
2276 Diag(Shadow->getTargetDecl()->getLocation(),
2277 diag::note_using_decl_target);
2278 Diag(Shadow->getUsingDecl()->getLocation(),
2279 diag::note_using_decl) << 0;
2280 return true;
2281 }
2282
John McCalle29c5cd2009-12-10 19:51:03 +00002283 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2284 Diag(Shadow->getTargetDecl()->getLocation(),
2285 diag::note_using_decl_target);
2286 Diag(Shadow->getUsingDecl()->getLocation(),
2287 diag::note_using_decl) << 0;
2288 return true;
2289 }
2290
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002291 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002292 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002293 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002294 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00002295 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002296
David Majnemerea5092a2013-07-07 23:49:50 +00002297 // If the old declaration is invalid, just give up here.
2298 if (Old->isInvalidDecl())
2299 return true;
2300
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002301 // Determine whether the previous declaration was a definition,
2302 // implicit declaration, or a declaration.
2303 diag::kind PrevDiag;
2304 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002305 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002306 else if (Old->isImplicit())
2307 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002308 else
Chris Lattner0369c572008-11-23 23:12:31 +00002309 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002310
Charles Davisfea48452010-02-18 02:00:42 +00002311 // Don't complain about this if we're in GNU89 mode and the old function
2312 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002313 // Don't complain about specializations. They are not supposed to have
2314 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002315 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002316 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002317 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002318 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002319 !canRedefineFunction(Old, getLangOpts())) {
2320 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002321 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2322 Diag(Old->getLocation(), PrevDiag);
2323 } else {
2324 Diag(New->getLocation(), diag::err_static_non_static) << New;
2325 Diag(Old->getLocation(), PrevDiag);
2326 return true;
2327 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002328 }
2329
Reid Kleckner78af0702013-08-27 23:08:25 +00002330
2331 // If a function is first declared with a calling convention, but is later
2332 // declared or defined without one, all following decls assume the calling
2333 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002334 //
John McCalla5f46fb2012-08-25 02:00:03 +00002335 // It's OK if a function is first declared without a calling convention,
2336 // but is later declared or defined with the default calling convention.
2337 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002338 // To test if either decl has an explicit calling convention, we look for
2339 // AttributedType sugar nodes on the type as written. If they are missing or
2340 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002341 //
2342 // Note also that we DO NOT return at this point, because we still have
2343 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002344 QualType OldQType = Context.getCanonicalType(Old->getType());
2345 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002346 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002347 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002348 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2349 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2350 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002351
Reid Kleckner78af0702013-08-27 23:08:25 +00002352 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002353 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002354 const FunctionType *FT =
2355 First->getType().getCanonicalType()->castAs<FunctionType>();
2356 FunctionType::ExtInfo FI = FT->getExtInfo();
2357 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2358 if (!NewCCExplicit) {
2359 // Inherit the CC from the previous declaration if it was specified
2360 // there but not here.
2361 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2362 RequiresAdjustment = true;
2363 } else {
2364 // Calling conventions aren't compatible, so complain.
2365 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2366 Diag(New->getLocation(), diag::err_cconv_change)
2367 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2368 << !FirstCCExplicit
2369 << (!FirstCCExplicit ? "" :
2370 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002371
Reid Kleckner78af0702013-08-27 23:08:25 +00002372 // Put the note on the first decl, since it is the one that matters.
2373 Diag(First->getLocation(), diag::note_previous_declaration);
2374 return true;
2375 }
John McCallcddbad02010-02-04 05:44:44 +00002376 }
2377
John McCallab26cfa2010-02-05 21:31:56 +00002378 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002379 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2380 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2381 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002382 }
2383
Douglas Gregor77e274f2010-06-18 21:30:25 +00002384 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002385 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2386 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2387 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002388 Diag(New->getLocation(), diag::err_regparm_mismatch)
2389 << NewType->getRegParmType()
2390 << OldType->getRegParmType();
2391 Diag(Old->getLocation(), diag::note_previous_declaration);
2392 return true;
2393 }
John McCall4f5019e2010-12-19 02:44:49 +00002394
2395 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2396 RequiresAdjustment = true;
2397 }
2398
Douglas Gregorf1404d72011-10-14 15:55:40 +00002399 // Merge ns_returns_retained attribute.
2400 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2401 if (NewTypeInfo.getProducesResult()) {
2402 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2403 Diag(Old->getLocation(), diag::note_previous_declaration);
2404 return true;
2405 }
2406
2407 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2408 RequiresAdjustment = true;
2409 }
2410
John McCall4f5019e2010-12-19 02:44:49 +00002411 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002412 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2413 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2414 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002415 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002416 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002417 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002418
2419 // If this redeclaration makes the function inline, we may need to add it to
2420 // UndefinedButUsed.
2421 if (!Old->isInlined() && New->isInlined() &&
2422 !New->hasAttr<GNUInlineAttr>() &&
2423 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2424 Old->isUsed(false) &&
2425 !Old->isDefined() && !New->isThisDeclarationADefinition())
2426 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2427 SourceLocation()));
2428
2429 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2430 // about it.
2431 if (New->hasAttr<GNUInlineAttr>() &&
2432 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2433 UndefinedButUsed.erase(Old->getCanonicalDecl());
2434 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002435
David Blaikiebbafb8a2012-03-11 07:00:24 +00002436 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002437 // (C++98 13.1p2):
2438 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002439 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002440 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002441
2442 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002443 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002444 // Redeclarations or specializations of a function or function template
2445 // with a declared return type that uses a placeholder type shall also
2446 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002447 QualType OldDeclaredReturnType =
2448 (Old->getTypeSourceInfo()
2449 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2450 : OldType)->getReturnType();
2451 QualType NewDeclaredReturnType =
2452 (New->getTypeSourceInfo()
2453 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2454 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002455 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002456 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2457 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2458 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002459 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2460 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002461 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2462 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002463 if (New->isCXXClassMember() && New->isOutOfLine())
2464 Diag(New->getLocation(),
2465 diag::err_member_def_does_not_match_ret_type) << New;
2466 else
2467 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002468 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2469 return true;
2470 }
2471 else
2472 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002473 }
2474
Alp Toker314cc812014-01-25 16:55:45 +00002475 QualType OldReturnType = OldType->getReturnType();
2476 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002477 if (OldReturnType != NewReturnType) {
2478 // If this function has a deduced return type and has already been
2479 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002480 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002481 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002482 New->setType(
2483 SubstAutoType(New->getType(),
2484 OldAT->isDependentType() ? Context.DependentTy
2485 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002486 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002487 SubstAutoType(NewQType,
2488 OldAT->isDependentType() ? Context.DependentTy
2489 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002490 }
2491 }
2492
2493 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2494 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002495 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002496 // Preserve triviality.
2497 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002498
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002499 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002500 // 2 CXXMethodDecls referring to the same function will be injected.
2501 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002502 bool IsClassScopeExplicitSpecialization =
2503 OldMethod->isFunctionTemplateSpecialization() &&
2504 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002505 bool isFriend = NewMethod->getFriendObjectKind();
2506
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002507 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2508 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002509 // -- Member function declarations with the same name and the
2510 // same parameter types cannot be overloaded if any of them
2511 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002512 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002513 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2514 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2515 return true;
2516 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002517
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002518 // C++ [class.mem]p1:
2519 // [...] A member shall not be declared twice in the
2520 // member-specification, except that a nested class or member
2521 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002522 if (ActiveTemplateInstantiations.empty()) {
2523 unsigned NewDiag;
2524 if (isa<CXXConstructorDecl>(OldMethod))
2525 NewDiag = diag::err_constructor_redeclared;
2526 else if (isa<CXXDestructorDecl>(NewMethod))
2527 NewDiag = diag::err_destructor_redeclared;
2528 else if (isa<CXXConversionDecl>(NewMethod))
2529 NewDiag = diag::err_conv_function_redeclared;
2530 else
2531 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002532
Richard Smith57e7ff92012-07-13 04:12:04 +00002533 Diag(New->getLocation(), NewDiag);
2534 } else {
2535 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2536 << New << New->getType();
2537 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002538 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002539
2540 // Complain if this is an explicit declaration of a special
2541 // member that was initially declared implicitly.
2542 //
2543 // As an exception, it's okay to befriend such methods in order
2544 // to permit the implicit constructor/destructor/operator calls.
2545 } else if (OldMethod->isImplicit()) {
2546 if (isFriend) {
2547 NewMethod->setImplicit();
2548 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002549 Diag(NewMethod->getLocation(),
2550 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002551 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002552 return true;
2553 }
Richard Smith337a5a12012-06-08 01:30:54 +00002554 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002555 Diag(NewMethod->getLocation(),
2556 diag::err_definition_of_explicitly_defaulted_member)
2557 << getSpecialMember(OldMethod);
2558 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002559 }
2560 }
2561
Richard Smith10876ef2013-01-17 01:30:42 +00002562 // C++11 [dcl.attr.noreturn]p1:
2563 // The first declaration of a function shall specify the noreturn
2564 // attribute if any declaration of that function specifies the noreturn
2565 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002566 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2567 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2568 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002569 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002570 diag::note_noreturn_missing_first_decl);
2571 }
2572
Richard Smithe233fbf2013-01-28 22:42:45 +00002573 // C++11 [dcl.attr.depend]p2:
2574 // The first declaration of a function shall specify the
2575 // carries_dependency attribute for its declarator-id if any declaration
2576 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002577 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2578 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2579 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002580 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002581 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002582 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2583 }
2584
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002585 // (C++98 8.3.5p3):
2586 // All declarations for a function shall agree exactly in both the
2587 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002588 // We also want to respect all the extended bits except noreturn.
2589
2590 // noreturn should now match unless the old type info didn't have it.
2591 QualType OldQTypeForComparison = OldQType;
2592 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2593 assert(OldQType == QualType(OldType, 0));
2594 const FunctionType *OldTypeForComparison
2595 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2596 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2597 assert(OldQTypeForComparison.isCanonical());
2598 }
2599
Rafael Espindolaf4187652013-02-14 01:18:37 +00002600 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002601 // As a special case, retain the language linkage from previous
2602 // declarations of a friend function as an extension.
2603 //
2604 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2605 // and is useful because there's otherwise no way to specify language
2606 // linkage within class scope.
2607 //
2608 // Check cautiously as the friend object kind isn't yet complete.
2609 if (New->getFriendObjectKind() != Decl::FOK_None) {
2610 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2611 Diag(Old->getLocation(), PrevDiag);
2612 } else {
2613 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2614 Diag(Old->getLocation(), PrevDiag);
2615 return true;
2616 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002617 }
2618
John McCall4f5019e2010-12-19 02:44:49 +00002619 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002620 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002621
Richard Smith541b38b2013-09-20 01:15:31 +00002622 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2623 New->isLocalExternDecl()) {
2624 // It's OK if we couldn't merge types for a local function declaraton
2625 // if either the old or new type is dependent. We'll merge the types
2626 // when we instantiate the function.
2627 return false;
2628 }
2629
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002630 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002631 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002632
2633 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002634 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002635 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002636 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002637 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2638 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002639 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002640 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002641 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002642 // The old declaration provided a function prototype, but the
2643 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002644 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Alp Toker9cacbab2014-01-20 20:26:09 +00002645 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2646 OldProto->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +00002647 NewQType =
2648 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2649 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002650 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002651 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002652
2653 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002654 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00002655 for (FunctionProtoType::param_type_iterator
2656 ParamType = OldProto->param_type_begin(),
2657 ParamEnd = OldProto->param_type_end();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002658 ParamType != ParamEnd; ++ParamType) {
2659 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002660 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002661 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002662 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002663 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002664 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002665 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002666 Param->setImplicit();
2667 Params.push_back(Param);
2668 }
2669
David Blaikie9c70e042011-09-21 18:16:56 +00002670 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002671 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002672
Richard Smith1c34fb72013-08-13 18:18:50 +00002673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002674 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002675
Douglas Gregora74a2972009-03-06 22:43:54 +00002676 // GNU C permits a K&R definition to follow a prototype declaration
2677 // if the declared types of the parameters in the K&R definition
2678 // match the types in the prototype declaration, even when the
2679 // promoted types of the parameters from the K&R definition differ
2680 // from the types in the prototype. GCC then keeps the types from
2681 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002682 //
2683 // If a variadic prototype is followed by a non-variadic K&R definition,
2684 // the K&R definition becomes variadic. This is sort of an edge case, but
2685 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2686 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002687 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002688 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002689 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002690 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 SmallVector<QualType, 16> ArgTypes;
2692 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002693 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002694 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002695 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002696 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregora74a2972009-03-06 22:43:54 +00002698 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002699 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2700 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002701 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002702 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002703 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002704 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2705 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002706 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002707 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002708 ArgTypes.push_back(NewParm->getType());
2709 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002710 NewParm->getType(),
2711 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002712 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2713 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002714 Warnings.push_back(Warn);
2715 ArgTypes.push_back(NewParm->getType());
2716 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002717 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002718 }
2719
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002720 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002721 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2722 Diag(Warnings[Warn].NewParm->getLocation(),
2723 diag::ext_param_promoted_not_compatible_with_prototype)
2724 << Warnings[Warn].PromotedType
2725 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002726 if (Warnings[Warn].OldParm->getLocation().isValid())
2727 Diag(Warnings[Warn].OldParm->getLocation(),
2728 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002729 }
2730
Richard Smith1c34fb72013-08-13 18:18:50 +00002731 if (MergeTypeWithOld)
2732 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2733 OldProto->getExtProtoInfo()));
2734 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002735 }
2736
2737 // Fall through to diagnose conflicting types.
2738 }
2739
John McCallad327cd2013-04-14 08:50:55 +00002740 // A function that has already been declared has been redeclared or
2741 // defined with a different type; show an appropriate diagnostic.
2742
2743 // If the previous declaration was an implicitly-generated builtin
2744 // declaration, then at the very least we should use a specialized note.
2745 unsigned BuiltinID;
2746 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2747 // If it's actually a library-defined builtin function like 'malloc'
2748 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002749 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002750 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2751 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2752 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002753
2754 // If this is a global redeclaration, just forget hereafter
2755 // about the "builtin-ness" of the function.
2756 //
2757 // Doing this for local extern declarations is problematic. If
2758 // the builtin declaration remains visible, a second invalid
2759 // local declaration will produce a hard error; if it doesn't
2760 // remain visible, a single bogus local redeclaration (which is
2761 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002762 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002763 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2764
Douglas Gregor893c2c92009-03-23 17:47:24 +00002765 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002766 }
Steve Naroff17832a42008-01-16 15:01:34 +00002767
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002768 PrevDiag = diag::note_previous_builtin_declaration;
2769 }
2770
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002771 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002772 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002773 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002774}
2775
Douglas Gregore62c0a42009-02-24 01:23:02 +00002776/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002777/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002778///
2779/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002780/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002781/// the new declaration, once we know that New is in fact a
2782/// redeclaration of Old.
2783///
2784/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002785bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002786 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002787 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002788 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002789
Douglas Gregore62c0a42009-02-24 01:23:02 +00002790 // Merge "pure" flag.
2791 if (Old->isPure())
2792 New->setPure();
2793
Rafael Espindolabefe1302012-11-25 14:07:59 +00002794 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002795 if (Old->getMostRecentDecl()->isUsed(false))
2796 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002797
John McCallf79e87d2011-03-02 04:00:57 +00002798 // Merge attributes from the parameters. These can mismatch with K&R
2799 // declarations.
2800 if (New->getNumParams() == Old->getNumParams())
2801 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2802 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002803 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002804
David Blaikiebbafb8a2012-03-11 07:00:24 +00002805 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002806 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002807
Rafael Espindola8778c282012-11-29 16:09:03 +00002808 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2810 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002812 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002813 New->setType(Merged);
2814
Douglas Gregore62c0a42009-02-24 01:23:02 +00002815 return false;
2816}
2817
John McCall31168b02011-06-15 23:02:42 +00002818
John McCallf79e87d2011-03-02 04:00:57 +00002819void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002820 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002821
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002822 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002823 AvailabilityMergeKind MergeKind =
2824 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2825 : AMK_Override;
2826 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002827
2828 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002829 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2830 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002831 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002832 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002833 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002834 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002835
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002836 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002837}
2838
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002839/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2840/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002841/// emitting diagnostics as appropriate.
2842///
2843/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002844/// to here in AddInitializerToDecl. We can't check them before the initializer
2845/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002846void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2847 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002848 if (New->isInvalidDecl() || Old->isInvalidDecl())
2849 return;
2850
2851 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002852 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002853 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002854 // We don't know what the new type is until the initializer is attached.
2855 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002856 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2857 // These could still be something that needs exception specs checked.
2858 return MergeVarDeclExceptionSpecs(New, Old);
2859 }
Richard Smith30482bc2011-02-20 03:19:35 +00002860 // C++ [basic.link]p10:
2861 // [...] the types specified by all declarations referring to a given
2862 // object or function shall be identical, except that declarations for an
2863 // array object can specify array types that differ by the presence or
2864 // absence of a major array bound (8.3.4).
2865 else if (Old->getType()->isIncompleteArrayType() &&
2866 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002867 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2868 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2869 if (Context.hasSameType(OldArray->getElementType(),
2870 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002871 MergedT = New->getType();
2872 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002873 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002874 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2875 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2876 if (Context.hasSameType(OldArray->getElementType(),
2877 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002878 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002879 } else if (New->getType()->isObjCObjectPointerType() &&
2880 Old->getType()->isObjCObjectPointerType()) {
2881 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2882 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002883 }
2884 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002885 // C 6.2.7p2:
2886 // All declarations that refer to the same object or function shall have
2887 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002888 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2889 }
2890 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002891 // It's OK if we couldn't merge types if either type is dependent, for a
2892 // block-scope variable. In other cases (static data members of class
2893 // templates, variable templates, ...), we require the types to be
2894 // equivalent.
2895 // FIXME: The C++ standard doesn't say anything about this.
2896 if ((New->getType()->isDependentType() ||
2897 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2898 // If the old type was dependent, we can't merge with it, so the new type
2899 // becomes dependent for now. We'll reproduce the original type when we
2900 // instantiate the TypeSourceInfo for the variable.
2901 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2902 New->setType(Context.DependentTy);
2903 return;
2904 }
2905
2906 // FIXME: Even if this merging succeeds, some other non-visible declaration
2907 // of this variable might have an incompatible type. For instance:
2908 //
2909 // extern int arr[];
2910 // void f() { extern int arr[2]; }
2911 // void g() { extern int arr[3]; }
2912 //
2913 // Neither C nor C++ requires a diagnostic for this, but we should still try
2914 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002915 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002916 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002917 Diag(Old->getLocation(), diag::note_previous_definition);
2918 return New->setInvalidDecl();
2919 }
John McCallb65e8fe2013-04-01 18:34:28 +00002920
2921 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002922 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002923 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002924 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002925}
2926
Richard Smith3c785782013-09-03 21:00:58 +00002927static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2928 LookupResult &Previous) {
2929 // C11 6.2.7p4:
2930 // For an identifier with internal or external linkage declared
2931 // in a scope in which a prior declaration of that identifier is
2932 // visible, if the prior declaration specifies internal or
2933 // external linkage, the type of the identifier at the later
2934 // declaration becomes the composite type.
2935 //
2936 // If the variable isn't visible, we do not merge with its type.
2937 if (Previous.isShadowed())
2938 return false;
2939
2940 if (S.getLangOpts().CPlusPlus) {
2941 // C++11 [dcl.array]p3:
2942 // If there is a preceding declaration of the entity in the same
2943 // scope in which the bound was specified, an omitted array bound
2944 // is taken to be the same as in that earlier declaration.
2945 return NewVD->isPreviousDeclInSameBlockScope() ||
2946 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2947 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2948 } else {
2949 // If the old declaration was function-local, don't merge with its
2950 // type unless we're in the same function.
2951 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2952 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2953 }
2954}
2955
Chris Lattner01564d92007-01-27 19:27:06 +00002956/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2957/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2958/// situation, merging decls or emitting diagnostics as appropriate.
2959///
Mike Stump11289f42009-09-09 15:08:12 +00002960/// Tentative definition rules (C99 6.9.2p2) are checked by
2961/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002962/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002963///
Richard Smith3c785782013-09-03 21:00:58 +00002964void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002965 // If the new decl is already invalid, don't do any other checking.
2966 if (New->isInvalidDecl())
2967 return;
Mike Stump11289f42009-09-09 15:08:12 +00002968
Richard Smithbeef3452014-01-16 23:39:20 +00002969 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2970
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002971 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002972 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002973 VarTemplateDecl *OldTemplate = 0;
2974 if (Previous.isSingleResult()) {
2975 if (NewTemplate) {
2976 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2977 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2978 } else
2979 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002980 }
2981 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002982 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002983 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002984 Diag(Previous.getRepresentativeDecl()->getLocation(),
2985 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002986 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002987 }
Chris Lattner84966392008-03-03 03:28:21 +00002988
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002989 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2990 return;
2991
Richard Smithbeef3452014-01-16 23:39:20 +00002992 // Ensure the template parameters are compatible.
2993 if (NewTemplate &&
2994 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2995 OldTemplate->getTemplateParameters(),
2996 /*Complain=*/true, TPL_TemplateMatch))
2997 return;
2998
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002999 // C++ [class.mem]p1:
3000 // A member shall not be declared twice in the member-specification [...]
3001 //
3002 // Here, we need only consider static data members.
3003 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3004 Diag(New->getLocation(), diag::err_duplicate_member)
3005 << New->getIdentifier();
3006 Diag(Old->getLocation(), diag::note_previous_declaration);
3007 New->setInvalidDecl();
3008 }
3009
Douglas Gregor32c17572012-01-01 20:30:41 +00003010 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003011 // Warn if an already-declared variable is made a weak_import in a subsequent
3012 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003013 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003014 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003015 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003016 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3017 Diag(Old->getLocation(), diag::note_previous_definition);
3018 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003019 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003020 }
Chris Lattner84966392008-03-03 03:28:21 +00003021
Richard Smith30482bc2011-02-20 03:19:35 +00003022 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003023 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3024
Richard Smith30482bc2011-02-20 03:19:35 +00003025 if (New->isInvalidDecl())
3026 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003027
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003028 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003029 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003030 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003031 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003032 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003033 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003034 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003035 }
Mike Stump11289f42009-09-09 15:08:12 +00003036 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003037 // For an identifier declared with the storage-class specifier
3038 // extern in a scope in which a prior declaration of that
3039 // identifier is visible,23) if the prior declaration specifies
3040 // internal or external linkage, the linkage of the identifier at
3041 // the later declaration is the same as the linkage specified at
3042 // the prior declaration. If no prior declaration is visible, or
3043 // if the prior declaration specifies no linkage, then the
3044 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003045 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003046 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003047 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003048 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003049 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003050 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003051 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003052 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003053 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003054
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003055 // Check if extern is followed by non-extern and vice-versa.
3056 if (New->hasExternalStorage() &&
3057 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3058 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3059 Diag(Old->getLocation(), diag::note_previous_definition);
3060 return New->setInvalidDecl();
3061 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003062 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3063 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003064 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3065 Diag(Old->getLocation(), diag::note_previous_definition);
3066 return New->setInvalidDecl();
3067 }
3068
Steve Naroffa5629372008-09-17 14:05:40 +00003069 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003070
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003071 // FIXME: The test for external storage here seems wrong? We still
3072 // need to check for mismatches.
3073 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003074 // Don't complain about out-of-line definitions of static members.
3075 !(Old->getLexicalDeclContext()->isRecord() &&
3076 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003077 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003078 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003079 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003080 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003081
Richard Smithfd3834f2013-04-13 02:43:54 +00003082 if (New->getTLSKind() != Old->getTLSKind()) {
3083 if (!Old->getTLSKind()) {
3084 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3085 Diag(Old->getLocation(), diag::note_previous_declaration);
3086 } else if (!New->getTLSKind()) {
3087 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3088 Diag(Old->getLocation(), diag::note_previous_declaration);
3089 } else {
3090 // Do not allow redeclaration to change the variable between requiring
3091 // static and dynamic initialization.
3092 // FIXME: GCC allows this, but uses the TLS keyword on the first
3093 // declaration to determine the kind. Do we need to be compatible here?
3094 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3095 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3096 Diag(Old->getLocation(), diag::note_previous_declaration);
3097 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003098 }
3099
Sebastian Redlf1842912010-02-02 18:35:11 +00003100 // C++ doesn't have tentative definitions, so go right ahead and check here.
3101 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003102 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003103 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003104 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003105 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003106 Diag(Def->getLocation(), diag::note_previous_definition);
3107 New->setInvalidDecl();
3108 return;
3109 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003110
Rafael Espindolaf4187652013-02-14 01:18:37 +00003111 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003112 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3113 Diag(Old->getLocation(), diag::note_previous_definition);
3114 New->setInvalidDecl();
3115 return;
3116 }
3117
Rafael Espindolabefe1302012-11-25 14:07:59 +00003118 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003119 if (Old->getMostRecentDecl()->isUsed(false))
3120 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003121
Douglas Gregor0760fa12009-03-10 23:43:53 +00003122 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003123 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003124 if (NewTemplate)
3125 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003126
3127 // Inherit access appropriately.
3128 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003129 if (NewTemplate)
3130 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003131}
3132
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003133/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3134/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003135Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003136 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003137 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003138}
3139
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003140static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003141 if (!S.Context.getLangOpts().CPlusPlus)
3142 return;
3143
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003144 if (isa<CXXRecordDecl>(Tag->getParent())) {
3145 // If this tag is the direct child of a class, number it if
3146 // it is anonymous.
3147 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3148 return;
3149 MangleNumberingContext &MCtx =
3150 S.Context.getManglingNumberContext(Tag->getParent());
3151 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3152 return;
3153 }
3154
3155 // If this tag isn't a direct child of a class, number it if it is local.
3156 Decl *ManglingContextDecl;
3157 if (MangleNumberingContext *MCtx =
3158 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3159 ManglingContextDecl)) {
3160 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3161 }
3162}
3163
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003164/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003165/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003166/// parameters to cope with template friend declarations.
3167Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3168 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003169 MultiTemplateParamsArg TemplateParams,
3170 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003171 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003172 TagDecl *Tag = 0;
3173 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3174 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003175 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003176 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003177 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003178 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003179
3180 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003181 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003182
John McCall07e91c02009-08-06 02:15:43 +00003183 // Note that the above type specs guarantee that the
3184 // type rep is a Decl, whereas in many of the others
3185 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003186 if (isa<TagDecl>(TagD))
3187 Tag = cast<TagDecl>(TagD);
3188 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3189 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003190 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003191
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003192 if (Tag) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003193 HandleTagNumbering(*this, Tag);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003194 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003195 if (Tag->isInvalidDecl())
3196 return Tag;
3197 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003198
Nuno Lopese9823fa2009-12-17 11:35:26 +00003199 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3200 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3201 // or incomplete types shall not be restrict-qualified."
3202 if (TypeQuals & DeclSpec::TQ_restrict)
3203 Diag(DS.getRestrictSpecLoc(),
3204 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3205 << DS.getSourceRange();
3206 }
3207
Richard Smitha77a0a62011-08-15 21:04:07 +00003208 if (DS.isConstexprSpecified()) {
3209 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3210 // and definitions of functions and variables.
3211 if (Tag)
3212 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3213 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3214 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003215 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3216 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003217 else
3218 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3219 // Don't emit warnings after this error.
3220 return TagD;
3221 }
3222
Richard Smithb1402ae2013-03-18 22:52:47 +00003223 DiagnoseFunctionSpecifiers(DS);
3224
Douglas Gregor3dad8422009-09-26 06:47:28 +00003225 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003226 // If we're dealing with a decl but not a TagDecl, assume that
3227 // whatever routines created it handled the friendship aspect.
3228 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003229 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003230 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003231 }
John McCallaa017372011-03-22 23:00:04 +00003232
Richard Smithb1402ae2013-03-18 22:52:47 +00003233 CXXScopeSpec &SS = DS.getTypeSpecScope();
3234 bool IsExplicitSpecialization =
3235 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3236 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3237 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3238 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3239 // nested-name-specifier unless it is an explicit instantiation
3240 // or an explicit specialization.
3241 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3242 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3243 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3244 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3245 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3246 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3247 << SS.getRange();
3248 return 0;
3249 }
3250
3251 // Track whether this decl-specifier declares anything.
3252 bool DeclaresAnything = true;
3253
3254 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003255 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003256 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003257 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003258 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003259 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003260 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003261
Richard Smithb1402ae2013-03-18 22:52:47 +00003262 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003263 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003264 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003265
Richard Smithb1402ae2013-03-18 22:52:47 +00003266 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003267 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003268 CurContext->isRecord() &&
3269 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3270 // Handle 2 kinds of anonymous struct:
3271 // struct STRUCT;
3272 // and
3273 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3274 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003275 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003276 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3277 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003278 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003279 << DS.getSourceRange();
3280 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3281 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003282 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003283
3284 // Skip all the checks below if we have a type error.
3285 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3286 (TagD && TagD->isInvalidDecl()))
3287 return TagD;
3288
3289 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003290 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3291 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3292 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003293 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3294 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003295
John McCallaa017372011-03-22 23:00:04 +00003296 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003297 // Customize diagnostic for a typedef missing a name.
3298 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003299 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003300 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003301 else
3302 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003303 }
Mike Stump11289f42009-09-09 15:08:12 +00003304
Richard Smithb1402ae2013-03-18 22:52:47 +00003305 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003306 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3307 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3308 << Tag->getTagKind()
3309 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3310
Richard Smithb1402ae2013-03-18 22:52:47 +00003311 ActOnDocumentableDecl(TagD);
3312
3313 // C 6.7/2:
3314 // A declaration [...] shall declare at least a declarator [...], a tag,
3315 // or the members of an enumeration.
3316 // C++ [dcl.dcl]p3:
3317 // [If there are no declarators], and except for the declaration of an
3318 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3319 // names into the program, or shall redeclare a name introduced by a
3320 // previous declaration.
3321 if (!DeclaresAnything) {
3322 // In C, we allow this as a (popular) extension / bug. Don't bother
3323 // producing further diagnostics for redundant qualifiers after this.
3324 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3325 return TagD;
3326 }
3327
3328 // C++ [dcl.stc]p1:
3329 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3330 // init-declarator-list of the declaration shall not be empty.
3331 // C++ [dcl.fct.spec]p1:
3332 // If a cv-qualifier appears in a decl-specifier-seq, the
3333 // init-declarator-list of the declaration shall not be empty.
3334 //
3335 // Spurious qualifiers here appear to be valid in C.
3336 unsigned DiagID = diag::warn_standalone_specifier;
3337 if (getLangOpts().CPlusPlus)
3338 DiagID = diag::ext_standalone_specifier;
3339
3340 // Note that a linkage-specification sets a storage class, but
3341 // 'extern "C" struct foo;' is actually valid and not theoretically
3342 // useless.
3343 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3344 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3345 Diag(DS.getStorageClassSpecLoc(), DiagID)
3346 << DeclSpec::getSpecifierName(SCS);
3347
Richard Smithb4a9e862013-04-12 22:46:28 +00003348 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3349 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3350 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003351 if (DS.getTypeQualifiers()) {
3352 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3353 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3354 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3355 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3356 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003357 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3358 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003359 }
3360
Eli Friedmane3217952011-12-17 00:36:09 +00003361 // Warn about ignored type attributes, for example:
3362 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003363 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003364 if (!DS.getAttributes().empty()) {
3365 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3366 if (TypeSpecType == DeclSpec::TST_class ||
3367 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003368 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003369 TypeSpecType == DeclSpec::TST_union ||
3370 TypeSpecType == DeclSpec::TST_enum) {
3371 AttributeList* attrs = DS.getAttributes().getList();
3372 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003373 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003374 << attrs->getName()
3375 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3376 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003377 TypeSpecType == DeclSpec::TST_union ? 2 :
3378 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003379 attrs = attrs->getNext();
3380 }
3381 }
3382 }
John McCallaa017372011-03-22 23:00:04 +00003383
John McCall48871652010-08-21 09:40:31 +00003384 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003385}
3386
John McCallea305ed2009-12-18 10:40:03 +00003387/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003388/// check if there's an existing declaration that can't be overloaded.
3389///
3390/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003391static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3392 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003393 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003394 DeclarationName Name,
3395 SourceLocation NameLoc,
3396 unsigned diagnostic) {
3397 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3398 Sema::ForRedeclaration);
3399 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003400
John McCallea305ed2009-12-18 10:40:03 +00003401 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003402 return false;
3403
3404 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003405 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003406 assert(PrevDecl && "Expected a non-null Decl");
3407
3408 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3409 return false;
John McCall1f82f242009-11-18 22:49:29 +00003410
John McCallea305ed2009-12-18 10:40:03 +00003411 SemaRef.Diag(NameLoc, diagnostic) << Name;
3412 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003413
3414 return true;
3415}
3416
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003417/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3418/// anonymous struct or union AnonRecord into the owning context Owner
3419/// and scope S. This routine will be invoked just after we realize
3420/// that an unnamed union or struct is actually an anonymous union or
3421/// struct, e.g.,
3422///
3423/// @code
3424/// union {
3425/// int i;
3426/// float f;
3427/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3428/// // f into the surrounding scope.x
3429/// @endcode
3430///
3431/// This routine is recursive, injecting the names of nested anonymous
3432/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003433static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003434 DeclContext *Owner,
3435 RecordDecl *AnonRecord,
3436 AccessSpecifier AS,
3437 SmallVectorImpl<NamedDecl *> &Chaining,
3438 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003439 unsigned diagKind
3440 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3441 : diag::err_anonymous_struct_member_redecl;
3442
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003443 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003444
3445 // Look every FieldDecl and IndirectFieldDecl with a name.
3446 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3447 DEnd = AnonRecord->decls_end();
3448 D != DEnd; ++D) {
3449 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3450 cast<NamedDecl>(*D)->getDeclName()) {
3451 ValueDecl *VD = cast<ValueDecl>(*D);
3452 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3453 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003454 // C++ [class.union]p2:
3455 // The names of the members of an anonymous union shall be
3456 // distinct from the names of any other entity in the
3457 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003458 Invalid = true;
3459 } else {
3460 // C++ [class.union]p2:
3461 // For the purpose of name lookup, after the anonymous union
3462 // definition, the members of the anonymous union are
3463 // considered to have been defined in the scope in which the
3464 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003465 unsigned OldChainingSize = Chaining.size();
3466 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3467 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3468 PE = IF->chain_end(); PI != PE; ++PI)
3469 Chaining.push_back(*PI);
3470 else
3471 Chaining.push_back(VD);
3472
Francois Pichet783dd6e2010-11-21 06:08:52 +00003473 assert(Chaining.size() >= 2);
3474 NamedDecl **NamedChain =
3475 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3476 for (unsigned i = 0; i < Chaining.size(); i++)
3477 NamedChain[i] = Chaining[i];
3478
3479 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003480 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3481 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003482 NamedChain, Chaining.size());
3483
3484 IndirectField->setAccess(AS);
3485 IndirectField->setImplicit();
3486 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003487
3488 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003489 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003490
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003491 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003492 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003493 }
3494 }
3495
3496 return Invalid;
3497}
3498
Douglas Gregorc4df4072010-04-19 22:54:31 +00003499/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3500/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003501/// illegal input values are mapped to SC_None.
3502static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003503StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3504 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3505 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3506 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003507 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003508 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003509 case DeclSpec::SCS_extern:
3510 if (DS.isExternInLinkageSpec())
3511 return SC_None;
3512 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003513 case DeclSpec::SCS_static: return SC_Static;
3514 case DeclSpec::SCS_auto: return SC_Auto;
3515 case DeclSpec::SCS_register: return SC_Register;
3516 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003517 // Illegal SCSs map to None: error reporting is up to the caller.
3518 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003519 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003520 }
3521 llvm_unreachable("unknown storage class specifier");
3522}
3523
Richard Smithab44d5b2013-12-10 08:25:00 +00003524static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3525 assert(Record->hasInClassInitializer());
3526
3527 for (DeclContext::decl_iterator I = Record->decls_begin(),
3528 E = Record->decls_end();
3529 I != E; ++I) {
3530 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3531 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3532 FD = IFD->getAnonField();
3533 if (FD && FD->hasInClassInitializer())
3534 return FD->getLocation();
3535 }
3536
3537 llvm_unreachable("couldn't find in-class initializer");
3538}
3539
3540static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3541 SourceLocation DefaultInitLoc) {
3542 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3543 return;
3544
3545 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3546 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3547}
3548
3549static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3550 CXXRecordDecl *AnonUnion) {
3551 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3552 return;
3553
3554 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3555}
3556
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003557/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003558/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003559/// (C++ [class.union]) and a C11 feature; anonymous structures
3560/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003561Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003562 AccessSpecifier AS,
3563 RecordDecl *Record,
3564 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003565 DeclContext *Owner = Record->getDeclContext();
3566
3567 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003568 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003569 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003570 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003571 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003572 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003573 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003574
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003575 // C and C++ require different kinds of checks for anonymous
3576 // structs/unions.
3577 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003578 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003579 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003580 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003581 if (Record->isUnion()) {
3582 // C++ [class.union]p6:
3583 // Anonymous unions declared in a named namespace or in the
3584 // global namespace shall be declared static.
3585 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3586 (isa<TranslationUnitDecl>(Owner) ||
3587 (isa<NamespaceDecl>(Owner) &&
3588 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003589 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3590 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003591
3592 // Recover by adding 'static'.
3593 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003594 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003595 }
3596 // C++ [class.union]p6:
3597 // A storage class is not allowed in a declaration of an
3598 // anonymous union in a class scope.
3599 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3600 isa<RecordDecl>(Owner)) {
3601 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003602 diag::err_anonymous_union_with_storage_spec)
3603 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003604
3605 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003606 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3607 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003608 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003609 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003610 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003611
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003612 // Ignore const/volatile/restrict qualifiers.
3613 if (DS.getTypeQualifiers()) {
3614 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3615 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003616 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003617 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3618 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003619 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003620 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003621 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003622 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3623 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003624 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003625 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003626 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003627 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003628 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3629 Diag(DS.getAtomicSpecLoc(),
3630 diag::ext_anonymous_struct_union_qualified)
3631 << Record->isUnion() << "_Atomic"
3632 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003633
3634 DS.ClearTypeQualifiers();
3635 }
3636
Mike Stump11289f42009-09-09 15:08:12 +00003637 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003638 // The member-specification of an anonymous union shall only
3639 // define non-static data members. [Note: nested types and
3640 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003641 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3642 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003643 Mem != MemEnd; ++Mem) {
3644 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3645 // C++ [class.union]p3:
3646 // An anonymous union shall not have private or protected
3647 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003648 assert(FD->getAccess() != AS_none);
3649 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003650 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3651 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3652 Invalid = true;
3653 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003654
Alexis Hunt97ab5542011-05-16 22:41:40 +00003655 // C++ [class.union]p1
3656 // An object of a class with a non-trivial constructor, a non-trivial
3657 // copy constructor, a non-trivial destructor, or a non-trivial copy
3658 // assignment operator cannot be a member of a union, nor can an
3659 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003660 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003661 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003662 } else if ((*Mem)->isImplicit()) {
3663 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00003664 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3665 // This is a type that showed up in an
3666 // elaborated-type-specifier inside the anonymous struct or
3667 // union, but which actually declares a type outside of the
3668 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003669 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3670 if (!MemRecord->isAnonymousStructOrUnion() &&
3671 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003672 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003673 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003674 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3675 << (int)Record->isUnion();
3676 else {
3677 // This is a nested type declaration.
3678 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3679 << (int)Record->isUnion();
3680 Invalid = true;
3681 }
Richard Smith254d2662013-01-28 00:54:05 +00003682 } else {
3683 // This is an anonymous type definition within another anonymous type.
3684 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3685 // not part of standard C++.
3686 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003687 diag::ext_anonymous_record_with_anonymous_type)
3688 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003689 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00003690 } else if (isa<AccessSpecDecl>(*Mem)) {
3691 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003692 } else {
3693 // We have something that isn't a non-static data
3694 // member. Complain about it.
3695 unsigned DK = diag::err_anonymous_record_bad_member;
3696 if (isa<TypeDecl>(*Mem))
3697 DK = diag::err_anonymous_record_with_type;
3698 else if (isa<FunctionDecl>(*Mem))
3699 DK = diag::err_anonymous_record_with_function;
3700 else if (isa<VarDecl>(*Mem))
3701 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003702
3703 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003704 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003705 DK == diag::err_anonymous_record_with_type)
3706 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003707 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003708 else {
3709 Diag((*Mem)->getLocation(), DK)
3710 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003711 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003712 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003713 }
3714 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003715
3716 // C++11 [class.union]p8 (DR1460):
3717 // At most one variant member of a union may have a
3718 // brace-or-equal-initializer.
3719 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3720 Owner->isRecord())
3721 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3722 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003723 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003724
3725 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003726 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003727 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003728 Invalid = true;
3729 }
3730
John McCallfa2d6922009-10-22 23:31:08 +00003731 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003732 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003733 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003734 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003735
Mike Stump11289f42009-09-09 15:08:12 +00003736 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003737 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003738 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003739 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003740 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003741 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003742 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003743 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003744 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003745 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003746 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003747 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003748 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003749 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003750 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003751 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003752 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003753 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003754 // mutable can only appear on non-static class members, so it's always
3755 // an error here
3756 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3757 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003758 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003759 }
3760
Abramo Bagnaradff19302011-03-08 08:55:46 +00003761 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003762 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003763 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003764 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003765 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003766
3767 // Default-initialize the implicit variable. This initialization will be
3768 // trivial in almost all cases, except if a union member has an in-class
3769 // initializer:
3770 // union { int n = 0; };
3771 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003772 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003773 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003774
Richard Smithab44d5b2013-12-10 08:25:00 +00003775 // Mark this as an anonymous struct/union type.
3776 Record->setAnonymousStructOrUnion(true);
3777
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003778 // Add the anonymous struct/union object to the current
3779 // context. We'll be referencing this object when we refer to one of
3780 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003781 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003782
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003783 // Inject the members of the anonymous struct/union into the owning
3784 // context and into the identifier resolver chain for name lookup
3785 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003786 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003787 Chain.push_back(Anon);
3788
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003789 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3790 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003791 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003792
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003793 if (Invalid)
3794 Anon->setInvalidDecl();
3795
John McCall48871652010-08-21 09:40:31 +00003796 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003797}
3798
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003799/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3800/// Microsoft C anonymous structure.
3801/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3802/// Example:
3803///
3804/// struct A { int a; };
3805/// struct B { struct A; int b; };
3806///
3807/// void foo() {
3808/// B var;
3809/// var.a = 3;
3810/// }
3811///
3812Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3813 RecordDecl *Record) {
3814
3815 // If there is no Record, get the record via the typedef.
3816 if (!Record)
3817 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3818
3819 // Mock up a declarator.
3820 Declarator Dc(DS, Declarator::TypeNameContext);
3821 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3822 assert(TInfo && "couldn't build declarator info for anonymous struct");
3823
3824 // Create a declaration for this anonymous struct.
3825 NamedDecl* Anon = FieldDecl::Create(Context,
3826 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003827 DS.getLocStart(),
3828 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003829 /*IdentifierInfo=*/0,
3830 Context.getTypeDeclType(Record),
3831 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003832 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003833 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003834 Anon->setImplicit();
3835
3836 // Add the anonymous struct object to the current context.
3837 CurContext->addDecl(Anon);
3838
3839 // Inject the members of the anonymous struct into the current
3840 // context and into the identifier resolver chain for name lookup
3841 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003842 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003843 Chain.push_back(Anon);
3844
Nico Weberf8bb3de2012-02-01 00:41:00 +00003845 RecordDecl *RecordDef = Record->getDefinition();
3846 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3847 RecordDef, AS_none,
3848 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003849 Anon->setInvalidDecl();
3850
3851 return Anon;
3852}
Steve Naroff2fea1392007-09-02 02:04:30 +00003853
Douglas Gregor92751d42008-11-17 22:58:34 +00003854/// GetNameForDeclarator - Determine the full declaration name for the
3855/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003856DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003857 return GetNameFromUnqualifiedId(D.getName());
3858}
3859
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003860/// \brief Retrieves the declaration name from a parsed unqualified-id.
3861DeclarationNameInfo
3862Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3863 DeclarationNameInfo NameInfo;
3864 NameInfo.setLoc(Name.StartLocation);
3865
Douglas Gregor7861a802009-11-03 01:35:08 +00003866 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003867
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003868 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003869 case UnqualifiedId::IK_Identifier:
3870 NameInfo.setName(Name.Identifier);
3871 NameInfo.setLoc(Name.StartLocation);
3872 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003873
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003874 case UnqualifiedId::IK_OperatorFunctionId:
3875 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3876 Name.OperatorFunctionId.Operator));
3877 NameInfo.setLoc(Name.StartLocation);
3878 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3879 = Name.OperatorFunctionId.SymbolLocations[0];
3880 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3881 = Name.EndLocation.getRawEncoding();
3882 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003883
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003884 case UnqualifiedId::IK_LiteralOperatorId:
3885 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3886 Name.Identifier));
3887 NameInfo.setLoc(Name.StartLocation);
3888 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3889 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003890
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003891 case UnqualifiedId::IK_ConversionFunctionId: {
3892 TypeSourceInfo *TInfo;
3893 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3894 if (Ty.isNull())
3895 return DeclarationNameInfo();
3896 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3897 Context.getCanonicalType(Ty)));
3898 NameInfo.setLoc(Name.StartLocation);
3899 NameInfo.setNamedTypeInfo(TInfo);
3900 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003901 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003902
3903 case UnqualifiedId::IK_ConstructorName: {
3904 TypeSourceInfo *TInfo;
3905 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3906 if (Ty.isNull())
3907 return DeclarationNameInfo();
3908 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3909 Context.getCanonicalType(Ty)));
3910 NameInfo.setLoc(Name.StartLocation);
3911 NameInfo.setNamedTypeInfo(TInfo);
3912 return NameInfo;
3913 }
3914
3915 case UnqualifiedId::IK_ConstructorTemplateId: {
3916 // In well-formed code, we can only have a constructor
3917 // template-id that refers to the current context, so go there
3918 // to find the actual type being constructed.
3919 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3920 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3921 return DeclarationNameInfo();
3922
3923 // Determine the type of the class being constructed.
3924 QualType CurClassType = Context.getTypeDeclType(CurClass);
3925
3926 // FIXME: Check two things: that the template-id names the same type as
3927 // CurClassType, and that the template-id does not occur when the name
3928 // was qualified.
3929
3930 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3931 Context.getCanonicalType(CurClassType)));
3932 NameInfo.setLoc(Name.StartLocation);
3933 // FIXME: should we retrieve TypeSourceInfo?
3934 NameInfo.setNamedTypeInfo(0);
3935 return NameInfo;
3936 }
3937
3938 case UnqualifiedId::IK_DestructorName: {
3939 TypeSourceInfo *TInfo;
3940 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3941 if (Ty.isNull())
3942 return DeclarationNameInfo();
3943 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3944 Context.getCanonicalType(Ty)));
3945 NameInfo.setLoc(Name.StartLocation);
3946 NameInfo.setNamedTypeInfo(TInfo);
3947 return NameInfo;
3948 }
3949
3950 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003951 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003952 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3953 return Context.getNameForTemplate(TName, TNameLoc);
3954 }
3955
3956 } // switch (Name.getKind())
3957
David Blaikie83d382b2011-09-23 05:06:16 +00003958 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003959}
3960
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003961static QualType getCoreType(QualType Ty) {
3962 do {
3963 if (Ty->isPointerType() || Ty->isReferenceType())
3964 Ty = Ty->getPointeeType();
3965 else if (Ty->isArrayType())
3966 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3967 else
3968 return Ty.withoutLocalFastQualifiers();
3969 } while (true);
3970}
3971
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003972/// hasSimilarParameters - Determine whether the C++ functions Declaration
3973/// and Definition have "nearly" matching parameters. This heuristic is
3974/// used to improve diagnostics in the case where an out-of-line function
3975/// definition doesn't match any declaration within the class or namespace.
3976/// Also sets Params to the list of indices to the parameters that differ
3977/// between the declaration and the definition. If hasSimilarParameters
3978/// returns true and Params is empty, then all of the parameters match.
3979static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003980 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003981 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003982 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003983 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003984 if (Declaration->param_size() != Definition->param_size())
3985 return false;
3986 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3987 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3988 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3989
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003990 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00003991 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003992 continue;
3993
3994 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3995 QualType DefParamBaseTy = getCoreType(DefParamTy);
3996 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3997 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3998
3999 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4000 (DeclTyName && DeclTyName == DefTyName))
4001 Params.push_back(Idx);
4002 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004003 return false;
4004 }
4005
4006 return true;
4007}
4008
John McCall99b2fe52010-04-29 23:50:39 +00004009/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4010/// declarator needs to be rebuilt in the current instantiation.
4011/// Any bits of declarator which appear before the name are valid for
4012/// consideration here. That's specifically the type in the decl spec
4013/// and the base type in any member-pointer chunks.
4014static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4015 DeclarationName Name) {
4016 // The types we specifically need to rebuild are:
4017 // - typenames, typeofs, and decltypes
4018 // - types which will become injected class names
4019 // Of course, we also need to rebuild any type referencing such a
4020 // type. It's safest to just say "dependent", but we call out a
4021 // few cases here.
4022
4023 DeclSpec &DS = D.getMutableDeclSpec();
4024 switch (DS.getTypeSpecType()) {
4025 case DeclSpec::TST_typename:
4026 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004027 case DeclSpec::TST_underlyingType:
4028 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004029 // Grab the type from the parser.
4030 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004031 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004032 if (T.isNull() || !T->isDependentType()) break;
4033
4034 // Make sure there's a type source info. This isn't really much
4035 // of a waste; most dependent types should have type source info
4036 // attached already.
4037 if (!TSI)
4038 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4039
4040 // Rebuild the type in the current instantiation.
4041 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4042 if (!TSI) return true;
4043
4044 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004045 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4046 DS.UpdateTypeRep(LocType);
4047 break;
4048 }
4049
Richard Smith1620ebd2012-10-01 20:35:07 +00004050 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004051 case DeclSpec::TST_typeofExpr: {
4052 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004053 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004054 if (Result.isInvalid()) return true;
4055 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004056 break;
4057 }
4058
4059 default:
4060 // Nothing to do for these decl specs.
4061 break;
4062 }
4063
4064 // It doesn't matter what order we do this in.
4065 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4066 DeclaratorChunk &Chunk = D.getTypeObject(I);
4067
4068 // The only type information in the declarator which can come
4069 // before the declaration name is the base type of a member
4070 // pointer.
4071 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4072 continue;
4073
4074 // Rebuild the scope specifier in-place.
4075 CXXScopeSpec &SS = Chunk.Mem.Scope();
4076 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4077 return true;
4078 }
4079
4080 return false;
4081}
4082
Anders Carlsson1052fd72011-07-04 16:28:17 +00004083Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004084 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004085 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004086
4087 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004088 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004089 Dcl->setTopLevelDeclInObjCContainer();
4090
4091 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004092}
4093
Richard Smithdda56e42011-04-15 14:24:37 +00004094/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4095/// If T is the name of a class, then each of the following shall have a
4096/// name different from T:
4097/// - every static data member of class T;
4098/// - every member function of class T
4099/// - every member of class T that is itself a type;
4100/// \returns true if the declaration name violates these rules.
4101bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4102 DeclarationNameInfo NameInfo) {
4103 DeclarationName Name = NameInfo.getName();
4104
4105 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4106 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4107 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4108 return true;
4109 }
4110
4111 return false;
4112}
Douglas Gregor31feb332012-03-17 23:06:31 +00004113
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004114/// \brief Diagnose a declaration whose declarator-id has the given
4115/// nested-name-specifier.
4116///
4117/// \param SS The nested-name-specifier of the declarator-id.
4118///
4119/// \param DC The declaration context to which the nested-name-specifier
4120/// resolves.
4121///
4122/// \param Name The name of the entity being declared.
4123///
4124/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004125///
4126/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004127bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004128 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004129 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004130 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004131 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004132 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004133
4134 // If the user provided a superfluous scope specifier that refers back to the
4135 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004136 //
4137 // class X {
4138 // void X::f();
4139 // };
Richard Smitha2302242013-12-05 07:51:02 +00004140 //
4141 // Note, it was once ill-formed to give redundant qualification in all
4142 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004143 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004144 if (Cur->isRecord()) {
4145 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4146 : diag::err_member_extra_qualification)
4147 << Name << FixItHint::CreateRemoval(SS.getRange());
4148 SS.clear();
4149 } else {
4150 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4151 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004152 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004153 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004154
4155 // Check whether the qualifying scope encloses the scope of the original
4156 // declaration.
4157 if (!Cur->Encloses(DC)) {
4158 if (Cur->isRecord())
4159 Diag(Loc, diag::err_member_qualification)
4160 << Name << SS.getRange();
4161 else if (isa<TranslationUnitDecl>(DC))
4162 Diag(Loc, diag::err_invalid_declarator_global_scope)
4163 << Name << SS.getRange();
4164 else if (isa<FunctionDecl>(Cur))
4165 Diag(Loc, diag::err_invalid_declarator_in_function)
4166 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004167 else if (isa<BlockDecl>(Cur))
4168 Diag(Loc, diag::err_invalid_declarator_in_block)
4169 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004170 else
4171 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004172 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004173
Douglas Gregor31feb332012-03-17 23:06:31 +00004174 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004175 }
4176
4177 if (Cur->isRecord()) {
4178 // Cannot qualify members within a class.
4179 Diag(Loc, diag::err_member_qualification)
4180 << Name << SS.getRange();
4181 SS.clear();
4182
4183 // C++ constructors and destructors with incorrect scopes can break
4184 // our AST invariants by having the wrong underlying types. If
4185 // that's the case, then drop this declaration entirely.
4186 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4187 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4188 !Context.hasSameType(Name.getCXXNameType(),
4189 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4190 return true;
4191
4192 return false;
4193 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004194
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004195 // C++11 [dcl.meaning]p1:
4196 // [...] "The nested-name-specifier of the qualified declarator-id shall
4197 // not begin with a decltype-specifer"
4198 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4199 while (SpecLoc.getPrefix())
4200 SpecLoc = SpecLoc.getPrefix();
4201 if (dyn_cast_or_null<DecltypeType>(
4202 SpecLoc.getNestedNameSpecifier()->getAsType()))
4203 Diag(Loc, diag::err_decltype_in_declarator)
4204 << SpecLoc.getTypeLoc().getSourceRange();
4205
Douglas Gregor31feb332012-03-17 23:06:31 +00004206 return false;
4207}
4208
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004209NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4210 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004211 // TODO: consider using NameInfo for diagnostic.
4212 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4213 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004214
Chris Lattner02c04392007-07-25 00:24:17 +00004215 // All of these full declarators require an identifier. If it doesn't have
4216 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004217 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004218 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004219 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004220 diag::err_declarator_need_ident)
4221 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004222 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004223 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4224 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004225
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004226 // The scope passed in may not be a decl scope. Zip up the scope tree until
4227 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004228 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004229 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004230 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004231
John McCall99b2fe52010-04-29 23:50:39 +00004232 DeclContext *DC = CurContext;
4233 if (D.getCXXScopeSpec().isInvalid())
4234 D.setInvalidType();
4235 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004236 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4237 UPPC_DeclarationQualifier))
4238 return 0;
4239
John McCall99b2fe52010-04-29 23:50:39 +00004240 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4241 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004242 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004243 // If we could not compute the declaration context, it's because the
4244 // declaration context is dependent but does not refer to a class,
4245 // class template, or class template partial specialization. Complain
4246 // and return early, to avoid the coming semantic disaster.
4247 Diag(D.getIdentifierLoc(),
4248 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004249 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004250 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004251 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004252 }
John McCall99b2fe52010-04-29 23:50:39 +00004253 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004254
John McCall99b2fe52010-04-29 23:50:39 +00004255 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004256 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004257 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004258
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004259 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4260 Diag(D.getIdentifierLoc(),
4261 diag::err_member_def_undefined_record)
4262 << Name << DC << D.getCXXScopeSpec().getRange();
4263 D.setInvalidType();
4264 } else if (!D.getDeclSpec().isFriendSpecified()) {
4265 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4266 Name, D.getIdentifierLoc())) {
4267 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004268 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004269
4270 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004271 }
John McCall99b2fe52010-04-29 23:50:39 +00004272 }
4273
4274 // Check whether we need to rebuild the type of the given
4275 // declaration in the current instantiation.
4276 if (EnteringContext && IsDependentContext &&
4277 TemplateParamLists.size() != 0) {
4278 ContextRAII SavedContext(*this, DC);
4279 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4280 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004281 }
4282 }
Richard Smithdda56e42011-04-15 14:24:37 +00004283
4284 if (DiagnoseClassNameShadow(DC, NameInfo))
4285 // If this is a typedef, we'll end up spewing multiple diagnostics.
4286 // Just return early; it's safer.
4287 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4288 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004289
John McCall8cb7bdf2010-06-04 23:28:52 +00004290 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4291 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004292
Douglas Gregor506bd562010-12-13 22:49:22 +00004293 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4294 UPPC_DeclarationType))
4295 D.setInvalidType();
4296
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004297 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004298 ForRedeclaration);
4299
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004300 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004301 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004302 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004303 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004304
4305 // If the declaration we're planning to build will be a function
4306 // or object with linkage, then look for another declaration with
4307 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004308 //
4309 // If the declaration we're planning to build will be declared with
4310 // external linkage in the translation unit, create any builtin with
4311 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004312 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4313 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004314 else if (CurContext->isFunctionOrMethod() &&
4315 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4316 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004317 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004318 CreateBuiltins =
4319 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4320 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4321 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4322 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004323
4324 if (IsLinkageLookup)
4325 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004326
Richard Smith1c34fb72013-08-13 18:18:50 +00004327 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004328 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004329 LookupQualifiedName(Previous, DC);
4330
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004331 // C++ [dcl.meaning]p1:
4332 // When the declarator-id is qualified, the declaration shall refer to a
4333 // previously declared member of the class or namespace to which the
4334 // qualifier refers (or, in the case of a namespace, of an element of the
4335 // inline namespace set of that namespace (7.3.1)) or to a specialization
4336 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004337 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004338 // Note that we already checked the context above, and that we do not have
4339 // enough information to make sure that Previous contains the declaration
4340 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004341 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004342 // class X {
4343 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004344 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004345 // };
4346 //
Douglas Gregorad590502008-12-15 23:53:10 +00004347 // void X::f(int) { } // ill-formed
4348 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004349 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004350 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004351 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004352
4353 // C++ [dcl.meaning]p1:
4354 // [...] the member shall not merely have been introduced by a
4355 // using-declaration in the scope of the class or namespace nominated by
4356 // the nested-name-specifier of the declarator-id.
4357 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004358 }
4359
John McCall1f82f242009-11-18 22:49:29 +00004360 if (Previous.isSingleResult() &&
4361 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004362 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004363 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004364 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4365 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004366
Douglas Gregor5101c242008-12-05 18:15:24 +00004367 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004368 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004369 }
4370
Douglas Gregor83a586e2008-04-13 21:07:44 +00004371 // In C++, the previous declaration we find might be a tag type
4372 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004373 // tag type. Note that this does does not apply if we're declaring a
4374 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004375 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004376 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004377 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004378
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004379 // Check that there are no default arguments other than in the parameters
4380 // of a function declaration (C++ only).
4381 if (getLangOpts().CPlusPlus)
4382 CheckExtraCXXDefaultArguments(D);
4383
Nico Webercb4c7f42012-12-23 00:40:46 +00004384 NamedDecl *New;
4385
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004386 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004388 if (TemplateParamLists.size()) {
4389 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004390 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004391 }
Mike Stump11289f42009-09-09 15:08:12 +00004392
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004393 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004394 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004395 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004396 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004397 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004398 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004399 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4400 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004401 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004402
4403 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004404 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004406 // If this has an identifier and is not an invalid redeclaration or
4407 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004408 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004409 !(D.isRedeclaration() && New->isInvalidDecl())) {
4410 // Only make a locally-scoped extern declaration visible if it is the first
4411 // declaration of this entity. Qualified lookup for such an entity should
4412 // only find this declaration if there is no visible declaration of it.
4413 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4414 PushOnScopeChains(New, S, AddToContext);
4415 if (!AddToContext)
4416 CurContext->addHiddenDecl(New);
4417 }
Mike Stump11289f42009-09-09 15:08:12 +00004418
John McCall48871652010-08-21 09:40:31 +00004419 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004420}
4421
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004422/// Helper method to turn variable array types into constant array
4423/// types in certain situations which would otherwise be errors (for
4424/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004425static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4426 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004427 bool &SizeIsNegative,
4428 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004429 // This method tries to turn a variable array into a constant
4430 // array even when the size isn't an ICE. This is necessary
4431 // for compatibility with code that depends on gcc's buggy
4432 // constant expression folding, like struct {char x[(int)(char*)2];}
4433 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004434 Oversized = 0;
4435
4436 if (T->isDependentType())
4437 return QualType();
4438
John McCall8ccfcb52009-09-24 19:53:00 +00004439 QualifierCollector Qs;
4440 const Type *Ty = Qs.strip(T);
4441
4442 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004443 QualType Pointee = PTy->getPointeeType();
4444 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004445 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4446 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004447 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004448 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004449 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004450 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004451 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4452 QualType Inner = PTy->getInnerType();
4453 QualType FixedType =
4454 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4455 Oversized);
4456 if (FixedType.isNull()) return FixedType;
4457 FixedType = Context.getParenType(FixedType);
4458 return Qs.apply(Context, FixedType);
4459 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004460
4461 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004462 if (!VLATy)
4463 return QualType();
4464 // FIXME: We should probably handle this case
4465 if (VLATy->getElementType()->isVariablyModifiedType())
4466 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004467
Richard Smith42d3af92011-12-07 00:43:50 +00004468 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004469 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004470 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004471 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004472
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004473 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004474 if (Res.isSigned() && Res.isNegative()) {
4475 SizeIsNegative = true;
4476 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004477 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004478
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004479 // Check whether the array is too large to be addressed.
4480 unsigned ActiveSizeBits
4481 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4482 Res);
4483 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4484 Oversized = Res;
4485 return QualType();
4486 }
4487
4488 return Context.getConstantArrayType(VLATy->getElementType(),
4489 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004490}
4491
Abramo Bagnara341ab732012-11-08 14:44:42 +00004492static void
4493FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004494 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4495 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4496 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4497 DstPTL.getPointeeLoc());
4498 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004499 return;
4500 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004501 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4502 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4503 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4504 DstPTL.getInnerLoc());
4505 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4506 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004507 return;
4508 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004509 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4510 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4511 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4512 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004513 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004514 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4515 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4516 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004517}
4518
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004519/// Helper method to turn variable array types into constant array
4520/// types in certain situations which would otherwise be errors (for
4521/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004522static TypeSourceInfo*
4523TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4524 ASTContext &Context,
4525 bool &SizeIsNegative,
4526 llvm::APSInt &Oversized) {
4527 QualType FixedTy
4528 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4529 SizeIsNegative, Oversized);
4530 if (FixedTy.isNull())
4531 return 0;
4532 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4533 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4534 FixedTInfo->getTypeLoc());
4535 return FixedTInfo;
4536}
4537
Richard Smith78165b52013-01-10 23:43:47 +00004538/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004539/// that it can be found later for redeclarations. We include any extern "C"
4540/// declaration that is not visible in the translation unit here, not just
4541/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004542void
Richard Smith39b79682013-06-18 20:15:12 +00004543Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004544 if (!getLangOpts().CPlusPlus &&
4545 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4546 // Don't need to track declarations in the TU in C.
4547 return;
4548
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004549 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004550 // FIXME: There can be multiple such declarations if they are functions marked
4551 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004552 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004553}
4554
Richard Smith39b79682013-06-18 20:15:12 +00004555NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004556 if (ExternalSource) {
4557 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004558 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004559 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004560 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004561 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4562 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004563 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4564 if (Pos == LocallyScopedExternCDecls.end())
4565 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004566 }
4567 }
Richard Smith39b79682013-06-18 20:15:12 +00004568
4569 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004570 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004571}
4572
Eli Friedman574c7452009-04-07 19:37:57 +00004573/// \brief Diagnose function specifiers on a declaration of an identifier that
4574/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004575void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004576 // FIXME: We should probably indicate the identifier in question to avoid
4577 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004578 if (DS.isInlineSpecified())
4579 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004580 diag::err_inline_non_function);
4581
Richard Smithb1402ae2013-03-18 22:52:47 +00004582 if (DS.isVirtualSpecified())
4583 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004584 diag::err_virtual_non_function);
4585
Richard Smithb1402ae2013-03-18 22:52:47 +00004586 if (DS.isExplicitSpecified())
4587 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004588 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004589
Richard Smithb1402ae2013-03-18 22:52:47 +00004590 if (DS.isNoreturnSpecified())
4591 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004592 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004593}
4594
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004595NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004596Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004597 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004598 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4599 if (D.getCXXScopeSpec().isSet()) {
4600 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4601 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004602 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004603 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004604 DC = CurContext;
4605 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004606 }
4607
Richard Smithb1402ae2013-03-18 22:52:47 +00004608 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004609
Richard Smitha77a0a62011-08-15 21:04:07 +00004610 if (D.getDeclSpec().isConstexprSpecified())
4611 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4612 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004613
Douglas Gregord8f446f2010-07-13 06:37:01 +00004614 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4615 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4616 << D.getName().getSourceRange();
4617 return 0;
4618 }
4619
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004620 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004621 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004622
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004623 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004624 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004625
Richard Smith3f1b5d02011-05-05 21:57:07 +00004626 CheckTypedefForVariablyModifiedType(S, NewTD);
4627
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004628 bool Redeclaration = D.isRedeclaration();
4629 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4630 D.setRedeclaration(Redeclaration);
4631 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004632}
4633
Richard Smith3f1b5d02011-05-05 21:57:07 +00004634void
4635Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004636 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4637 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004638 // Note that variably modified types must be fixed before merging the decl so
4639 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004640 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4641 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004642 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004643 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004644
Chris Lattner9fecd742009-04-19 05:21:20 +00004645 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004646 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004647 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004648 TypeSourceInfo *FixedTInfo =
4649 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4650 SizeIsNegative,
4651 Oversized);
4652 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004653 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004654 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004655 } else {
4656 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004657 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004658 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004659 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004660 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004661 Diag(NewTD->getLocation(), diag::err_array_too_large)
4662 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004663 else
Richard Smithdda56e42011-04-15 14:24:37 +00004664 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004665 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004666 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004667 }
4668 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004669}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004670
Richard Smith3f1b5d02011-05-05 21:57:07 +00004671
4672/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4673/// declares a typedef-name, either using the 'typedef' type specifier or via
4674/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4675NamedDecl*
4676Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4677 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004678 // Merge the decl with the existing one if appropriate. If the decl is
4679 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004680 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4681 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004682 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004683 if (!Previous.empty()) {
4684 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004685 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004686 }
4687
Douglas Gregor27821ce2009-07-07 16:35:42 +00004688 // If this is the C FILE type, notify the AST context.
4689 if (IdentifierInfo *II = NewTD->getIdentifier())
4690 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004691 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004692 if (II->isStr("FILE"))
4693 Context.setFILEDecl(NewTD);
4694 else if (II->isStr("jmp_buf"))
4695 Context.setjmp_bufDecl(NewTD);
4696 else if (II->isStr("sigjmp_buf"))
4697 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004698 else if (II->isStr("ucontext_t"))
4699 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004700 }
4701
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004702 return NewTD;
4703}
4704
Douglas Gregor5d68a202009-02-24 19:23:27 +00004705/// \brief Determines whether the given declaration is an out-of-scope
4706/// previous declaration.
4707///
4708/// This routine should be invoked when name lookup has found a
4709/// previous declaration (PrevDecl) that is not in the scope where a
4710/// new declaration by the same name is being introduced. If the new
4711/// declaration occurs in a local scope, previous declarations with
4712/// linkage may still be considered previous declarations (C99
4713/// 6.2.2p4-5, C++ [basic.link]p6).
4714///
4715/// \param PrevDecl the previous declaration found by name
4716/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004717///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004718/// \param DC the context in which the new declaration is being
4719/// declared.
4720///
4721/// \returns true if PrevDecl is an out-of-scope previous declaration
4722/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004723static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004724isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4725 ASTContext &Context) {
4726 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004727 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004728
Douglas Gregoreddf4332009-02-24 20:03:32 +00004729 if (!PrevDecl->hasLinkage())
4730 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004731
David Blaikiebbafb8a2012-03-11 07:00:24 +00004732 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004733 // C++ [basic.link]p6:
4734 // If there is a visible declaration of an entity with linkage
4735 // having the same name and type, ignoring entities declared
4736 // outside the innermost enclosing namespace scope, the block
4737 // scope declaration declares that same entity and receives the
4738 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004739 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004740 if (!OuterContext->isFunctionOrMethod())
4741 // This rule only applies to block-scope declarations.
4742 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004743
4744 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4745 if (PrevOuterContext->isRecord())
4746 // We found a member function: ignore it.
4747 return false;
4748
4749 // Find the innermost enclosing namespace for the new and
4750 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004751 OuterContext = OuterContext->getEnclosingNamespaceContext();
4752 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004753
Douglas Gregorfcee9462010-08-27 22:55:10 +00004754 // The previous declaration is in a different namespace, so it
4755 // isn't the same function.
4756 if (!OuterContext->Equals(PrevOuterContext))
4757 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004758 }
4759
Douglas Gregor5d68a202009-02-24 19:23:27 +00004760 return true;
4761}
4762
John McCall3e11ebe2010-03-15 10:12:16 +00004763static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4764 CXXScopeSpec &SS = D.getCXXScopeSpec();
4765 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004766 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004767}
4768
John McCall31168b02011-06-15 23:02:42 +00004769bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4770 QualType type = decl->getType();
4771 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4772 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4773 // Various kinds of declaration aren't allowed to be __autoreleasing.
4774 unsigned kind = -1U;
4775 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4776 if (var->hasAttr<BlocksAttr>())
4777 kind = 0; // __block
4778 else if (!var->hasLocalStorage())
4779 kind = 1; // global
4780 } else if (isa<ObjCIvarDecl>(decl)) {
4781 kind = 3; // ivar
4782 } else if (isa<FieldDecl>(decl)) {
4783 kind = 2; // field
4784 }
4785
4786 if (kind != -1U) {
4787 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4788 << kind;
4789 }
4790 } else if (lifetime == Qualifiers::OCL_None) {
4791 // Try to infer lifetime.
4792 if (!type->isObjCLifetimeType())
4793 return false;
4794
4795 lifetime = type->getObjCARCImplicitLifetime();
4796 type = Context.getLifetimeQualifiedType(type, lifetime);
4797 decl->setType(type);
4798 }
4799
4800 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4801 // Thread-local variables cannot have lifetime.
4802 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004803 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004804 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004805 << var->getType();
4806 return true;
4807 }
4808 }
4809
4810 return false;
4811}
4812
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004813static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004814 // Ensure that an auto decl is deduced otherwise the checks below might cache
4815 // the wrong linkage.
4816 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4817
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004818 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004819 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004820 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004821 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4822 ND.dropAttr<WeakAttr>();
4823 }
4824 }
4825 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004826 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004827 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4828 ND.dropAttr<WeakRefAttr>();
4829 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004830 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004831
4832 // 'selectany' only applies to externally visible varable declarations.
4833 // It does not apply to functions.
4834 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4835 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4836 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4837 ND.dropAttr<SelectAnyAttr>();
4838 }
4839 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004840}
4841
John McCallc87d9722013-04-02 02:48:58 +00004842/// Given that we are within the definition of the given function,
4843/// will that definition behave like C99's 'inline', where the
4844/// definition is discarded except for optimization purposes?
4845static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4846 // Try to avoid calling GetGVALinkageForFunction.
4847
4848 // All cases of this require the 'inline' keyword.
4849 if (!FD->isInlined()) return false;
4850
4851 // This is only possible in C++ with the gnu_inline attribute.
4852 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4853 return false;
4854
4855 // Okay, go ahead and call the relatively-more-expensive function.
4856
4857#ifndef NDEBUG
4858 // AST quite reasonably asserts that it's working on a function
4859 // definition. We don't really have a way to tell it that we're
4860 // currently defining the function, so just lie to it in +Asserts
4861 // builds. This is an awful hack.
4862 FD->setLazyBody(1);
4863#endif
4864
4865 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4866
4867#ifndef NDEBUG
4868 FD->setLazyBody(0);
4869#endif
4870
4871 return isC99Inline;
4872}
4873
Richard Smithac974a32013-06-30 09:48:50 +00004874/// Determine whether a variable is extern "C" prior to attaching
4875/// an initializer. We can't just call isExternC() here, because that
4876/// will also compute and cache whether the declaration is externally
4877/// visible, which might change when we attach the initializer.
4878///
4879/// This can only be used if the declaration is known to not be a
4880/// redeclaration of an internal linkage declaration.
4881///
4882/// For instance:
4883///
4884/// auto x = []{};
4885///
4886/// Attaching the initializer here makes this declaration not externally
4887/// visible, because its type has internal linkage.
4888///
4889/// FIXME: This is a hack.
4890template<typename T>
4891static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4892 if (S.getLangOpts().CPlusPlus) {
4893 // In C++, the overloadable attribute negates the effects of extern "C".
4894 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4895 return false;
4896 }
4897 return D->isExternC();
4898}
4899
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004900static bool shouldConsiderLinkage(const VarDecl *VD) {
4901 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4902 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004903 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004904 if (DC->isFileContext())
4905 return true;
4906 if (DC->isRecord())
4907 return false;
4908 llvm_unreachable("Unexpected context");
4909}
4910
4911static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4912 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4913 if (DC->isFileContext() || DC->isFunctionOrMethod())
4914 return true;
4915 if (DC->isRecord())
4916 return false;
4917 llvm_unreachable("Unexpected context");
4918}
4919
Richard Smith541b38b2013-09-20 01:15:31 +00004920/// Adjust the \c DeclContext for a function or variable that might be a
4921/// function-local external declaration.
4922bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4923 if (!DC->isFunctionOrMethod())
4924 return false;
4925
4926 // If this is a local extern function or variable declared within a function
4927 // template, don't add it into the enclosing namespace scope until it is
4928 // instantiated; it might have a dependent type right now.
4929 if (DC->isDependentContext())
4930 return true;
4931
4932 // C++11 [basic.link]p7:
4933 // When a block scope declaration of an entity with linkage is not found to
4934 // refer to some other declaration, then that entity is a member of the
4935 // innermost enclosing namespace.
4936 //
4937 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4938 // semantically-enclosing namespace, not a lexically-enclosing one.
4939 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4940 DC = DC->getParent();
4941 return true;
4942}
4943
Larisse Voufo39a1e502013-08-06 01:03:05 +00004944NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004945Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004946 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004947 MultiTemplateParamsArg TemplateParamLists,
4948 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004949 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004950 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004951
Douglas Gregorc4df4072010-04-19 22:54:31 +00004952 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004953 VarDecl::StorageClass SC =
4954 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004955
Richard Smith541b38b2013-09-20 01:15:31 +00004956 DeclContext *OriginalDC = DC;
4957 bool IsLocalExternDecl = SC == SC_Extern &&
4958 adjustContextForLocalExternDecl(DC);
4959
Richard Smith5990db62013-04-15 08:33:22 +00004960 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004961 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4962 // half array type (unless the cl_khr_fp16 extension is enabled).
4963 if (Context.getBaseElementType(R)->isHalfType()) {
4964 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4965 D.setInvalidType();
4966 }
4967 }
4968
Douglas Gregorc4df4072010-04-19 22:54:31 +00004969 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004970 // mutable can only appear on non-static class members, so it's always
4971 // an error here
4972 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004973 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004974 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004975 }
John McCallc87d9722013-04-02 02:48:58 +00004976
Richard Smithf2c9afc2013-06-17 01:34:01 +00004977 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4978 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4979 D.getDeclSpec().getStorageClassSpecLoc())) {
4980 // In C++11, the 'register' storage class specifier is deprecated.
4981 // Suppress the warning in system macros, it's used in macros in some
4982 // popular C system headers, such as in glibc's htonl() macro.
4983 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4984 diag::warn_deprecated_register)
4985 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4986 }
4987
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004988 IdentifierInfo *II = Name.getAsIdentifierInfo();
4989 if (!II) {
4990 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00004991 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004992 return 0;
4993 }
4994
Richard Smithb1402ae2013-03-18 22:52:47 +00004995 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00004996
Douglas Gregor212cab32009-03-11 20:22:50 +00004997 if (!DC->isRecord() && S->getFnParent() == 0) {
4998 // C99 6.9p2: The storage-class specifiers auto and register shall not
4999 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005000 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005001 // If this is a register variable with an asm label specified, then this
5002 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005003 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005004 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5005 else
5006 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005007 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005008 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005009 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005010
David Blaikiebbafb8a2012-03-11 07:00:24 +00005011 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005012 // Set up the special work-group-local storage class for variables in the
5013 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005014 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005015 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005016 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005017
Guy Benyei61054192013-02-07 10:55:47 +00005018 // OpenCL v1.2 s6.9.b p4:
5019 // The sampler type cannot be used with the __local and __global address
5020 // space qualifiers.
5021 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5022 R.getAddressSpace() == LangAS::opencl_global)) {
5023 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5024 }
5025
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005026 // OpenCL 1.2 spec, p6.9 r:
5027 // The event type cannot be used to declare a program scope variable.
5028 // The event type cannot be used with the __local, __constant and __global
5029 // address space qualifiers.
5030 if (R->isEventT()) {
5031 if (S->getParent() == 0) {
5032 Diag(D.getLocStart(), diag::err_event_t_global_var);
5033 D.setInvalidType();
5034 }
5035
5036 if (R.getAddressSpace()) {
5037 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5038 D.setInvalidType();
5039 }
5040 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005041 }
5042
Larisse Voufo39a1e502013-08-06 01:03:05 +00005043 bool IsExplicitSpecialization = false;
5044 bool IsVariableTemplateSpecialization = false;
5045 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005046 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005047 VarDecl *NewVD = 0;
5048 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005049 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005050 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005051 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005052 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005053 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005054
5055 if (D.isInvalidType())
5056 NewVD->setInvalidDecl();
5057 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005058 bool Invalid = false;
5059
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005060 if (DC->isRecord() && !CurContext->isRecord()) {
5061 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005062 switch (SC) {
5063 case SC_None:
5064 break;
5065 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005066 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5067 diag::err_static_out_of_line)
5068 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005069 break;
5070 case SC_Auto:
5071 case SC_Register:
5072 case SC_Extern:
5073 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5074 // to names of variables declared in a block or to function parameters.
5075 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5076 // of class members
5077
5078 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5079 diag::err_storage_class_for_static_member)
5080 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5081 break;
5082 case SC_PrivateExtern:
5083 llvm_unreachable("C storage class in c++!");
5084 case SC_OpenCLWorkGroupLocal:
5085 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005086 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005087 }
5088
Richard Smith42973752012-02-16 20:41:22 +00005089 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005090 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5091 if (RD->isLocalClass())
5092 Diag(D.getIdentifierLoc(),
5093 diag::err_static_data_member_not_allowed_in_local_class)
5094 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005095
Richard Smith42973752012-02-16 20:41:22 +00005096 // C++98 [class.union]p1: If a union contains a static data member,
5097 // the program is ill-formed. C++11 drops this restriction.
5098 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005099 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005100 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005101 ? diag::warn_cxx98_compat_static_data_member_in_union
5102 : diag::ext_static_data_member_in_union) << Name;
5103 // We conservatively disallow static data members in anonymous structs.
5104 else if (!RD->getDeclName())
5105 Diag(D.getIdentifierLoc(),
5106 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005107 << Name << RD->isUnion();
5108 }
5109 }
5110
5111 // Match up the template parameter lists with the scope specifier, then
5112 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005113 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5114 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5115 D.getCXXScopeSpec(), TemplateParamLists,
5116 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005117
Richard Smithbeef3452014-01-16 23:39:20 +00005118 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5119 !TemplateParams) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005120 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5121
5122 // We have encountered something that the user meant to be a
5123 // specialization (because it has explicitly-specified template
5124 // arguments) but that was not introduced with a "template<>" (or had
5125 // too few of them).
5126 // FIXME: Differentiate between attempts for explicit instantiations
5127 // (starting with "template") and the rest.
5128 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5129 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5130 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5131 "template<> ");
Richard Smith72db5632014-01-25 21:32:06 +00005132 IsExplicitSpecialization = true;
Richard Smithbeef3452014-01-16 23:39:20 +00005133 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5134 SourceLocation(), 0, 0,
5135 SourceLocation());
5136 }
5137
5138 if (TemplateParams) {
5139 if (!TemplateParams->size() &&
5140 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5141 // There is an extraneous 'template<>' for this variable. Complain
5142 // about it, but allow the declaration of the variable.
5143 Diag(TemplateParams->getTemplateLoc(),
5144 diag::err_template_variable_noparams)
5145 << II
5146 << SourceRange(TemplateParams->getTemplateLoc(),
5147 TemplateParams->getRAngleLoc());
5148 TemplateParams = 0;
5149 } else {
5150 // Only C++1y supports variable templates (N3651).
5151 Diag(D.getIdentifierLoc(),
5152 getLangOpts().CPlusPlus1y
5153 ? diag::warn_cxx11_compat_variable_template
5154 : diag::ext_variable_template);
5155
5156 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5157 // This is an explicit specialization or a partial specialization.
5158 // FIXME: Check that we can declare a specialization here.
5159 IsVariableTemplateSpecialization = true;
5160 IsPartialSpecialization = TemplateParams->size() > 0;
5161 } else { // if (TemplateParams->size() > 0)
5162 // This is a template declaration.
5163 IsVariableTemplate = true;
5164
5165 // Check that we can declare a template here.
5166 if (CheckTemplateDeclScope(S, TemplateParams))
5167 return 0;
5168 }
5169 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005170 }
Mike Stump11289f42009-09-09 15:08:12 +00005171
Larisse Voufo39a1e502013-08-06 01:03:05 +00005172 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005173 SourceLocation TemplateKWLoc =
5174 TemplateParamLists.size() > 0
5175 ? TemplateParamLists[0]->getTemplateLoc()
5176 : SourceLocation();
5177 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005178 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005179 IsPartialSpecialization);
5180 if (Res.isInvalid())
5181 return 0;
5182 NewVD = cast<VarDecl>(Res.get());
5183 AddToScope = false;
5184 } else
5185 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5186 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005187
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005188 // If this is supposed to be a variable template, create it as such.
5189 if (IsVariableTemplate) {
5190 NewTemplate =
5191 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005192 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005193 NewVD->setDescribedVarTemplate(NewTemplate);
5194 }
5195
Richard Smithb2bc2e62011-02-21 20:05:19 +00005196 // If this decl has an auto type in need of deduction, make a note of the
5197 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005198 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005199 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005200
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005201 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005202 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005203 if (NewTemplate)
5204 NewTemplate->setInvalidDecl();
5205 }
Mike Stump11289f42009-09-09 15:08:12 +00005206
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005207 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005208
Richard Smith72db5632014-01-25 21:32:06 +00005209 // If we have any template parameter lists that don't directly belong to
5210 // the variable (matching the scope specifier), store them.
5211 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5212 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005213 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005214 Context, TemplateParamLists.size() - VDTemplateParamLists,
5215 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005216
Richard Smith6331c402012-02-13 22:16:19 +00005217 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005218 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005219 }
5220
Douglas Gregor41866812011-09-12 18:37:38 +00005221 // Set the lexical context. If the declarator has a C++ scope specifier, the
5222 // lexical context will be different from the semantic context.
5223 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005224 if (NewTemplate)
5225 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005226
Richard Smith541b38b2013-09-20 01:15:31 +00005227 if (IsLocalExternDecl)
5228 NewVD->setLocalExternDecl();
5229
Richard Smithb4a9e862013-04-12 22:46:28 +00005230 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005231 if (NewVD->hasLocalStorage()) {
5232 // C++11 [dcl.stc]p4:
5233 // When thread_local is applied to a variable of block scope the
5234 // storage-class-specifier static is implied if it does not appear
5235 // explicitly.
5236 // Core issue: 'static' is not implied if the variable is declared
5237 // 'extern'.
5238 if (SCSpec == DeclSpec::SCS_unspecified &&
5239 TSCS == DeclSpec::TSCS_thread_local &&
5240 DC->isFunctionOrMethod())
5241 NewVD->setTSCSpec(TSCS);
5242 else
5243 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5244 diag::err_thread_non_global)
5245 << DeclSpec::getSpecifierName(TSCS);
5246 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005247 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5248 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005249 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005250 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005251 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005252
John McCallc87d9722013-04-02 02:48:58 +00005253 // C99 6.7.4p3
5254 // An inline definition of a function with external linkage shall
5255 // not contain a definition of a modifiable object with static or
5256 // thread storage duration...
5257 // We only apply this when the function is required to be defined
5258 // elsewhere, i.e. when the function is not 'extern inline'. Note
5259 // that a local variable with thread storage duration still has to
5260 // be marked 'static'. Also note that it's possible to get these
5261 // semantics in C++ using __attribute__((gnu_inline)).
5262 if (SC == SC_Static && S->getFnParent() != 0 &&
5263 !NewVD->getType().isConstQualified()) {
5264 FunctionDecl *CurFD = getCurFunctionDecl();
5265 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5266 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5267 diag::warn_static_local_in_extern_inline);
5268 MaybeSuggestAddingStaticToDecl(CurFD);
5269 }
5270 }
5271
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005272 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005273 if (IsVariableTemplateSpecialization)
5274 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5275 << (IsPartialSpecialization ? 1 : 0)
5276 << FixItHint::CreateRemoval(
5277 D.getDeclSpec().getModulePrivateSpecLoc());
5278 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005279 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5280 << 2
5281 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005282 else if (NewVD->hasLocalStorage())
5283 Diag(NewVD->getLocation(), diag::err_module_private_local)
5284 << 0 << NewVD->getDeclName()
5285 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5286 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005287 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005288 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005289 if (NewTemplate)
5290 NewTemplate->setModulePrivate();
5291 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005292 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005293
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005294 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005295 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005296
Richard Smith848e1f12013-02-01 08:12:08 +00005297 if (NewVD->hasAttrs())
5298 CheckAlignasUnderalignment(NewVD);
5299
Peter Collingbournec6b08572012-08-28 20:37:50 +00005300 if (getLangOpts().CUDA) {
5301 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5302 // storage [duration]."
5303 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005304 (NewVD->hasAttr<CUDASharedAttr>() ||
5305 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005306 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005307 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005308 }
5309
John McCall31168b02011-06-15 23:02:42 +00005310 // In auto-retain/release, infer strong retension for variables of
5311 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005312 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005313 NewVD->setInvalidDecl();
5314
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005315 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005316 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005317 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005318 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005319 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005320 if (S->getFnParent() != 0) {
5321 switch (SC) {
5322 case SC_None:
5323 case SC_Auto:
5324 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5325 break;
5326 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005327 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005328 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5329 break;
5330 case SC_Static:
5331 case SC_Extern:
5332 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005333 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005334 break;
5335 }
5336 }
5337
5338 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005339 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005340 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5341 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5342 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5343 if (I != ExtnameUndeclaredIdentifiers.end()) {
5344 NewVD->addAttr(I->second);
5345 ExtnameUndeclaredIdentifiers.erase(I);
5346 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005347 }
5348
John McCalla2a3f7d2010-03-16 21:48:18 +00005349 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005350 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005351 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005352
John McCall1f82f242009-11-18 22:49:29 +00005353 // Don't consider existing declarations that are in a different
5354 // scope and are out-of-semantic-context declarations (if the new
5355 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005356 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5357 D.getCXXScopeSpec().isNotEmpty() ||
5358 IsExplicitSpecialization ||
5359 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005360
Richard Smith1c34fb72013-08-13 18:18:50 +00005361 // Check whether the previous declaration is in the same block scope. This
5362 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5363 if (getLangOpts().CPlusPlus &&
5364 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5365 NewVD->setPreviousDeclInSameBlockScope(
5366 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005367 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005368
David Blaikiebbafb8a2012-03-11 07:00:24 +00005369 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005370 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5371 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005372 // If this is an explicit specialization of a static data member, check it.
5373 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5374 CheckMemberSpecialization(NewVD, Previous))
5375 NewVD->setInvalidDecl();
5376
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005377 // Merge the decl with the existing one if appropriate.
5378 if (!Previous.empty()) {
5379 if (Previous.isSingleResult() &&
5380 isa<FieldDecl>(Previous.getFoundDecl()) &&
5381 D.getCXXScopeSpec().isSet()) {
5382 // The user tried to define a non-static data member
5383 // out-of-line (C++ [dcl.meaning]p1).
5384 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5385 << D.getCXXScopeSpec().getRange();
5386 Previous.clear();
5387 NewVD->setInvalidDecl();
5388 }
5389 } else if (D.getCXXScopeSpec().isSet()) {
5390 // No previous declaration in the qualifying scope.
5391 Diag(D.getIdentifierLoc(), diag::err_no_member)
5392 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005393 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005394 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005395 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005396
Richard Smithbeef3452014-01-16 23:39:20 +00005397 if (!IsVariableTemplateSpecialization)
5398 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005399
Richard Smithbeef3452014-01-16 23:39:20 +00005400 if (NewTemplate) {
5401 VarTemplateDecl *PrevVarTemplate =
5402 NewVD->getPreviousDecl()
5403 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5404 : 0;
5405
5406 // Check the template parameter list of this declaration, possibly
5407 // merging in the template parameter list from the previous variable
5408 // template declaration.
5409 if (CheckTemplateParameterList(
5410 TemplateParams,
5411 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5412 : 0,
5413 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5414 DC->isDependentContext())
5415 ? TPC_ClassTemplateMember
5416 : TPC_VarTemplate))
5417 NewVD->setInvalidDecl();
5418
5419 // If we are providing an explicit specialization of a static variable
5420 // template, make a note of that.
5421 if (PrevVarTemplate &&
5422 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5423 PrevVarTemplate->setMemberSpecialization();
5424 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005425 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005426
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005427 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005428
Richard Smithac974a32013-06-30 09:48:50 +00005429 // If this is the first declaration of an extern C variable, update
5430 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005431 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005432 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005433 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005434
Reid Klecknerd8110b62013-09-10 20:14:30 +00005435 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005436 Decl *ManglingContextDecl;
5437 if (MangleNumberingContext *MCtx =
5438 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5439 ManglingContextDecl)) {
5440 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5441 }
5442 }
5443
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005444 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005445 if (NewVD->isInvalidDecl())
5446 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005447 ActOnDocumentableDecl(NewTemplate);
5448 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005449 }
5450
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005451 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005452}
5453
John McCalldf8b37c2010-03-22 09:20:08 +00005454/// \brief Diagnose variable or built-in function shadowing. Implements
5455/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005456///
John McCalldf8b37c2010-03-22 09:20:08 +00005457/// This method is called whenever a VarDecl is added to a "useful"
5458/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005459///
John McCall2d8c7602010-03-20 04:12:52 +00005460/// \param S the scope in which the shadowing name is being declared
5461/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005462///
John McCalldf8b37c2010-03-22 09:20:08 +00005463void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005464 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005465 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005466 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005467 return;
5468
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005469 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005470 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005471 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005472
5473 DeclContext *NewDC = D->getDeclContext();
5474
John McCall2d8c7602010-03-20 04:12:52 +00005475 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005476 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005477 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005478
John McCalla2a3f7d2010-03-16 21:48:18 +00005479 NamedDecl* ShadowedDecl = R.getFoundDecl();
5480 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5481 return;
5482
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005483 // Fields are not shadowed by variables in C++ static methods.
5484 if (isa<FieldDecl>(ShadowedDecl))
5485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5486 if (MD->isStatic())
5487 return;
5488
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005489 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5490 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005491 // For shadowing external vars, make sure that we point to the global
5492 // declaration, not a locally scoped extern declaration.
5493 for (VarDecl::redecl_iterator
5494 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5495 I != E; ++I)
5496 if (I->isFileVarDecl()) {
5497 ShadowedDecl = *I;
5498 break;
5499 }
5500 }
5501
5502 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5503
John McCall2d8c7602010-03-20 04:12:52 +00005504 // Only warn about certain kinds of shadowing for class members.
5505 if (NewDC && NewDC->isRecord()) {
5506 // In particular, don't warn about shadowing non-class members.
5507 if (!OldDC->isRecord())
5508 return;
5509
5510 // TODO: should we warn about static data members shadowing
5511 // static data members from base classes?
5512
5513 // TODO: don't diagnose for inaccessible shadowed members.
5514 // This is hard to do perfectly because we might friend the
5515 // shadowing context, but that's just a false negative.
5516 }
5517
5518 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005519 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005520 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005521 if (isa<FieldDecl>(ShadowedDecl))
5522 Kind = 3; // field
5523 else
5524 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005525 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005526 Kind = 1; // global
5527 else
5528 Kind = 0; // local
5529
John McCall2d8c7602010-03-20 04:12:52 +00005530 DeclarationName Name = R.getLookupName();
5531
John McCalla2a3f7d2010-03-16 21:48:18 +00005532 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005533 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5534 return;
John McCall2d8c7602010-03-20 04:12:52 +00005535 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005536 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5537}
5538
John McCalldf8b37c2010-03-22 09:20:08 +00005539/// \brief Check -Wshadow without the advantage of a previous lookup.
5540void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005541 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005542 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005543 return;
5544
John McCalldf8b37c2010-03-22 09:20:08 +00005545 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5546 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5547 LookupName(R, S);
5548 CheckShadow(S, D, R);
5549}
5550
Richard Smithac974a32013-06-30 09:48:50 +00005551/// Check for conflict between this global or extern "C" declaration and
5552/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005553template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005554static bool checkGlobalOrExternCConflict(
5555 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5556 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5557 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005558
Richard Smithac974a32013-06-30 09:48:50 +00005559 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5560 // The common case: this global doesn't conflict with any extern "C"
5561 // declaration.
5562 return false;
5563 }
5564
5565 if (Prev) {
5566 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5567 // Both the old and new declarations have C language linkage. This is a
5568 // redeclaration.
5569 Previous.clear();
5570 Previous.addDecl(Prev);
5571 return true;
5572 }
5573
5574 // This is a global, non-extern "C" declaration, and there is a previous
5575 // non-global extern "C" declaration. Diagnose if this is a variable
5576 // declaration.
5577 if (!isa<VarDecl>(ND))
5578 return false;
5579 } else {
5580 // The declaration is extern "C". Check for any declaration in the
5581 // translation unit which might conflict.
5582 if (IsGlobal) {
5583 // We have already performed the lookup into the translation unit.
5584 IsGlobal = false;
5585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5586 I != E; ++I) {
5587 if (isa<VarDecl>(*I)) {
5588 Prev = *I;
5589 break;
5590 }
5591 }
5592 } else {
5593 DeclContext::lookup_result R =
5594 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5595 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5596 I != E; ++I) {
5597 if (isa<VarDecl>(*I)) {
5598 Prev = *I;
5599 break;
5600 }
5601 // FIXME: If we have any other entity with this name in global scope,
5602 // the declaration is ill-formed, but that is a defect: it breaks the
5603 // 'stat' hack, for instance. Only variables can have mangled name
5604 // clashes with extern "C" declarations, so only they deserve a
5605 // diagnostic.
5606 }
5607 }
5608
5609 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005610 return false;
5611 }
5612
Richard Smithac974a32013-06-30 09:48:50 +00005613 // Use the first declaration's location to ensure we point at something which
5614 // is lexically inside an extern "C" linkage-spec.
5615 assert(Prev && "should have found a previous declaration to diagnose");
5616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005617 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005618 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005619 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005620
5621 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5622 << IsGlobal << ND;
5623 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5624 << IsGlobal;
5625 return false;
5626}
5627
5628/// Apply special rules for handling extern "C" declarations. Returns \c true
5629/// if we have found that this is a redeclaration of some prior entity.
5630///
5631/// Per C++ [dcl.link]p6:
5632/// Two declarations [for a function or variable] with C language linkage
5633/// with the same name that appear in different scopes refer to the same
5634/// [entity]. An entity with C language linkage shall not be declared with
5635/// the same name as an entity in global scope.
5636template<typename T>
5637static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5638 LookupResult &Previous) {
5639 if (!S.getLangOpts().CPlusPlus) {
5640 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005641 // variable declared in function scope. We don't need this in C++, because
5642 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005643 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5644 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5645 Previous.clear();
5646 Previous.addDecl(Prev);
5647 return true;
5648 }
5649 }
5650 return false;
5651 }
5652
5653 // A declaration in the translation unit can conflict with an extern "C"
5654 // declaration.
5655 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5656 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5657
5658 // An extern "C" declaration can conflict with a declaration in the
5659 // translation unit or can be a redeclaration of an extern "C" declaration
5660 // in another scope.
5661 if (isIncompleteDeclExternC(S,ND))
5662 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5663
5664 // Neither global nor extern "C": nothing to do.
5665 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005666}
5667
Richard Smith27d807c2013-04-30 13:56:41 +00005668void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005669 // If the decl is already known invalid, don't check it.
5670 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005671 return;
Mike Stump11289f42009-09-09 15:08:12 +00005672
Abramo Bagnara341ab732012-11-08 14:44:42 +00005673 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5674 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005675
Richard Smith27d807c2013-04-30 13:56:41 +00005676 // Defer checking an 'auto' type until its initializer is attached.
5677 if (T->isUndeducedType())
5678 return;
5679
John McCall8b07ec22010-05-15 11:32:37 +00005680 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005681 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5682 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005683 T = Context.getObjCObjectPointerType(T);
5684 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005685 }
Mike Stump11289f42009-09-09 15:08:12 +00005686
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005687 // Emit an error if an address space was applied to decl with local storage.
5688 // This includes arrays of objects with address space qualifiers, but not
5689 // automatic variables that point to other address spaces.
5690 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005691 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005692 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005693 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005694 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005695 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005696
Tanya Lattner713eef42013-04-05 20:14:50 +00005697 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5698 // __constant address space.
5699 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5700 && T.getAddressSpace() != LangAS::opencl_constant
5701 && !T->isSamplerT()){
5702 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5703 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005704 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005705 }
5706
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005707 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5708 // scope.
5709 if ((getLangOpts().OpenCLVersion >= 120)
5710 && NewVD->isStaticLocal()) {
5711 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5712 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005713 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005714 }
5715
Mike Stumpca5ae662009-04-14 00:57:29 +00005716 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005717 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005718 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005719 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005720 else {
5721 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005722 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005723 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005724 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005725
Chris Lattner9fecd742009-04-19 05:21:20 +00005726 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005727 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005728 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005729 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005730
Chris Lattner9fecd742009-04-19 05:21:20 +00005731 if ((isVM && NewVD->hasLinkage()) ||
5732 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005733 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005734 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005735 TypeSourceInfo *FixedTInfo =
5736 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5737 SizeIsNegative, Oversized);
5738 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005739 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005740 // FIXME: This won't give the correct result for
5741 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005742 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005743
Anders Carlsson6c885802009-02-28 21:56:50 +00005744 if (NewVD->isFileVarDecl())
5745 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005746 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005747 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005748 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005749 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005750 else
5751 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005752 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005753 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005754 return;
Mike Stump11289f42009-09-09 15:08:12 +00005755 }
5756
Abramo Bagnara341ab732012-11-08 14:44:42 +00005757 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005758 if (NewVD->isFileVarDecl())
5759 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5760 else
5761 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005762 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005763 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005764 }
Mike Stump11289f42009-09-09 15:08:12 +00005765
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005766 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005767 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005768 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005769 }
5770
David Majnemer0ffa3312013-05-29 00:56:45 +00005771 if (T->isVoidType()) {
5772 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5773 // of objects and functions.
5774 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5775 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5776 << T;
5777 NewVD->setInvalidDecl();
5778 return;
5779 }
Richard Smith27d807c2013-04-30 13:56:41 +00005780 }
5781
5782 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5783 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5784 NewVD->setInvalidDecl();
5785 return;
5786 }
5787
5788 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5789 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5790 NewVD->setInvalidDecl();
5791 return;
5792 }
5793
5794 if (NewVD->isConstexpr() && !T->isDependentType() &&
5795 RequireLiteralType(NewVD->getLocation(), T,
5796 diag::err_constexpr_var_non_literal)) {
5797 // Can't perform this check until the type is deduced.
5798 NewVD->setInvalidDecl();
5799 return;
5800 }
5801}
5802
5803/// \brief Perform semantic checking on a newly-created variable
5804/// declaration.
5805///
5806/// This routine performs all of the type-checking required for a
5807/// variable declaration once it has been built. It is used both to
5808/// check variables after they have been parsed and their declarators
5809/// have been translated into a declaration, and to check variables
5810/// that have been instantiated from a template.
5811///
5812/// Sets NewVD->isInvalidDecl() if an error was encountered.
5813///
5814/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005815bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005816 CheckVariableDeclarationType(NewVD);
5817
5818 // If the decl is already known invalid, don't check it.
5819 if (NewVD->isInvalidDecl())
5820 return false;
5821
John McCallb65e8fe2013-04-01 18:34:28 +00005822 // If we did not find anything by this name, look for a non-visible
5823 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005824 if (Previous.empty() &&
5825 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005826 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005827
Douglas Gregor3552dab2013-01-09 00:47:56 +00005828 // Filter out any non-conflicting previous declarations.
5829 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5830
John McCall1f82f242009-11-18 22:49:29 +00005831 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005832 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005833 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005834 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005835 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005836}
5837
Douglas Gregor36d1b142009-10-06 17:59:45 +00005838/// \brief Data used with FindOverriddenMethod
5839struct FindOverriddenMethodData {
5840 Sema *S;
5841 CXXMethodDecl *Method;
5842};
5843
5844/// \brief Member lookup function that determines whether a given C++
5845/// method overrides a method in a base class, to be used with
5846/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005847static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005848 CXXBasePath &Path,
5849 void *UserData) {
5850 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005851
Douglas Gregor36d1b142009-10-06 17:59:45 +00005852 FindOverriddenMethodData *Data
5853 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005854
5855 DeclarationName Name = Data->Method->getDeclName();
5856
5857 // FIXME: Do we care about other names here too?
5858 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005859 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005860 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5861 CanQualType CT = Data->S->Context.getCanonicalType(T);
5862
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005863 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005864 }
5865
5866 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005867 !Path.Decls.empty();
5868 Path.Decls = Path.Decls.slice(1)) {
5869 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005870 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5871 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005872 return true;
5873 }
5874 }
5875
5876 return false;
5877}
5878
David Blaikie7e414262012-10-17 00:47:58 +00005879namespace {
5880 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5881}
5882/// \brief Report an error regarding overriding, along with any relevant
5883/// overriden methods.
5884///
5885/// \param DiagID the primary error to report.
5886/// \param MD the overriding method.
5887/// \param OEK which overrides to include as notes.
5888static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5889 OverrideErrorKind OEK = OEK_All) {
5890 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5891 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5892 E = MD->end_overridden_methods();
5893 I != E; ++I) {
5894 // This check (& the OEK parameter) could be replaced by a predicate, but
5895 // without lambdas that would be overkill. This is still nicer than writing
5896 // out the diag loop 3 times.
5897 if ((OEK == OEK_All) ||
5898 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5899 (OEK == OEK_Deleted && (*I)->isDeleted()))
5900 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5901 }
5902}
5903
Sebastian Redld5b24532009-11-18 21:51:29 +00005904/// AddOverriddenMethods - See if a method overrides any in the base classes,
5905/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005906bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005907 // Look for virtual methods in base classes that this method might override.
5908 CXXBasePaths Paths;
5909 FindOverriddenMethodData Data;
5910 Data.Method = MD;
5911 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005912 bool hasDeletedOverridenMethods = false;
5913 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005914 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005915 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5916 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5917 E = Paths.found_decls_end(); I != E; ++I) {
5918 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005919 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005920 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005921 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005922 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005923 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005924 hasDeletedOverridenMethods |= OldMD->isDeleted();
5925 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005926 AddedAny = true;
5927 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005928 }
5929 }
5930 }
David Blaikie7e414262012-10-17 00:47:58 +00005931
5932 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5933 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5934 }
5935 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5936 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5937 }
5938
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005939 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005940}
5941
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005942namespace {
5943 // Struct for holding all of the extra arguments needed by
5944 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5945 struct ActOnFDArgs {
5946 Scope *S;
5947 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005948 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005949 bool AddToScope;
5950 };
5951}
5952
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005953namespace {
5954
5955// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005956// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005957class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5958 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005959 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5960 CXXRecordDecl *Parent)
5961 : Context(Context), OriginalFD(TypoFD),
5962 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005963
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005964 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005965 if (candidate.getEditDistance() == 0)
5966 return false;
5967
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005968 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005969 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5970 CDeclEnd = candidate.end();
5971 CDecl != CDeclEnd; ++CDecl) {
5972 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5973
5974 if (FD && !FD->hasBody() &&
5975 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5976 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5977 CXXRecordDecl *Parent = MD->getParent();
5978 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5979 return true;
5980 } else if (!ExpectedParent) {
5981 return true;
5982 }
5983 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005984 }
5985
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005986 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005987 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005988
5989 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005990 ASTContext &Context;
5991 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005992 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005993};
5994
5995}
5996
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005997/// \brief Generate diagnostics for an invalid function redeclaration.
5998///
5999/// This routine handles generating the diagnostic messages for an invalid
6000/// function redeclaration, including finding possible similar declarations
6001/// or performing typo correction if there are no previous declarations with
6002/// the same name.
6003///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006004/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006005/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006006static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006007 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006008 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006009 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006010 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006011 SmallVector<unsigned, 1> MismatchedParams;
6012 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006013 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006014 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006015 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6016 : diag::err_member_decl_does_not_match;
6017 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6018 IsLocalFriend ? Sema::LookupLocalFriendName
6019 : Sema::LookupOrdinaryName,
6020 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006021
6022 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006023 if (IsLocalFriend)
6024 SemaRef.LookupName(Prev, S);
6025 else
6026 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006027 assert(!Prev.isAmbiguous() &&
6028 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006029 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006030 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6031 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006032 if (!Prev.empty()) {
6033 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6034 Func != FuncEnd; ++Func) {
6035 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006036 if (FD &&
6037 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006038 // Add 1 to the index so that 0 can mean the mismatch didn't
6039 // involve a parameter
6040 unsigned ParamNum =
6041 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6042 NearMatches.push_back(std::make_pair(FD, ParamNum));
6043 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006044 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006045 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006046 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006047 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6048 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6049 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006050 // Set up everything for the call to ActOnFunctionDeclarator
6051 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6052 ExtraArgs.D.getIdentifierLoc());
6053 Previous.clear();
6054 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006055 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6056 CDeclEnd = Correction.end();
6057 CDecl != CDeclEnd; ++CDecl) {
6058 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006059 if (FD && !FD->hasBody() &&
6060 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006061 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006062 }
6063 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006064 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006065
6066 NamedDecl *Result;
6067 // Retry building the function declaration with the new previous
6068 // declarations, and with errors suppressed.
6069 {
6070 // Trap errors.
6071 Sema::SFINAETrap Trap(SemaRef);
6072
6073 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6074 // pieces need to verify the typo-corrected C++ declaration and hopefully
6075 // eliminate the need for the parameter pack ExtraArgs.
6076 Result = SemaRef.ActOnFunctionDeclarator(
6077 ExtraArgs.S, ExtraArgs.D,
6078 Correction.getCorrectionDecl()->getDeclContext(),
6079 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6080 ExtraArgs.AddToScope);
6081
6082 if (Trap.hasErrorOccurred())
6083 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006084 }
Richard Smithf9b15102013-08-17 00:46:16 +00006085
6086 if (Result) {
6087 // Determine which correction we picked.
6088 Decl *Canonical = Result->getCanonicalDecl();
6089 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6090 I != E; ++I)
6091 if ((*I)->getCanonicalDecl() == Canonical)
6092 Correction.setCorrectionDecl(*I);
6093
6094 SemaRef.diagnoseTypo(
6095 Correction,
6096 SemaRef.PDiag(IsLocalFriend
6097 ? diag::err_no_matching_local_friend_suggest
6098 : diag::err_member_decl_does_not_match_suggest)
6099 << Name << NewDC << IsDefinition);
6100 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006101 }
Richard Smithf9b15102013-08-17 00:46:16 +00006102
6103 // Pretend the typo correction never occurred
6104 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6105 ExtraArgs.D.getIdentifierLoc());
6106 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6107 Previous.clear();
6108 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006109 }
6110
Richard Smithf9b15102013-08-17 00:46:16 +00006111 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6112 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006113
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006114 bool NewFDisConst = false;
6115 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006116 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006117
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006118 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006119 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6120 NearMatch != NearMatchEnd; ++NearMatch) {
6121 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006122 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6123 bool FDisConst = MD && MD->isConst();
6124 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006125
Richard Smith541b38b2013-09-20 01:15:31 +00006126 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006127 if (unsigned Idx = NearMatch->second) {
6128 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006129 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6130 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006131 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6132 : diag::note_local_decl_close_param_match)
6133 << Idx << FDParam->getType()
6134 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006135 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006136 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006137 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006138 } else
Richard Smith114394f2013-08-09 04:35:01 +00006139 SemaRef.Diag(FD->getLocation(),
6140 IsMember ? diag::note_member_def_close_match
6141 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006142 }
Richard Smithf9b15102013-08-17 00:46:16 +00006143 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006144}
6145
David Blaikie30d15442011-10-19 22:56:21 +00006146static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6147 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006148 switch (D.getDeclSpec().getStorageClassSpec()) {
6149 default: llvm_unreachable("Unknown storage class!");
6150 case DeclSpec::SCS_auto:
6151 case DeclSpec::SCS_register:
6152 case DeclSpec::SCS_mutable:
6153 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6154 diag::err_typecheck_sclass_func);
6155 D.setInvalidType();
6156 break;
6157 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006158 case DeclSpec::SCS_extern:
6159 if (D.getDeclSpec().isExternInLinkageSpec())
6160 return SC_None;
6161 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006162 case DeclSpec::SCS_static: {
6163 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6164 // C99 6.7.1p5:
6165 // The declaration of an identifier for a function that has
6166 // block scope shall have no explicit storage-class specifier
6167 // other than extern
6168 // See also (C++ [dcl.stc]p4).
6169 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6170 diag::err_static_block_func);
6171 break;
6172 } else
6173 return SC_Static;
6174 }
6175 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6176 }
6177
6178 // No explicit storage class has already been returned
6179 return SC_None;
6180}
6181
6182static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6183 DeclContext *DC, QualType &R,
6184 TypeSourceInfo *TInfo,
6185 FunctionDecl::StorageClass SC,
6186 bool &IsVirtualOkay) {
6187 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6188 DeclarationName Name = NameInfo.getName();
6189
6190 FunctionDecl *NewFD = 0;
6191 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006192
David Blaikiebbafb8a2012-03-11 07:00:24 +00006193 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006194 // Determine whether the function was written with a
6195 // prototype. This true when:
6196 // - there is a prototype in the declarator, or
6197 // - the type R of the function is some kind of typedef or other reference
6198 // to a type name (which eventually refers to a function type).
6199 bool HasPrototype =
6200 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6201 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6202
David Blaikie30d15442011-10-19 22:56:21 +00006203 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006204 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006205 TInfo, SC, isInline,
6206 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006207 if (D.isInvalidType())
6208 NewFD->setInvalidDecl();
6209
6210 // Set the lexical context.
6211 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6212
6213 return NewFD;
6214 }
6215
6216 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6217 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6218
6219 // Check that the return type is not an abstract class type.
6220 // For record types, this is done by the AbstractClassUsageDiagnoser once
6221 // the class has been completely parsed.
6222 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006223 SemaRef.RequireNonAbstractType(
6224 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6225 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006226 D.setInvalidType();
6227
6228 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6229 // This is a C++ constructor declaration.
6230 assert(DC->isRecord() &&
6231 "Constructors can only be declared in a member context");
6232
6233 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6234 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006235 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006236 R, TInfo, isExplicit, isInline,
6237 /*isImplicitlyDeclared=*/false,
6238 isConstexpr);
6239
6240 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6241 // This is a C++ destructor declaration.
6242 if (DC->isRecord()) {
6243 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6244 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6245 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6246 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006247 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006248 NameInfo, R, TInfo, isInline,
6249 /*isImplicitlyDeclared=*/false);
6250
6251 // If the class is complete, then we now create the implicit exception
6252 // specification. If the class is incomplete or dependent, we can't do
6253 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006254 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006255 Record->getDefinition() && !Record->isBeingDefined() &&
6256 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6257 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6258 }
6259
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006260 // The Microsoft ABI requires that we perform the destructor body
6261 // checks (i.e. operator delete() lookup) at every declaration, as
6262 // any translation unit may need to emit a deleting destructor.
6263 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6264 !Record->isDependentType() && Record->getDefinition() &&
Hans Wennborge955e392013-12-17 17:49:22 +00006265 !Record->isBeingDefined() && !NewDD->isDeleted()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006266 SemaRef.CheckDestructor(NewDD);
6267 }
6268
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006269 IsVirtualOkay = true;
6270 return NewDD;
6271
6272 } else {
6273 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6274 D.setInvalidType();
6275
6276 // Create a FunctionDecl to satisfy the function definition parsing
6277 // code path.
6278 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006279 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006280 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006281 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006282 /*hasPrototype=*/true, isConstexpr);
6283 }
6284
6285 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6286 if (!DC->isRecord()) {
6287 SemaRef.Diag(D.getIdentifierLoc(),
6288 diag::err_conv_function_not_member);
6289 return 0;
6290 }
6291
6292 SemaRef.CheckConversionDeclarator(D, R, SC);
6293 IsVirtualOkay = true;
6294 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006295 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006296 R, TInfo, isInline, isExplicit,
6297 isConstexpr, SourceLocation());
6298
6299 } else if (DC->isRecord()) {
6300 // If the name of the function is the same as the name of the record,
6301 // then this must be an invalid constructor that has a return type.
6302 // (The parser checks for a return type and makes the declarator a
6303 // constructor if it has no return type).
6304 if (Name.getAsIdentifierInfo() &&
6305 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6306 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6307 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6308 << SourceRange(D.getIdentifierLoc());
6309 return 0;
6310 }
6311
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006312 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006313 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6314 cast<CXXRecordDecl>(DC),
6315 D.getLocStart(), NameInfo, R,
6316 TInfo, SC, isInline,
6317 isConstexpr, SourceLocation());
6318 IsVirtualOkay = !Ret->isStatic();
6319 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006320 } else {
6321 // Determine whether the function was written with a
6322 // prototype. This true when:
6323 // - we're in C++ (where every function has a prototype),
6324 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006325 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006326 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006327 true/*HasPrototype*/, isConstexpr);
6328 }
6329}
6330
Eli Friedman8f5e9832012-09-20 01:40:23 +00006331void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6332 // In C++, the empty parameter-type-list must be spelled "void"; a
6333 // typedef of void is not permitted.
6334 if (getLangOpts().CPlusPlus &&
6335 Param->getType().getUnqualifiedType() != Context.VoidTy) {
6336 bool IsTypeAlias = false;
6337 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6338 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6339 else if (const TemplateSpecializationType *TST =
6340 Param->getType()->getAs<TemplateSpecializationType>())
6341 IsTypeAlias = TST->isTypeAlias();
6342 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6343 << IsTypeAlias;
6344 }
6345}
6346
Matt Arsenaultefb38192013-07-23 01:23:36 +00006347enum OpenCLParamType {
6348 ValidKernelParam,
6349 PtrPtrKernelParam,
6350 PtrKernelParam,
6351 InvalidKernelParam,
6352 RecordKernelParam
6353};
6354
6355static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6356 if (PT->isPointerType()) {
6357 QualType PointeeType = PT->getPointeeType();
6358 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6359 }
6360
6361 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6362 // be used as builtin types.
6363
6364 if (PT->isImageType())
6365 return PtrKernelParam;
6366
6367 if (PT->isBooleanType())
6368 return InvalidKernelParam;
6369
6370 if (PT->isEventT())
6371 return InvalidKernelParam;
6372
6373 if (PT->isHalfType())
6374 return InvalidKernelParam;
6375
6376 if (PT->isRecordType())
6377 return RecordKernelParam;
6378
6379 return ValidKernelParam;
6380}
6381
6382static void checkIsValidOpenCLKernelParameter(
6383 Sema &S,
6384 Declarator &D,
6385 ParmVarDecl *Param,
6386 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6387 QualType PT = Param->getType();
6388
6389 // Cache the valid types we encounter to avoid rechecking structs that are
6390 // used again
6391 if (ValidTypes.count(PT.getTypePtr()))
6392 return;
6393
6394 switch (getOpenCLKernelParameterType(PT)) {
6395 case PtrPtrKernelParam:
6396 // OpenCL v1.2 s6.9.a:
6397 // A kernel function argument cannot be declared as a
6398 // pointer to a pointer type.
6399 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6400 D.setInvalidType();
6401 return;
6402
6403 // OpenCL v1.2 s6.9.k:
6404 // Arguments to kernel functions in a program cannot be declared with the
6405 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6406 // uintptr_t or a struct and/or union that contain fields declared to be
6407 // one of these built-in scalar types.
6408
6409 case InvalidKernelParam:
6410 // OpenCL v1.2 s6.8 n:
6411 // A kernel function argument cannot be declared
6412 // of event_t type.
6413 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6414 D.setInvalidType();
6415 return;
6416
6417 case PtrKernelParam:
6418 case ValidKernelParam:
6419 ValidTypes.insert(PT.getTypePtr());
6420 return;
6421
6422 case RecordKernelParam:
6423 break;
6424 }
6425
6426 // Track nested structs we will inspect
6427 SmallVector<const Decl *, 4> VisitStack;
6428
6429 // Track where we are in the nested structs. Items will migrate from
6430 // VisitStack to HistoryStack as we do the DFS for bad field.
6431 SmallVector<const FieldDecl *, 4> HistoryStack;
6432 HistoryStack.push_back((const FieldDecl *) 0);
6433
6434 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6435 VisitStack.push_back(PD);
6436
6437 assert(VisitStack.back() && "First decl null?");
6438
6439 do {
6440 const Decl *Next = VisitStack.pop_back_val();
6441 if (!Next) {
6442 assert(!HistoryStack.empty());
6443 // Found a marker, we have gone up a level
6444 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6445 ValidTypes.insert(Hist->getType().getTypePtr());
6446
6447 continue;
6448 }
6449
6450 // Adds everything except the original parameter declaration (which is not a
6451 // field itself) to the history stack.
6452 const RecordDecl *RD;
6453 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6454 HistoryStack.push_back(Field);
6455 RD = Field->getType()->castAs<RecordType>()->getDecl();
6456 } else {
6457 RD = cast<RecordDecl>(Next);
6458 }
6459
6460 // Add a null marker so we know when we've gone back up a level
6461 VisitStack.push_back((const Decl *) 0);
6462
6463 for (RecordDecl::field_iterator I = RD->field_begin(),
6464 E = RD->field_end(); I != E; ++I) {
6465 const FieldDecl *FD = *I;
6466 QualType QT = FD->getType();
6467
6468 if (ValidTypes.count(QT.getTypePtr()))
6469 continue;
6470
6471 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6472 if (ParamType == ValidKernelParam)
6473 continue;
6474
6475 if (ParamType == RecordKernelParam) {
6476 VisitStack.push_back(FD);
6477 continue;
6478 }
6479
6480 // OpenCL v1.2 s6.9.p:
6481 // Arguments to kernel functions that are declared to be a struct or union
6482 // do not allow OpenCL objects to be passed as elements of the struct or
6483 // union.
6484 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6485 S.Diag(Param->getLocation(),
6486 diag::err_record_with_pointers_kernel_param)
6487 << PT->isUnionType()
6488 << PT;
6489 } else {
6490 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6491 }
6492
6493 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6494 << PD->getDeclName();
6495
6496 // We have an error, now let's go back up through history and show where
6497 // the offending field came from
6498 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6499 E = HistoryStack.end(); I != E; ++I) {
6500 const FieldDecl *OuterField = *I;
6501 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6502 << OuterField->getType();
6503 }
6504
6505 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6506 << QT->isPointerType()
6507 << QT;
6508 D.setInvalidType();
6509 return;
6510 }
6511 } while (!VisitStack.empty());
6512}
6513
Mike Stump11289f42009-09-09 15:08:12 +00006514NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006515Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006516 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006517 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006518 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006519 QualType R = TInfo->getType();
6520
Zhongxing Xubece5d62009-01-16 01:13:29 +00006521 assert(R.getTypePtr()->isFunctionType());
6522
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006523 // TODO: consider using NameInfo for diagnostic.
6524 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6525 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006526 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006527
Richard Smithb4a9e862013-04-12 22:46:28 +00006528 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6530 diag::err_invalid_thread)
6531 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006532
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006533 if (D.isFirstDeclarationOfMember())
6534 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006535
Douglas Gregor513e63c2010-12-10 19:28:19 +00006536 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006537 FunctionTemplateDecl *FunctionTemplate = 0;
6538 bool isExplicitSpecialization = false;
6539 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006540
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006541 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006542 bool HasExplicitTemplateArgs = false;
6543 TemplateArgumentListInfo TemplateArgs;
6544
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006545 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006546
Richard Smith541b38b2013-09-20 01:15:31 +00006547 DeclContext *OriginalDC = DC;
6548 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6549
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006550 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6551 isVirtualOkay);
6552 if (!NewFD) return 0;
6553
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006554 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6555 NewFD->setTopLevelDeclInObjCContainer();
6556
Richard Smith541b38b2013-09-20 01:15:31 +00006557 // Set the lexical context. If this is a function-scope declaration, or has a
6558 // C++ scope specifier, or is the object of a friend declaration, the lexical
6559 // context will be different from the semantic context.
6560 NewFD->setLexicalDeclContext(CurContext);
6561
6562 if (IsLocalExternDecl)
6563 NewFD->setLocalExternDecl();
6564
David Blaikiebbafb8a2012-03-11 07:00:24 +00006565 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006566 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006567 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6568 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006569 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006570 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006571 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006572 // C++ [class.friend]p5
6573 // A function can be defined in a friend declaration of a
6574 // class . . . . Such a function is implicitly inline.
6575 NewFD->setImplicitlyInline();
6576 }
6577
John McCalldb632ac2012-09-25 07:32:39 +00006578 // If this is a method defined in an __interface, and is not a constructor
6579 // or an overloaded operator, then set the pure flag (isVirtual will already
6580 // return true).
6581 if (const CXXRecordDecl *Parent =
6582 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6583 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006584 NewFD->setPure(true);
6585 }
6586
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006587 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006588 isExplicitSpecialization = false;
6589 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006590 if (D.isInvalidType())
6591 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006592
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006593 // Match up the template parameter lists with the scope specifier, then
6594 // determine whether we have a template or a template specialization.
6595 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006596 if (TemplateParameterList *TemplateParams =
6597 MatchTemplateParametersToScopeSpecifier(
6598 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6599 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6600 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006601 if (TemplateParams->size() > 0) {
6602 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006603
Abramo Bagnara60804e12011-03-18 15:16:37 +00006604 // Check that we can declare a template here.
6605 if (CheckTemplateDeclScope(S, TemplateParams))
6606 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006607
Abramo Bagnara60804e12011-03-18 15:16:37 +00006608 // A destructor cannot be a template.
6609 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6610 Diag(NewFD->getLocation(), diag::err_destructor_template);
6611 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006612 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006613
6614 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006615 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006616 // now that we know what the current instantiation is.
6617 if (DC->isDependentContext()) {
6618 ContextRAII SavedContext(*this, DC);
6619 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6620 Invalid = true;
6621 }
6622
John McCall1f0479e2010-03-24 08:27:58 +00006623
Abramo Bagnara60804e12011-03-18 15:16:37 +00006624 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6625 NewFD->getLocation(),
6626 Name, TemplateParams,
6627 NewFD);
6628 FunctionTemplate->setLexicalDeclContext(CurContext);
6629 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6630
6631 // For source fidelity, store the other template param lists.
6632 if (TemplateParamLists.size() > 1) {
6633 NewFD->setTemplateParameterListsInfo(Context,
6634 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006635 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006636 }
6637 } else {
6638 // This is a function template specialization.
6639 isFunctionTemplateSpecialization = true;
6640 // For source fidelity, store all the template param lists.
6641 NewFD->setTemplateParameterListsInfo(Context,
6642 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006643 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006644
6645 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6646 if (isFriend) {
6647 // We want to remove the "template<>", found here.
6648 SourceRange RemoveRange = TemplateParams->getSourceRange();
6649
6650 // If we remove the template<> and the name is not a
6651 // template-id, we're actually silently creating a problem:
6652 // the friend declaration will refer to an untemplated decl,
6653 // and clearly the user wants a template specialization. So
6654 // we need to insert '<>' after the name.
6655 SourceLocation InsertLoc;
6656 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6657 InsertLoc = D.getName().getSourceRange().getEnd();
6658 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6659 }
6660
6661 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6662 << Name << RemoveRange
6663 << FixItHint::CreateRemoval(RemoveRange)
6664 << FixItHint::CreateInsertion(InsertLoc, "<>");
6665 }
6666 }
6667 }
6668 else {
6669 // All template param lists were matched against the scope specifier:
6670 // this is NOT (an explicit specialization of) a template.
6671 if (TemplateParamLists.size() > 0)
6672 // For source fidelity, store all the template param lists.
6673 NewFD->setTemplateParameterListsInfo(Context,
6674 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006675 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006676 }
6677
6678 if (Invalid) {
6679 NewFD->setInvalidDecl();
6680 if (FunctionTemplate)
6681 FunctionTemplate->setInvalidDecl();
6682 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006683
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006684 // C++ [dcl.fct.spec]p5:
6685 // The virtual specifier shall only be used in declarations of
6686 // nonstatic class member functions that appear within a
6687 // member-specification of a class declaration; see 10.3.
6688 //
6689 if (isVirtual && !NewFD->isInvalidDecl()) {
6690 if (!isVirtualOkay) {
6691 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6692 diag::err_virtual_non_function);
6693 } else if (!CurContext->isRecord()) {
6694 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006695 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6696 diag::err_virtual_out_of_class)
6697 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6698 } else if (NewFD->getDescribedFunctionTemplate()) {
6699 // C++ [temp.mem]p3:
6700 // A member function template shall not be virtual.
6701 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6702 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006703 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6704 } else {
6705 // Okay: Add virtual to the method.
6706 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006707 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006708
6709 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006710 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006711 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006712 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006713
Richard Smithc1564702013-11-15 02:58:23 +00006714 if (getLangOpts().CPlusPlus1y &&
6715 (NewFD->isDependentContext() ||
6716 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006717 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006718 // If the function template is referenced directly (for instance, as a
6719 // member of the current instantiation), pretend it has a dependent type.
6720 // This is not really justified by the standard, but is the only sane
6721 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006722 // FIXME: For a friend function, we have not marked the function as being
6723 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006724 const FunctionProtoType *FPT =
6725 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006726 QualType Result =
6727 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006728 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006729 FPT->getExtProtoInfo()));
6730 }
6731
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006732 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006733 // The inline specifier shall not appear on a block scope function
6734 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006735 if (isInline && !NewFD->isInvalidDecl()) {
6736 if (CurContext->isFunctionOrMethod()) {
6737 // 'inline' is not allowed on block scope function declaration.
6738 Diag(D.getDeclSpec().getInlineSpecLoc(),
6739 diag::err_inline_declaration_block_scope) << Name
6740 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6741 }
6742 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006743
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006744 // C++ [dcl.fct.spec]p6:
6745 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006746 // constructor or conversion function within its class definition;
6747 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006748 if (isExplicit && !NewFD->isInvalidDecl()) {
6749 if (!CurContext->isRecord()) {
6750 // 'explicit' was specified outside of the class.
6751 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6752 diag::err_explicit_out_of_class)
6753 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6754 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6755 !isa<CXXConversionDecl>(NewFD)) {
6756 // 'explicit' was specified on a function that wasn't a constructor
6757 // or conversion function.
6758 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6759 diag::err_explicit_non_ctor_or_conv_function)
6760 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6761 }
6762 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006763
Richard Smitha77a0a62011-08-15 21:04:07 +00006764 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006765 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006766 // are implicitly inline.
6767 NewFD->setImplicitlyInline();
6768
Richard Smith574f4f62013-01-14 05:37:29 +00006769 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006770 // be either constructors or to return a literal type. Therefore,
6771 // destructors cannot be declared constexpr.
6772 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006773 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006774 }
6775
Douglas Gregor26701a42011-09-09 02:06:17 +00006776 // If __module_private__ was specified, mark the function accordingly.
6777 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006778 if (isFunctionTemplateSpecialization) {
6779 SourceLocation ModulePrivateLoc
6780 = D.getDeclSpec().getModulePrivateSpecLoc();
6781 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6782 << 0
6783 << FixItHint::CreateRemoval(ModulePrivateLoc);
6784 } else {
6785 NewFD->setModulePrivate();
6786 if (FunctionTemplate)
6787 FunctionTemplate->setModulePrivate();
6788 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006789 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006790
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006791 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006792 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006793 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006794 FunctionTemplate->setAccess(AS_public);
6795 }
Richard Smith64017682013-07-17 23:53:16 +00006796 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006797 NewFD->setAccess(AS_public);
6798 }
6799
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006800 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006801 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6802 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006803 switch (D.getFunctionDefinitionKind()) {
6804 case FDK_Declaration:
6805 case FDK_Definition:
6806 break;
6807
6808 case FDK_Defaulted:
6809 NewFD->setDefaulted();
6810 break;
6811
6812 case FDK_Deleted:
6813 NewFD->setDeletedAsWritten();
6814 break;
6815 }
6816
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006817 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6818 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006819 // C++ [class.mfct]p2:
6820 // A member function may be defined (8.4) in its class definition, in
6821 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006822 NewFD->setImplicitlyInline();
6823 }
6824
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006825 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6826 !CurContext->isRecord()) {
6827 // C++ [class.static]p1:
6828 // A data or function member of a class may be declared static
6829 // in a class definition, in which case it is a static member of
6830 // the class.
6831
6832 // Complain about the 'static' specifier if it's on an out-of-line
6833 // member function definition.
6834 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6835 diag::err_static_out_of_line)
6836 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6837 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006838
6839 // C++11 [except.spec]p15:
6840 // A deallocation function with no exception-specification is treated
6841 // as if it were specified with noexcept(true).
6842 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6843 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6844 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006845 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006846 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6847 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006848 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006849 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006850 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006851 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006852
6853 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006854 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006855 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006856 isExplicitSpecialization ||
6857 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006858
Zhongxing Xubece5d62009-01-16 01:13:29 +00006859 // Handle GNU asm-label extension (encoded as an attribute).
6860 if (Expr *E = (Expr*) D.getAsmLabel()) {
6861 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006862 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006863 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006864 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006865 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6866 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6867 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6868 if (I != ExtnameUndeclaredIdentifiers.end()) {
6869 NewFD->addAttr(I->second);
6870 ExtnameUndeclaredIdentifiers.erase(I);
6871 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006872 }
6873
Chris Lattner9af40c12009-04-25 06:12:16 +00006874 // Copy the parameter declarations from the declarator D to the function
6875 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006876 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006877 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006878 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006879
Zhongxing Xubece5d62009-01-16 01:13:29 +00006880 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6881 // function that takes no arguments, not a function that takes a
6882 // single void argument.
6883 // We let through "const void" here because Sema::GetTypeForDeclarator
6884 // already checks for that case.
6885 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6886 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006887 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006888 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +00006889 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
Zhongxing Xubece5d62009-01-16 01:13:29 +00006890 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006891 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00006892 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006893 assert(Param->getDeclContext() != NewFD && "Was set before ?");
6894 Param->setDeclContext(NewFD);
6895 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00006896
6897 if (Param->isInvalidDecl())
6898 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00006899 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006900 }
Mike Stump11289f42009-09-09 15:08:12 +00006901
John McCall9dd450b2009-09-21 23:43:11 +00006902 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00006903 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00006904 // following example, we'll need to synthesize (unnamed)
6905 // parameters for use in the declaration.
6906 //
6907 // @code
6908 // typedef void fn(int);
6909 // fn f;
6910 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00006911
Chris Lattner47c0d002009-04-25 06:03:53 +00006912 // Synthesize a parameter for each argument type.
Alp Toker9cacbab2014-01-20 20:26:09 +00006913 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
6914 AE = FT->param_type_end();
6915 AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00006916 ParmVarDecl *Param =
6917 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00006918 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00006919 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006920 }
Chris Lattner49303b22009-04-25 18:38:18 +00006921 } else {
6922 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6923 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00006924 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00006925
Chris Lattner9af40c12009-04-25 06:12:16 +00006926 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00006927 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00006928
James Molloy6f8780b2012-02-29 10:24:19 +00006929 // Find all anonymous symbols defined during the declaration of this function
6930 // and add to NewFD. This lets us track decls such 'enum Y' in:
6931 //
6932 // void f(enum Y {AA} x) {}
6933 //
6934 // which would otherwise incorrectly end up in the translation unit scope.
6935 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6936 DeclsInPrototypeScope.clear();
6937
Richard Smithdebc59d2013-01-30 05:45:05 +00006938 if (D.getDeclSpec().isNoreturnSpecified())
6939 NewFD->addAttr(
6940 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00006941 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00006942
Richard Smith84208dc2012-03-13 05:56:40 +00006943 // Functions returning a variably modified type violate C99 6.7.5.2p2
6944 // because all functions have linkage.
6945 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00006946 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00006947 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6948 NewFD->setInvalidDecl();
6949 }
6950
Rafael Espindolac67f2232012-05-10 02:50:16 +00006951 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00006952 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00006953
Alp Toker314cc812014-01-25 16:55:45 +00006954 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006955 const CXXRecordDecl *Ret = RetType->isRecordType() ?
6956 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6957 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6958 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006959 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Benjamin Kramer9940a5d2013-10-16 16:21:04 +00006960 // Attach the attribute to the new decl. Don't apply the attribute if it
6961 // returns an instance of the class (e.g. assignment operators).
6962 if (!MD || MD->getParent() != Ret) {
Aaron Ballman36a53502014-01-16 13:03:14 +00006963 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain11370012012-11-13 21:23:31 +00006964 }
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00006965 }
6966
Joey Gouly16cb99d2014-01-06 11:26:18 +00006967 if (getLangOpts().OpenCL) {
6968 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6969 // type declaration will generate a compilation error.
6970 unsigned AddressSpace = RetType.getAddressSpace();
6971 if (AddressSpace == LangAS::opencl_local ||
6972 AddressSpace == LangAS::opencl_global ||
6973 AddressSpace == LangAS::opencl_constant) {
6974 Diag(NewFD->getLocation(),
6975 diag::err_opencl_return_value_with_address_space);
6976 NewFD->setInvalidDecl();
6977 }
6978 }
6979
David Blaikiebbafb8a2012-03-11 07:00:24 +00006980 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006981 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00006982 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00006983 if (!NewFD->isInvalidDecl() && NewFD->isMain())
6984 CheckMain(NewFD, D.getDeclSpec());
6985
David Majnemerc729b0b2013-09-16 22:44:20 +00006986 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6987 CheckMSVCRTEntryPoint(NewFD);
6988
David Majnemer027f9c42013-07-06 02:13:46 +00006989 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00006990 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6991 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00006992 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00006993 // Make graceful recovery from an invalid redeclaration.
6994 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006995 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006996 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6997 "previous declaration set still overloaded");
6998 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00006999 // C++11 [replacement.functions]p3:
7000 // The program's definitions shall not be specified as inline.
7001 //
7002 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7003 //
7004 // Suppress the diagnostic if the function is __attribute__((used)), since
7005 // that forces an external definition to be emitted.
7006 if (D.getDeclSpec().isInlineSpecified() &&
7007 NewFD->isReplaceableGlobalAllocationFunction() &&
7008 !NewFD->hasAttr<UsedAttr>())
7009 Diag(D.getDeclSpec().getInlineSpecLoc(),
7010 diag::ext_operator_new_delete_declared_inline)
7011 << NewFD->getDeclName();
7012
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007013 // If the declarator is a template-id, translate the parser's template
7014 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007015 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7016 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7017 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7018 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007019 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007020 TemplateId->NumArgs);
7021 translateTemplateArguments(TemplateArgsPtr,
7022 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007023
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007024 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007025
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007026 if (NewFD->isInvalidDecl()) {
7027 HasExplicitTemplateArgs = false;
7028 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007029 // Function template with explicit template arguments.
7030 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7031 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7032
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007033 HasExplicitTemplateArgs = false;
7034 } else if (!isFunctionTemplateSpecialization &&
7035 !D.getDeclSpec().isFriendSpecified()) {
7036 // We have encountered something that the user meant to be a
7037 // specialization (because it has explicitly-specified template
7038 // arguments) but that was not introduced with a "template<>" (or had
7039 // too few of them).
Larisse Voufo39a1e502013-08-06 01:03:05 +00007040 // FIXME: Differentiate between attempts for explicit instantiations
7041 // (starting with "template") and the rest.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007042 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7043 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7044 << FixItHint::CreateInsertion(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007045 D.getDeclSpec().getLocStart(),
David Blaikie30d15442011-10-19 22:56:21 +00007046 "template<> ");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007047 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00007048 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007049 // "friend void foo<>(int);" is an implicit specialization decl.
7050 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007051 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007052 } else if (isFriend && isFunctionTemplateSpecialization) {
7053 // This combination is only possible in a recovery case; the user
7054 // wrote something like:
7055 // template <> friend void foo(int);
7056 // which we're recovering from as if the user had written:
7057 // friend void foo<>(int);
7058 // Go ahead and fake up a template id.
7059 HasExplicitTemplateArgs = true;
7060 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7061 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007062 }
John McCallf7cfb222010-10-13 05:45:15 +00007063
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007064 // If it's a friend (and only if it's a friend), it's possible
7065 // that either the specialized function type or the specialized
7066 // template is dependent, and therefore matching will fail. In
7067 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007068 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007069 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007070 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7071 TemplateSpecializationType::anyDependentTemplateArguments(
7072 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7073 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007074 assert(HasExplicitTemplateArgs &&
7075 "friend function specialization without template args");
7076 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7077 Previous))
7078 NewFD->setInvalidDecl();
7079 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007080 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007081 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007082 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007083 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007084 diag::ext_function_specialization_in_class :
7085 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007086 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007087 } else if (CheckFunctionTemplateSpecialization(NewFD,
7088 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7089 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007090 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007091
7092 // C++ [dcl.stc]p1:
7093 // A storage-class-specifier shall not be specified in an explicit
7094 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007095 FunctionTemplateSpecializationInfo *Info =
7096 NewFD->getTemplateSpecializationInfo();
7097 if (Info && SC != SC_None) {
7098 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007099 Diag(NewFD->getLocation(),
7100 diag::err_explicit_specialization_inconsistent_storage_class)
7101 << SC
7102 << FixItHint::CreateRemoval(
7103 D.getDeclSpec().getStorageClassSpecLoc());
7104
7105 else
7106 Diag(NewFD->getLocation(),
7107 diag::ext_explicit_specialization_storage_class)
7108 << FixItHint::CreateRemoval(
7109 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007110 }
7111
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007112 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7113 if (CheckMemberSpecialization(NewFD, Previous))
7114 NewFD->setInvalidDecl();
7115 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007116
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007117 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007118 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007119 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7120 CheckMain(NewFD, D.getDeclSpec());
7121
David Majnemerc729b0b2013-09-16 22:44:20 +00007122 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7123 CheckMSVCRTEntryPoint(NewFD);
7124
Nico Weber7607fce2013-12-21 00:49:51 +00007125 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007126 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7127 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007128 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007129
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007130 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007131 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7132 "previous declaration set still overloaded");
7133
7134 NamedDecl *PrincipalDecl = (FunctionTemplate
7135 ? cast<NamedDecl>(FunctionTemplate)
7136 : NewFD);
7137
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007138 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007139 AccessSpecifier Access = AS_public;
7140 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007141 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007142
7143 NewFD->setAccess(Access);
7144 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007145 }
7146
7147 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7148 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7149 PrincipalDecl->setNonMemberOperator();
7150
7151 // If we have a function template, check the template parameter
7152 // list. This will check and merge default template arguments.
7153 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007154 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007155 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007156 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
David Blaikie30d15442011-10-19 22:56:21 +00007157 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007158 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007159 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007160 ? TPC_FriendFunctionTemplateDefinition
7161 : TPC_FriendFunctionTemplate)
7162 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007163 DC && DC->isRecord() &&
7164 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007165 ? TPC_ClassTemplateMember
7166 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007167 }
7168
7169 if (NewFD->isInvalidDecl()) {
7170 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007171 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007172 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007173 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007174 // Fake up an access specifier if it's supposed to be a class member.
7175 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7176 NewFD->setAccess(AS_public);
7177
7178 // Qualified decls generally require a previous declaration.
7179 if (D.getCXXScopeSpec().isSet()) {
7180 // ...with the major exception of templated-scope or
7181 // dependent-scope friend declarations.
7182
7183 // TODO: we currently also suppress this check in dependent
7184 // contexts because (1) the parameter depth will be off when
7185 // matching friend templates and (2) we might actually be
7186 // selecting a friend based on a dependent factor. But there
7187 // are situations where these conditions don't apply and we
7188 // can actually do this check immediately.
7189 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007190 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007191 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7192 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007193 // ignore these
7194 } else {
7195 // The user tried to provide an out-of-line definition for a
7196 // function that is a member of a class or namespace, but there
7197 // was no such member function declared (C++ [class.mfct]p2,
7198 // C++ [namespace.memdef]p2). For example:
7199 //
7200 // class X {
7201 // void f() const;
7202 // };
7203 //
7204 // void X::f() { } // ill-formed
7205 //
7206 // Complain about this problem, and attempt to suggest close
7207 // matches (e.g., those that differ only in cv-qualifiers and
7208 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007209
Richard Smith114394f2013-08-09 04:35:01 +00007210 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7211 *this, Previous, NewFD, ExtraArgs, false, 0)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007212 AddToScope = ExtraArgs.AddToScope;
7213 return Result;
7214 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007215 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007216
7217 // Unqualified local friend declarations are required to resolve
7218 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007219 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007220 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7221 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007222 AddToScope = ExtraArgs.AddToScope;
7223 return Result;
7224 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007225 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007226
Richard Smitha2302242013-12-05 07:51:02 +00007227 } else if (!D.isFunctionDefinition() &&
7228 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007229 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007230 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007231 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007232 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007233 // Note that this is not the case for explicit specializations of
7234 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007235 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7236 // extension for compatibility with old SWIG code which likes to
7237 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007238 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7239 << D.getCXXScopeSpec().getRange();
7240 }
7241 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007242
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007243 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007244 checkAttributesAfterMerging(*this, *NewFD);
7245
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007246 AddKnownFunctionAttributes(NewFD);
7247
Douglas Gregor72609052010-08-06 13:50:58 +00007248 if (NewFD->hasAttr<OverloadableAttr>() &&
7249 !NewFD->getType()->getAs<FunctionProtoType>()) {
7250 Diag(NewFD->getLocation(),
7251 diag::err_attribute_overloadable_no_prototype)
7252 << NewFD;
7253
7254 // Turn this into a variadic function with no parameters.
7255 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007256 FunctionProtoType::ExtProtoInfo EPI(
7257 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007258 EPI.Variadic = true;
7259 EPI.ExtInfo = FT->getExtInfo();
7260
Alp Toker314cc812014-01-25 16:55:45 +00007261 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007262 NewFD->setType(R);
7263 }
7264
Eli Friedman570024a2010-08-05 06:57:20 +00007265 // If there's a #pragma GCC visibility in scope, and this isn't a class
7266 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007267 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007268 AddPushedVisibilityAttribute(NewFD);
7269
John McCall32f5fe12011-09-30 05:12:12 +00007270 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7271 // marking the function.
7272 AddCFAuditedAttribute(NewFD);
7273
Richard Smithac974a32013-06-30 09:48:50 +00007274 // If this is the first declaration of an extern C variable, update
7275 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007276 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007277 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007278 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007279
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007280 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007281 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007282
David Blaikiebbafb8a2012-03-11 07:00:24 +00007283 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007284 if (FunctionTemplate) {
7285 if (NewFD->isInvalidDecl())
7286 FunctionTemplate->setInvalidDecl();
7287 return FunctionTemplate;
7288 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007289 }
Mike Stump11289f42009-09-09 15:08:12 +00007290
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007291 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007292 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7293 if ((getLangOpts().OpenCLVersion >= 120)
7294 && (SC == SC_Static)) {
7295 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7296 D.setInvalidType();
7297 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007298
7299 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007300 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007301 Diag(D.getIdentifierLoc(),
7302 diag::err_expected_kernel_void_return_type);
7303 D.setInvalidType();
7304 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007305
7306 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007307 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7308 PE = NewFD->param_end(); PI != PE; ++PI) {
Joey Gouly39989da2013-01-29 10:54:06 +00007309 ParmVarDecl *Param = *PI;
Matt Arsenaultefb38192013-07-23 01:23:36 +00007310 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007311 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007312 }
7313
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007314 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007315
David Blaikiebbafb8a2012-03-11 07:00:24 +00007316 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007317 if (IdentifierInfo *II = NewFD->getIdentifier())
7318 if (!NewFD->isInvalidDecl() &&
7319 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7320 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007321 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007322 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7323
7324 Context.setcudaConfigureCallDecl(NewFD);
7325 }
7326 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007327
7328 // Here we have an function template explicit specialization at class scope.
7329 // The actually specialization will be postponed to template instatiation
7330 // time via the ClassScopeFunctionSpecializationDecl node.
7331 if (isDependentClassScopeExplicitSpecialization) {
7332 ClassScopeFunctionSpecializationDecl *NewSpec =
7333 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007334 Context, CurContext, SourceLocation(),
7335 cast<CXXMethodDecl>(NewFD),
7336 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007337 CurContext->addDecl(NewSpec);
7338 AddToScope = false;
7339 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007340
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007341 return NewFD;
7342}
7343
7344/// \brief Perform semantic checking of a new function declaration.
7345///
7346/// Performs semantic analysis of the new function declaration
7347/// NewFD. This routine performs all semantic checking that does not
7348/// require the actual declarator involved in the declaration, and is
7349/// used both for the declaration of functions as they are parsed
7350/// (called via ActOnDeclarator) and for the declaration of functions
7351/// that have been instantiated via C++ template instantiation (called
7352/// via InstantiateDecl).
7353///
James Dennettffad8b72012-06-22 08:10:18 +00007354/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007355/// an explicit specialization of the previous declaration.
7356///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007357/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007358///
James Dennettffad8b72012-06-22 08:10:18 +00007359/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007360bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007361 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007362 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007363 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7364 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007365
Richard Smith1c34fb72013-08-13 18:18:50 +00007366 // Determine whether the type of this function should be merged with
7367 // a previous visible declaration. This never happens for functions in C++,
7368 // and always happens in C if the previous declaration was visible.
7369 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7370 !Previous.isShadowed();
7371
Douglas Gregor3552dab2013-01-09 00:47:56 +00007372 // Filter out any non-conflicting previous declarations.
7373 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7374
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007375 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007376 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007377
Douglas Gregore62c0a42009-02-24 01:23:02 +00007378 // Merge or overload the declaration with an existing declaration of
7379 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007380 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007381 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007382 // a declaration that requires merging. If it's an overload,
7383 // there's no more work to do here; we'll just add the new
7384 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007385 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007386 NamedDecl *Candidate = Previous.getFoundDecl();
7387 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7388 Redeclaration = true;
7389 OldDecl = Candidate;
7390 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007391 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007392 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7393 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007394 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007395 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007396 break;
7397
7398 case Ovl_NonFunction:
7399 Redeclaration = true;
7400 break;
7401
7402 case Ovl_Overload:
7403 Redeclaration = false;
7404 break;
John McCall1f82f242009-11-18 22:49:29 +00007405 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007406
David Blaikiebbafb8a2012-03-11 07:00:24 +00007407 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007408 // If a function name is overloadable in C, then every function
7409 // with that name must be marked "overloadable".
7410 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7411 << Redeclaration << NewFD;
7412 NamedDecl *OverloadedDecl = 0;
7413 if (Redeclaration)
7414 OverloadedDecl = OldDecl;
7415 else if (!Previous.empty())
7416 OverloadedDecl = Previous.getRepresentativeDecl();
7417 if (OverloadedDecl)
7418 Diag(OverloadedDecl->getLocation(),
7419 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007420 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007421 }
John McCall1f82f242009-11-18 22:49:29 +00007422 }
Richard Smith574f4f62013-01-14 05:37:29 +00007423 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007424
Richard Smithac974a32013-06-30 09:48:50 +00007425 // Check for a previous extern "C" declaration with this name.
7426 if (!Redeclaration &&
7427 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7428 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7429 if (!Previous.empty()) {
7430 // This is an extern "C" declaration with the same name as a previous
7431 // declaration, and thus redeclares that entity...
7432 Redeclaration = true;
7433 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007434 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007435
7436 // ... except in the presence of __attribute__((overloadable)).
7437 if (OldDecl->hasAttr<OverloadableAttr>()) {
7438 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7439 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7440 << Redeclaration << NewFD;
7441 Diag(Previous.getFoundDecl()->getLocation(),
7442 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007443 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007444 }
7445 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7446 Redeclaration = false;
7447 OldDecl = 0;
7448 }
7449 }
7450 }
7451 }
7452
Richard Smith574f4f62013-01-14 05:37:29 +00007453 // C++11 [dcl.constexpr]p8:
7454 // A constexpr specifier for a non-static member function that is not
7455 // a constructor declares that member function to be const.
7456 //
7457 // This needs to be delayed until we know whether this is an out-of-line
7458 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007459 //
7460 // This rule is not present in C++1y, so we produce a backwards
7461 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007462 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007463 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7464 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007465 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007466 CXXMethodDecl *OldMD = 0;
7467 if (OldDecl)
7468 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007469 if (!OldMD || !OldMD->isStatic()) {
7470 const FunctionProtoType *FPT =
7471 MD->getType()->castAs<FunctionProtoType>();
7472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7473 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007474 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007475 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007476
7477 // Warn that we did this, if we're not performing template instantiation.
7478 // In that case, we'll have warned already when the template was defined.
7479 if (ActiveTemplateInstantiations.empty()) {
7480 SourceLocation AddConstLoc;
7481 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7482 .IgnoreParens().getAs<FunctionTypeLoc>())
7483 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7484
7485 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7486 << FixItHint::CreateInsertion(AddConstLoc, " const");
7487 }
Richard Smith574f4f62013-01-14 05:37:29 +00007488 }
7489 }
7490
7491 if (Redeclaration) {
7492 // NewFD and OldDecl represent declarations that need to be
7493 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007494 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007495 NewFD->setInvalidDecl();
7496 return Redeclaration;
7497 }
7498
7499 Previous.clear();
7500 Previous.addDecl(OldDecl);
7501
7502 if (FunctionTemplateDecl *OldTemplateDecl
7503 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7504 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7505 FunctionTemplateDecl *NewTemplateDecl
7506 = NewFD->getDescribedFunctionTemplate();
7507 assert(NewTemplateDecl && "Template/non-template mismatch");
7508 if (CXXMethodDecl *Method
7509 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7510 Method->setAccess(OldTemplateDecl->getAccess());
7511 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007512 }
Richard Smith574f4f62013-01-14 05:37:29 +00007513
7514 // If this is an explicit specialization of a member that is a function
7515 // template, mark it as a member specialization.
7516 if (IsExplicitSpecialization &&
7517 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7518 NewTemplateDecl->setMemberSpecialization();
7519 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007520 }
Richard Smith574f4f62013-01-14 05:37:29 +00007521
7522 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007523 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007524 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007525
7526 if (isa<CXXMethodDecl>(NewFD)) {
7527 // A valid redeclaration of a C++ method must be out-of-line,
7528 // but (unfortunately) it's not necessarily a definition
7529 // because of templates, which means that the previous
7530 // declaration is not necessarily from the class definition.
7531
7532 // For just setting the access, that doesn't matter.
7533 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7534 NewFD->setAccess(oldMethod->getAccess());
7535
7536 // Update the key-function state if necessary for this ABI.
7537 if (NewFD->isInlined() &&
7538 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7539 // setNonKeyFunction needs to work with the original
7540 // declaration from the class definition, and isVirtual() is
7541 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007542 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007543 if (oldMethod->isVirtual()) {
7544 Context.setNonKeyFunction(oldMethod);
7545 }
7546 }
7547 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007548 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007549 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007550
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007551 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007552 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007553 // C++-specific checks.
7554 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7555 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007556 } else if (CXXDestructorDecl *Destructor =
7557 dyn_cast<CXXDestructorDecl>(NewFD)) {
7558 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007559 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007560
Douglas Gregor7454c562010-07-02 20:37:36 +00007561 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007562 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007563 if (!ClassType->isDependentType()) {
7564 DeclarationName Name
7565 = Context.DeclarationNames.getCXXDestructorName(
7566 Context.getCanonicalType(ClassType));
7567 if (NewFD->getDeclName() != Name) {
7568 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007569 NewFD->setInvalidDecl();
7570 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007571 }
7572 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007573 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007574 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007575 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007576 }
7577
7578 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7580 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007581 !Method->getDescribedFunctionTemplate() &&
7582 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007583 if (AddOverriddenMethods(Method->getParent(), Method)) {
7584 // If the function was marked as "static", we have a problem.
7585 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007586 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007587 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007588 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007589 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007590
7591 if (Method->isStatic())
7592 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007593 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007594
7595 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7596 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007597 CheckOverloadedOperatorDeclaration(NewFD)) {
7598 NewFD->setInvalidDecl();
7599 return Redeclaration;
7600 }
Alexis Huntc88db062010-01-13 09:01:02 +00007601
7602 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7603 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007604 CheckLiteralOperatorDeclaration(NewFD)) {
7605 NewFD->setInvalidDecl();
7606 return Redeclaration;
7607 }
Alexis Huntc88db062010-01-13 09:01:02 +00007608
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007609 // In C++, check default arguments now that we have merged decls. Unless
7610 // the lexical context is the class, because in this case this is done
7611 // during delayed parsing anyway.
7612 if (!CurContext->isRecord())
7613 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007614
Douglas Gregor9246b682010-12-21 19:47:46 +00007615 // If this function declares a builtin function, check the type of this
7616 // declaration against the expected type for the builtin.
7617 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7618 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007619 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007620 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7621 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7622 // The type of this function differs from the type of the builtin,
7623 // so forget about the builtin entirely.
7624 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7625 }
7626 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007627
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007628 // If this function is declared as being extern "C", then check to see if
7629 // the function returns a UDT (class, struct, or union type) that is not C
7630 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007631 // But, issue any diagnostic on the first declaration only.
7632 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007633 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007634 if (R->isIncompleteType() && !R->isVoidType())
7635 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7636 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007637 else if (!R.isPODType(Context) && !R->isVoidType() &&
7638 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007639 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007640 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007641 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007642 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007643}
7644
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007645static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7646 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7647 if (!TSI)
7648 return SourceRange();
7649
7650 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007651 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007652 if (!FunctionTL)
7653 return SourceRange();
7654
Alp Toker42a16a62014-01-25 23:51:36 +00007655 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007656 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007657 return ResultTL.getSourceRange();
7658
7659 return SourceRange();
7660}
7661
David Blaikied937bf12011-09-08 06:33:04 +00007662void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007663 // C++11 [basic.start.main]p3:
7664 // A program that [...] declares main to be inline, static or
7665 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007666 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7667 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007668 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007669 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007670 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007671 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007672 ? diag::err_static_main : diag::warn_static_main)
7673 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7674 if (FD->isInlineSpecified())
7675 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7676 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007677 if (DS.isNoreturnSpecified()) {
7678 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7679 SourceRange NoreturnRange(NoreturnLoc,
7680 PP.getLocForEndOfToken(NoreturnLoc));
7681 Diag(NoreturnLoc, diag::ext_noreturn_main);
7682 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7683 << FixItHint::CreateRemoval(NoreturnRange);
7684 }
Richard Smith3f333f22012-02-04 06:10:17 +00007685 if (FD->isConstexpr()) {
7686 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7687 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7688 FD->setConstexpr(false);
7689 }
John McCall02dee0a2009-07-25 04:36:53 +00007690
Joey Goulya7310a82013-11-05 12:30:39 +00007691 if (getLangOpts().OpenCL) {
7692 Diag(FD->getLocation(), diag::err_opencl_no_main)
7693 << FD->hasAttr<OpenCLKernelAttr>();
7694 FD->setInvalidDecl();
7695 return;
7696 }
7697
John McCall02dee0a2009-07-25 04:36:53 +00007698 QualType T = FD->getType();
7699 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007700 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007701
John McCall5ed3caf2012-02-14 19:50:52 +00007702 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007703 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007704 // In C and C++, main magically returns 0 if you fall off the end;
7705 // set the flag which tells us that.
7706 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7707 FD->setHasImplicitReturnZero(true);
7708
7709 // In C with GNU extensions we allow main() to have non-integer return
7710 // type, but we should warn about the extension, and we disable the
7711 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007712 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007713 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7714
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007715 SourceRange ResultRange = getResultSourceRange(FD);
7716 if (ResultRange.isValid())
7717 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7718 << FixItHint::CreateReplacement(ResultRange, "int");
7719
John McCall5ed3caf2012-02-14 19:50:52 +00007720 // Otherwise, this is just a flat-out error.
7721 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007722 SourceRange ResultRange = getResultSourceRange(FD);
7723 if (ResultRange.isValid())
7724 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7725 << FixItHint::CreateReplacement(ResultRange, "int");
7726 else
7727 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7728
John McCall02dee0a2009-07-25 04:36:53 +00007729 FD->setInvalidDecl(true);
7730 }
7731
7732 // Treat protoless main() as nullary.
7733 if (isa<FunctionNoProtoType>(FT)) return;
7734
7735 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007736 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007737 assert(FD->getNumParams() == nparams);
7738
John McCall0e21fcc2009-12-24 09:58:38 +00007739 bool HasExtraParameters = (nparams > 3);
7740
7741 // Darwin passes an undocumented fourth argument of type char**. If
7742 // other platforms start sprouting these, the logic below will start
7743 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007744 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007745 HasExtraParameters = false;
7746
7747 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007748 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7749 FD->setInvalidDecl(true);
7750 nparams = 3;
7751 }
7752
7753 // FIXME: a lot of the following diagnostics would be improved
7754 // if we had some location information about types.
7755
7756 QualType CharPP =
7757 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007758 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007759
7760 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007761 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007762
7763 bool mismatch = true;
7764
7765 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7766 mismatch = false;
7767 else if (Expected[i] == CharPP) {
7768 // As an extension, the following forms are okay:
7769 // char const **
7770 // char const * const *
7771 // char * const *
7772
John McCall8ccfcb52009-09-24 19:53:00 +00007773 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007774 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007775 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7776 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007777 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7778 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007779 qs.removeConst();
7780 mismatch = !qs.empty();
7781 }
7782 }
7783
7784 if (mismatch) {
7785 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7786 // TODO: suggest replacing given type with expected type
7787 FD->setInvalidDecl(true);
7788 }
7789 }
7790
7791 if (nparams == 1 && !FD->isInvalidDecl()) {
7792 Diag(FD->getLocation(), diag::warn_main_one_arg);
7793 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007794
7795 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007796 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007797 FD->setInvalidDecl();
7798 }
7799}
7800
7801void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7802 QualType T = FD->getType();
7803 assert(T->isFunctionType() && "function decl is not of function type");
7804 const FunctionType *FT = T->castAs<FunctionType>();
7805
7806 // Set an implicit return of 'zero' if the function can return some integral,
7807 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007808 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7809 FT->getReturnType()->isAnyPointerType() ||
7810 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007811 // DllMain is exempt because a return value of zero means it failed.
7812 if (FD->getName() != "DllMain")
7813 FD->setHasImplicitReturnZero(true);
7814
7815 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007816 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007817 FD->setInvalidDecl();
7818 }
John McCalld9baf6a2009-07-24 03:03:21 +00007819}
7820
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007821bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007822 // FIXME: Need strict checking. In C89, we need to check for
7823 // any assignment, increment, decrement, function-calls, or
7824 // commas outside of a sizeof. In C99, it's the same list,
7825 // except that the aforementioned are allowed in unevaluated
7826 // expressions. Everything else falls under the
7827 // "may accept other forms of constant expressions" exception.
7828 // (We never end up here for C++, so the constant expression
7829 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007830 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007831 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007832 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7833 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007834 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007835}
7836
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007837namespace {
7838 // Visits an initialization expression to see if OrigDecl is evaluated in
7839 // its own initialization and throws a warning if it does.
7840 class SelfReferenceChecker
7841 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7842 Sema &S;
7843 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007844 bool isRecordType;
7845 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007846 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007847
7848 public:
7849 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7850
7851 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007852 S(S), OrigDecl(OrigDecl) {
7853 isPODType = false;
7854 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007855 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007856 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7857 isPODType = VD->getType().isPODType(S.Context);
7858 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007859 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007860 }
7861 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007862
Richard Trieu64c51ab2012-05-09 00:21:34 +00007863 // For most expressions, the cast is directly above the DeclRefExpr.
7864 // For conditional operators, the cast can be outside the conditional
7865 // operator if both expressions are DeclRefExpr's.
7866 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007867 if (isReferenceType)
7868 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007869 E = E->IgnoreParenImpCasts();
7870 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7871 HandleDeclRefExpr(DRE);
7872 return;
7873 }
7874
7875 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7876 HandleValue(CO->getTrueExpr());
7877 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007878 return;
7879 }
7880
7881 if (isa<MemberExpr>(E)) {
7882 Expr *Base = E->IgnoreParenImpCasts();
7883 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7884 // Check for static member variables and don't warn on them.
7885 if (!isa<FieldDecl>(ME->getMemberDecl()))
7886 return;
7887 Base = ME->getBase()->IgnoreParenImpCasts();
7888 }
7889 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7890 HandleDeclRefExpr(DRE);
7891 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007892 }
7893 }
7894
Richard Trieu32673472012-10-01 17:39:51 +00007895 // Reference types are handled here since all uses of references are
7896 // bad, not just r-value uses.
7897 void VisitDeclRefExpr(DeclRefExpr *E) {
7898 if (isReferenceType)
7899 HandleDeclRefExpr(E);
7900 }
7901
Richard Trieu64c51ab2012-05-09 00:21:34 +00007902 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007903 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007904 (isRecordType && E->getCastKind() == CK_NoOp))
7905 HandleValue(E->getSubExpr());
7906
7907 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007908 }
7909
Richard Trieua04ad1a2011-09-01 21:44:13 +00007910 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007911 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007912 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007913
Richard Trieu742c6ed2012-10-03 00:41:36 +00007914 // Warn when a non-static method call is followed by non-static member
7915 // field accesses, which is followed by a DeclRefExpr.
7916 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7917 bool Warn = (MD && !MD->isStatic());
7918 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7919 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7920 if (!isa<FieldDecl>(ME->getMemberDecl()))
7921 Warn = false;
7922 Base = ME->getBase()->IgnoreParenImpCasts();
7923 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007924
Richard Trieu742c6ed2012-10-03 00:41:36 +00007925 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7926 if (Warn)
7927 HandleDeclRefExpr(DRE);
7928 return;
7929 }
7930
7931 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7932 // Visit that expression.
7933 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007934 }
7935
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007936 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7937 if (E->getNumArgs() > 0)
7938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7939 HandleDeclRefExpr(DRE);
7940
7941 Inherited::VisitCXXOperatorCallExpr(E);
7942 }
7943
Richard Trieua04ad1a2011-09-01 21:44:13 +00007944 void VisitUnaryOperator(UnaryOperator *E) {
7945 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007946 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7947 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7948 if (!isPODType)
7949 HandleValue(E->getSubExpr());
7950 return;
7951 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007952 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007953 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007954
7955 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7956
Richard Trieua04ad1a2011-09-01 21:44:13 +00007957 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007958 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007959 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007960 unsigned diag;
7961 if (isReferenceType) {
7962 diag = diag::warn_uninit_self_reference_in_reference_init;
7963 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7964 diag = diag::warn_static_self_reference_in_init;
7965 } else {
7966 diag = diag::warn_uninit_self_reference_in_init;
7967 }
7968
Richard Trieua04ad1a2011-09-01 21:44:13 +00007969 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007970 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007971 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007972 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007973 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007974 }
7975 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007976
Richard Trieu32673472012-10-01 17:39:51 +00007977 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7978 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7979 bool DirectInit) {
7980 // Parameters arguments are occassionially constructed with itself,
7981 // for instance, in recursive functions. Skip them.
7982 if (isa<ParmVarDecl>(OrigDecl))
7983 return;
7984
7985 E = E->IgnoreParens();
7986
7987 // Skip checking T a = a where T is not a record or reference type.
7988 // Doing so is a way to silence uninitialized warnings.
7989 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7991 if (ICE->getCastKind() == CK_LValueToRValue)
7992 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7993 if (DRE->getDecl() == OrigDecl)
7994 return;
7995
7996 SelfReferenceChecker(S, OrigDecl).Visit(E);
7997 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007998}
7999
Douglas Gregor5fb53972009-01-14 15:45:31 +00008000/// AddInitializerToDecl - Adds the initializer Init to the
8001/// declaration dcl. If DirectInit is true, this is C++ direct
8002/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008003void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8004 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008005 // If there is no declaration, there was an error parsing it. Just ignore
8006 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008007 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008008 return;
Mike Stump11289f42009-09-09 15:08:12 +00008009
Douglas Gregor0c880302009-03-11 23:00:04 +00008010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8011 // With declarators parsed the way they are, the parser cannot
8012 // distinguish between a normal initializer and a pure-specifier.
8013 // Thus this grotesque test.
8014 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008015 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008016 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8017 CheckPureMethod(Method, Init->getSourceRange());
8018 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008019 Diag(Method->getLocation(), diag::err_member_function_initialization)
8020 << Method->getDeclName() << Init->getSourceRange();
8021 Method->setInvalidDecl();
8022 }
8023 return;
8024 }
8025
Steve Naroff437b4d82007-09-12 20:13:48 +00008026 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8027 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008028 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8029 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008030 RealDecl->setInvalidDecl();
8031 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008032 }
Sebastian Redla9351792012-02-11 23:51:47 +00008033 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8034
Richard Smith0cc85782011-12-15 19:20:59 +00008035 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008036 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008037 Expr *DeduceInit = Init;
8038 // Initializer could be a C++ direct-initializer. Deduction only works if it
8039 // contains exactly one expression.
8040 if (CXXDirectInit) {
8041 if (CXXDirectInit->getNumExprs() == 0) {
8042 // It isn't possible to write this directly, but it is possible to
8043 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008044 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008045 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8046 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008047 << VDecl->getDeclName() << VDecl->getType()
8048 << VDecl->getSourceRange();
8049 RealDecl->setInvalidDecl();
8050 return;
8051 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008052 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008053 VDecl->isInitCapture()
8054 ? diag::err_init_capture_multiple_expressions
8055 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008056 << VDecl->getDeclName() << VDecl->getType()
8057 << VDecl->getSourceRange();
8058 RealDecl->setInvalidDecl();
8059 return;
8060 } else {
8061 DeduceInit = CXXDirectInit->getExpr(0);
8062 }
8063 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008064
8065 // Expressions default to 'id' when we're in a debugger.
8066 bool DefaultedToAuto = false;
8067 if (getLangOpts().DebuggerCastResultToId &&
8068 Init->getType() == Context.UnknownAnyTy) {
8069 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8070 if (Result.isInvalid()) {
8071 VDecl->setInvalidDecl();
8072 return;
8073 }
8074 Init = Result.take();
8075 DefaultedToAuto = true;
8076 }
Richard Smith061f1e22013-04-30 21:23:01 +00008077
8078 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008079 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008080 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008081 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008082 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008083 RealDecl->setInvalidDecl();
8084 return;
8085 }
Richard Smith061f1e22013-04-30 21:23:01 +00008086 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008087 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008088
John McCall31168b02011-06-15 23:02:42 +00008089 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008090 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008091 VDecl->setInvalidDecl();
8092
Jordan Rosed8d56692012-06-08 22:46:07 +00008093 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8094 // 'id' instead of a specific object type prevents most of our usual checks.
8095 // We only want to warn outside of template instantiations, though:
8096 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008097 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008098 DeducedType->isObjCIdType()) {
8099 SourceLocation Loc =
8100 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008101 Diag(Loc, diag::warn_auto_var_is_id)
8102 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8103 }
8104
Richard Smith30482bc2011-02-20 03:19:35 +00008105 // If this is a redeclaration, check that the type we just deduced matches
8106 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008107 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8108 // We never need to merge the type, because we cannot form an incomplete
8109 // array of auto, nor deduce such a type.
8110 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8111 }
Richard Smith27d807c2013-04-30 13:56:41 +00008112
8113 // Check the deduced type is valid for a variable declaration.
8114 CheckVariableDeclarationType(VDecl);
8115 if (VDecl->isInvalidDecl())
8116 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008117 }
Richard Smith0cc85782011-12-15 19:20:59 +00008118
8119 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8120 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8121 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8122 VDecl->setInvalidDecl();
8123 return;
8124 }
8125
Sebastian Redla9351792012-02-11 23:51:47 +00008126 if (!VDecl->getType()->isDependentType()) {
8127 // A definition must end up with a complete type, which means it must be
8128 // complete with the restriction that an array type might be completed by
8129 // the initializer; note that later code assumes this restriction.
8130 QualType BaseDeclType = VDecl->getType();
8131 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8132 BaseDeclType = Array->getElementType();
8133 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8134 diag::err_typecheck_decl_incomplete_type)) {
8135 RealDecl->setInvalidDecl();
8136 return;
8137 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008138
Sebastian Redla9351792012-02-11 23:51:47 +00008139 // The variable can not have an abstract class type.
8140 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8141 diag::err_abstract_type_in_decl,
8142 AbstractVariableType))
8143 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008144 }
8145
Sebastian Redl5ca79842010-02-01 20:16:42 +00008146 const VarDecl *Def;
8147 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008148 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008149 << VDecl->getDeclName();
8150 Diag(Def->getLocation(), diag::note_previous_definition);
8151 VDecl->setInvalidDecl();
8152 return;
8153 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008154
Douglas Gregorf0f83692010-08-24 05:27:49 +00008155 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008156 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008157 // C++ [class.static.data]p4
8158 // If a static data member is of const integral or const
8159 // enumeration type, its declaration in the class definition can
8160 // specify a constant-initializer which shall be an integral
8161 // constant expression (5.19). In that case, the member can appear
8162 // in integral constant expressions. The member shall still be
8163 // defined in a namespace scope if it is used in the program and the
8164 // namespace scope definition shall not contain an initializer.
8165 //
8166 // We already performed a redefinition check above, but for static
8167 // data members we also need to check whether there was an in-class
8168 // declaration with an initializer.
8169 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008170 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8171 << VDecl->getDeclName();
8172 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008173 return;
8174 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008175
Douglas Gregor71f39c92010-12-16 01:31:22 +00008176 if (VDecl->hasLocalStorage())
8177 getCurFunction()->setHasBranchProtectedScope();
8178
8179 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8180 VDecl->setInvalidDecl();
8181 return;
8182 }
8183 }
John McCalld4e1b762010-08-01 01:24:59 +00008184
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008185 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8186 // a kernel function cannot be initialized."
8187 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8188 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8189 VDecl->setInvalidDecl();
8190 return;
8191 }
8192
Steve Naroff61091402007-09-12 14:07:44 +00008193 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008194 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008195 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008196
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008197 // Expressions default to 'id' when we're in a debugger
8198 // and we are assigning it to a variable of Objective-C pointer type.
8199 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8200 Init->getType() == Context.UnknownAnyTy) {
8201 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8202 if (Result.isInvalid()) {
8203 VDecl->setInvalidDecl();
8204 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008205 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008206 Init = Result.take();
8207 }
Richard Smith0cc85782011-12-15 19:20:59 +00008208
8209 // Perform the initialization.
8210 if (!VDecl->isInvalidDecl()) {
8211 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8212 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008213 = DirectInit ?
8214 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8215 Init->getLocStart(),
8216 Init->getLocEnd())
8217 : InitializationKind::CreateDirectList(
8218 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008219 : InitializationKind::CreateCopy(VDecl->getLocation(),
8220 Init->getLocStart());
8221
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008222 MultiExprArg Args = Init;
8223 if (CXXDirectInit)
8224 Args = MultiExprArg(CXXDirectInit->getExprs(),
8225 CXXDirectInit->getNumExprs());
8226
8227 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8228 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008229 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008230 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008231 return;
Steve Naroff61091402007-09-12 14:07:44 +00008232 }
Richard Smith0cc85782011-12-15 19:20:59 +00008233
8234 Init = Result.takeAs<Expr>();
8235 }
8236
Richard Trieu32673472012-10-01 17:39:51 +00008237 // Check for self-references within variable initializers.
8238 // Variables declared within a function/method body (except for references)
8239 // are handled by a dataflow analysis.
8240 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8241 VDecl->getType()->isReferenceType()) {
8242 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8243 }
8244
Richard Smith0cc85782011-12-15 19:20:59 +00008245 // If the type changed, it means we had an incomplete type that was
8246 // completed by the initializer. For example:
8247 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008248 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008249 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008250 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008251
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008252 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008253 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8254
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008255 if (VDecl->hasAttr<BlocksAttr>())
8256 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008257
8258 // It is safe to assign a weak reference into a strong variable.
8259 // Although this code can still have problems:
8260 // id x = self.weakProp;
8261 // id y = self.weakProp;
8262 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8263 // paths through the function. This should be revisited if
8264 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008265 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008266 DiagnosticsEngine::Level Level =
8267 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8268 Init->getLocStart());
8269 if (Level != DiagnosticsEngine::Ignored)
8270 getCurFunction()->markSafeWeakUse(Init);
8271 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008272 }
8273
Richard Smith945f8d32013-01-14 22:39:08 +00008274 // The initialization is usually a full-expression.
8275 //
8276 // FIXME: If this is a braced initialization of an aggregate, it is not
8277 // an expression, and each individual field initializer is a separate
8278 // full-expression. For instance, in:
8279 //
8280 // struct Temp { ~Temp(); };
8281 // struct S { S(Temp); };
8282 // struct T { S a, b; } t = { Temp(), Temp() }
8283 //
8284 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008285 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8286 false,
8287 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008288 if (Result.isInvalid()) {
8289 VDecl->setInvalidDecl();
8290 return;
8291 }
8292 Init = Result.take();
8293
Richard Smith0cc85782011-12-15 19:20:59 +00008294 // Attach the initializer to the decl.
8295 VDecl->setInit(Init);
8296
8297 if (VDecl->isLocalVarDecl()) {
8298 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8299 // static storage duration shall be constant expressions or string literals.
8300 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008301 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8302 if (VDecl->getStorageClass() == SC_Static)
8303 CheckForConstantInitializer(Init, DclT);
8304 // C89 is stricter than C99 for non-static aggregate types.
8305 // C89 6.5.7p3: All the expressions [...] in an initializer list
8306 // for an object that has aggregate or union type shall be
8307 // constant expressions.
8308 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008309 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008310 !Init->isConstantInitializer(Context, false))
8311 Diag(Init->getExprLoc(),
8312 diag::ext_aggregate_init_not_constant)
8313 << Init->getSourceRange();
8314 }
Mike Stump11289f42009-09-09 15:08:12 +00008315 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008316 VDecl->getLexicalDeclContext()->isRecord()) {
8317 // This is an in-class initialization for a static data member, e.g.,
8318 //
8319 // struct S {
8320 // static const int value = 17;
8321 // };
8322
Douglas Gregor0c880302009-03-11 23:00:04 +00008323 // C++ [class.mem]p4:
8324 // A member-declarator can contain a constant-initializer only
8325 // if it declares a static member (9.4) of const integral or
8326 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008327 //
Richard Smith0cc85782011-12-15 19:20:59 +00008328 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008329 // If a non-volatile const static data member is of integral or
8330 // enumeration type, its declaration in the class definition can
8331 // specify a brace-or-equal-initializer in which every initalizer-clause
8332 // that is an assignment-expression is a constant expression. A static
8333 // data member of literal type can be declared in the class definition
8334 // with the constexpr specifier; if so, its declaration shall specify a
8335 // brace-or-equal-initializer in which every initializer-clause that is
8336 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008337
8338 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008339 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008340
Richard Smith2316cd82011-09-29 19:11:37 +00008341 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008342 // type. We separately check that every constexpr variable is of literal
8343 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008344 } else if (VDecl->isConstexpr()) {
8345
John McCalldb768922010-09-10 23:21:22 +00008346 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008347 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008348 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8349 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008350 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008351
8352 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008353 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008354 // Check whether the expression is a constant expression.
8355 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008356 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008357 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008358 // in-class initializer cannot be volatile.
8359 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8360 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008361 ; // Nothing to check.
8362 else if (Init->isIntegerConstantExpr(Context, &Loc))
8363 ; // Ok, it's an ICE!
8364 else if (Init->isEvaluatable(Context)) {
8365 // If we can constant fold the initializer through heroics, accept it,
8366 // but report this as a use of an extension for -pedantic.
8367 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8368 << Init->getSourceRange();
8369 } else {
8370 // Otherwise, this is some crazy unknown case. Report the issue at the
8371 // location provided by the isIntegerConstantExpr failed check.
8372 Diag(Loc, diag::err_in_class_initializer_non_constant)
8373 << Init->getSourceRange();
8374 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008375 }
8376
Richard Smith0cc85782011-12-15 19:20:59 +00008377 // We allow foldable floating-point constants as an extension.
8378 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008379 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8380 // it anyway and provide a fixit to add the 'constexpr'.
8381 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008382 Diag(VDecl->getLocation(),
8383 diag::ext_in_class_initializer_float_type_cxx11)
8384 << DclT << Init->getSourceRange();
8385 Diag(VDecl->getLocStart(),
8386 diag::note_in_class_initializer_float_type_cxx11)
8387 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008388 } else {
8389 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8390 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008391
Richard Smithcf656382013-01-25 04:22:16 +00008392 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8393 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8394 << Init->getSourceRange();
8395 VDecl->setInvalidDecl();
8396 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008397 }
Richard Smith256336d2011-09-29 23:18:34 +00008398
Richard Smith0cc85782011-12-15 19:20:59 +00008399 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008400 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008401 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008402 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008403 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8404 VDecl->setConstexpr(true);
8405
Richard Smith2316cd82011-09-29 19:11:37 +00008406 } else {
8407 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008408 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008409 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008410 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008411 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008412 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008413 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008414 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008415 VDecl->isExternC())) &&
8416 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008417 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008418
Richard Smith0cc85782011-12-15 19:20:59 +00008419 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008420 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008421 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008422 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8423 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8424 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008425 !Init->isConstantInitializer(
8426 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008427 // GNU C++98 edits for __thread, [basic.start.init]p4:
8428 // An object of thread storage duration shall not require dynamic
8429 // initialization.
8430 // FIXME: Need strict checking here.
8431 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8432 if (getLangOpts().CPlusPlus11)
8433 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8434 }
Steve Naroff61091402007-09-12 14:07:44 +00008435 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008436
Sebastian Redla9351792012-02-11 23:51:47 +00008437 // We will represent direct-initialization similarly to copy-initialization:
8438 // int x(1); -as-> int x = 1;
8439 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8440 //
8441 // Clients that want to distinguish between the two forms, can check for
8442 // direct initializer using VarDecl::getInitStyle().
8443 // A major benefit is that clients that don't particularly care about which
8444 // exactly form was it (like the CodeGen) can handle both cases without
8445 // special case code.
8446
8447 // C++ 8.5p11:
8448 // The form of initialization (using parentheses or '=') is generally
8449 // insignificant, but does matter when the entity being initialized has a
8450 // class type.
8451 if (CXXDirectInit) {
8452 assert(DirectInit && "Call-style initializer must be direct init.");
8453 VDecl->setInitStyle(VarDecl::CallInit);
8454 } else if (DirectInit) {
8455 // This must be list-initialization. No other way is direct-initialization.
8456 VDecl->setInitStyle(VarDecl::ListInit);
8457 }
8458
John McCall8b7fd8f12011-01-19 11:48:09 +00008459 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008460}
8461
John McCalleae5acb2010-03-31 02:13:20 +00008462/// ActOnInitializerError - Given that there was an error parsing an
8463/// initializer for the given declaration, try to return to some form
8464/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008465void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008466 // Our main concern here is re-establishing invariants like "a
8467 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008468 if (!D || D->isInvalidDecl()) return;
8469
8470 VarDecl *VD = dyn_cast<VarDecl>(D);
8471 if (!VD) return;
8472
Richard Smith30482bc2011-02-20 03:19:35 +00008473 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008474 if (ParsingInitForAutoVars.count(D)) {
8475 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008476 return;
8477 }
8478
John McCalleae5acb2010-03-31 02:13:20 +00008479 QualType Ty = VD->getType();
8480 if (Ty->isDependentType()) return;
8481
8482 // Require a complete type.
8483 if (RequireCompleteType(VD->getLocation(),
8484 Context.getBaseElementType(Ty),
8485 diag::err_typecheck_decl_incomplete_type)) {
8486 VD->setInvalidDecl();
8487 return;
8488 }
8489
8490 // Require an abstract type.
8491 if (RequireNonAbstractType(VD->getLocation(), Ty,
8492 diag::err_abstract_type_in_decl,
8493 AbstractVariableType)) {
8494 VD->setInvalidDecl();
8495 return;
8496 }
8497
8498 // Don't bother complaining about constructors or destructors,
8499 // though.
8500}
8501
John McCall48871652010-08-21 09:40:31 +00008502void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008503 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008504 // If there is no declaration, there was an error parsing it. Just ignore it.
8505 if (RealDecl == 0)
8506 return;
8507
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008508 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8509 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008510
Richard Smithf0215fe2011-12-25 21:17:58 +00008511 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008512 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008513 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8514 << Var->getDeclName() << Type;
8515 Var->setInvalidDecl();
8516 return;
8517 }
Mike Stump11289f42009-09-09 15:08:12 +00008518
Richard Smithf0215fe2011-12-25 21:17:58 +00008519 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008520 // the constexpr specifier; if so, its declaration shall specify
8521 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008522 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8523 // the definition of a variable [...] or the declaration of a static data
8524 // member.
8525 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8526 if (Var->isStaticDataMember())
8527 Diag(Var->getLocation(),
8528 diag::err_constexpr_static_mem_var_requires_init)
8529 << Var->getDeclName();
8530 else
8531 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008532 Var->setInvalidDecl();
8533 return;
8534 }
8535
Joey Gouly96b94e62014-01-03 14:16:55 +00008536 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8537 // be initialized.
8538 if (!Var->isInvalidDecl() &&
8539 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008540 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008541 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8542 Var->setInvalidDecl();
8543 return;
8544 }
8545
Douglas Gregore6565622010-02-09 07:26:29 +00008546 switch (Var->isThisDeclarationADefinition()) {
8547 case VarDecl::Definition:
8548 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8549 break;
8550
8551 // We have an out-of-line definition of a static data member
8552 // that has an in-class initializer, so we type-check this like
8553 // a declaration.
8554 //
8555 // Fall through
8556
8557 case VarDecl::DeclarationOnly:
8558 // It's only a declaration.
8559
8560 // Block scope. C99 6.7p7: If an identifier for an object is
8561 // declared with no linkage (C99 6.2.2p6), the type for the
8562 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008563 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008564 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008565 RequireCompleteType(Var->getLocation(), Type,
8566 diag::err_typecheck_decl_incomplete_type))
8567 Var->setInvalidDecl();
8568
8569 // Make sure that the type is not abstract.
8570 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8571 RequireNonAbstractType(Var->getLocation(), Type,
8572 diag::err_abstract_type_in_decl,
8573 AbstractVariableType))
8574 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008575 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008576 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008577 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008578 Diag(Var->getLocation(), diag::note_private_extern);
8579 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008580
Douglas Gregore6565622010-02-09 07:26:29 +00008581 return;
8582
8583 case VarDecl::TentativeDefinition:
8584 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8585 // object that has file scope without an initializer, and without a
8586 // storage-class specifier or with the storage-class specifier "static",
8587 // constitutes a tentative definition. Note: A tentative definition with
8588 // external linkage is valid (C99 6.2.2p5).
8589 if (!Var->isInvalidDecl()) {
8590 if (const IncompleteArrayType *ArrayT
8591 = Context.getAsIncompleteArrayType(Type)) {
8592 if (RequireCompleteType(Var->getLocation(),
8593 ArrayT->getElementType(),
8594 diag::err_illegal_decl_array_incomplete_type))
8595 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008596 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008597 // C99 6.9.2p3: If the declaration of an identifier for an object is
8598 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8599 // declared type shall not be an incomplete type.
8600 // NOTE: code such as the following
8601 // static struct s;
8602 // struct s { int a; };
8603 // is accepted by gcc. Hence here we issue a warning instead of
8604 // an error and we do not invalidate the static declaration.
8605 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008606 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008607 RequireCompleteType(Var->getLocation(), Type,
8608 diag::ext_typecheck_decl_incomplete_type);
8609 }
8610 }
8611
8612 // Record the tentative definition; we're done.
8613 if (!Var->isInvalidDecl())
8614 TentativeDefinitions.push_back(Var);
8615 return;
8616 }
8617
8618 // Provide a specific diagnostic for uninitialized variable
8619 // definitions with incomplete array type.
8620 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008621 Diag(Var->getLocation(),
8622 diag::err_typecheck_incomplete_array_needs_initializer);
8623 Var->setInvalidDecl();
8624 return;
8625 }
8626
John McCalla755f0f2010-08-01 01:25:24 +00008627 // Provide a specific diagnostic for uninitialized variable
8628 // definitions with reference type.
8629 if (Type->isReferenceType()) {
8630 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8631 << Var->getDeclName()
8632 << SourceRange(Var->getLocation(), Var->getLocation());
8633 Var->setInvalidDecl();
8634 return;
8635 }
Douglas Gregore6565622010-02-09 07:26:29 +00008636
8637 // Do not attempt to type-check the default initializer for a
8638 // variable with dependent type.
8639 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008640 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008641
Douglas Gregore6565622010-02-09 07:26:29 +00008642 if (Var->isInvalidDecl())
8643 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008644
Douglas Gregore6565622010-02-09 07:26:29 +00008645 if (RequireCompleteType(Var->getLocation(),
8646 Context.getBaseElementType(Type),
8647 diag::err_typecheck_decl_incomplete_type)) {
8648 Var->setInvalidDecl();
8649 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008650 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008651
Douglas Gregore6565622010-02-09 07:26:29 +00008652 // The variable can not have an abstract class type.
8653 if (RequireNonAbstractType(Var->getLocation(), Type,
8654 diag::err_abstract_type_in_decl,
8655 AbstractVariableType)) {
8656 Var->setInvalidDecl();
8657 return;
8658 }
8659
Douglas Gregor9574af62011-05-21 17:52:48 +00008660 // Check for jumps past the implicit initializer. C++0x
8661 // clarifies that this applies to a "variable with automatic
8662 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008663 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008664 // A program that jumps from a point where a variable with automatic
8665 // storage duration is not in scope to a point where it is in scope is
8666 // ill-formed unless the variable has scalar type, class type with a
8667 // trivial default constructor and a trivial destructor, a cv-qualified
8668 // version of one of these types, or an array of one of the preceding
8669 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008670 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008671 if (const RecordType *Record
8672 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008673 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008674 // Mark the function for further checking even if the looser rules of
8675 // C++11 do not require such checks, so that we can diagnose
8676 // incompatibilities with C++98.
8677 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008678 getCurFunction()->setHasBranchProtectedScope();
8679 }
Douglas Gregore6565622010-02-09 07:26:29 +00008680 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008681
8682 // C++03 [dcl.init]p9:
8683 // If no initializer is specified for an object, and the
8684 // object is of (possibly cv-qualified) non-POD class type (or
8685 // array thereof), the object shall be default-initialized; if
8686 // the object is of const-qualified type, the underlying class
8687 // type shall have a user-declared default
8688 // constructor. Otherwise, if no initializer is specified for
8689 // a non- static object, the object and its subobjects, if
8690 // any, have an indeterminate initial value); if the object
8691 // or any of its subobjects are of const-qualified type, the
8692 // program is ill-formed.
8693 // C++0x [dcl.init]p11:
8694 // If no initializer is specified for an object, the object is
8695 // default-initialized; [...].
8696 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8697 InitializationKind Kind
8698 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008699
8700 InitializationSequence InitSeq(*this, Entity, Kind, None);
8701 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008702 if (Init.isInvalid())
8703 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008704 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008705 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008706 // This is important for template substitution.
8707 Var->setInitStyle(VarDecl::CallInit);
8708 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008709
John McCall8b7fd8f12011-01-19 11:48:09 +00008710 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008711 }
8712}
8713
Richard Smith02e85f32011-04-14 22:09:26 +00008714void Sema::ActOnCXXForRangeDecl(Decl *D) {
8715 VarDecl *VD = dyn_cast<VarDecl>(D);
8716 if (!VD) {
8717 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8718 D->setInvalidDecl();
8719 return;
8720 }
8721
8722 VD->setCXXForRangeDecl(true);
8723
8724 // for-range-declaration cannot be given a storage class specifier.
8725 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008726 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008727 case SC_None:
8728 break;
8729 case SC_Extern:
8730 Error = 0;
8731 break;
8732 case SC_Static:
8733 Error = 1;
8734 break;
8735 case SC_PrivateExtern:
8736 Error = 2;
8737 break;
8738 case SC_Auto:
8739 Error = 3;
8740 break;
8741 case SC_Register:
8742 Error = 4;
8743 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008744 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008745 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008746 }
Richard Smith2316cd82011-09-29 19:11:37 +00008747 if (VD->isConstexpr())
8748 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008749 if (Error != -1) {
8750 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8751 << VD->getDeclName() << Error;
8752 D->setInvalidDecl();
8753 }
8754}
8755
John McCall8b7fd8f12011-01-19 11:48:09 +00008756void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8757 if (var->isInvalidDecl()) return;
8758
John McCall31168b02011-06-15 23:02:42 +00008759 // In ARC, don't allow jumps past the implicit initialization of a
8760 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008761 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008762 var->hasLocalStorage()) {
8763 switch (var->getType().getObjCLifetime()) {
8764 case Qualifiers::OCL_None:
8765 case Qualifiers::OCL_ExplicitNone:
8766 case Qualifiers::OCL_Autoreleasing:
8767 break;
8768
8769 case Qualifiers::OCL_Weak:
8770 case Qualifiers::OCL_Strong:
8771 getCurFunction()->setHasBranchProtectedScope();
8772 break;
8773 }
8774 }
8775
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008776 if (var->isThisDeclarationADefinition() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008777 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008778 getDiagnostics().getDiagnosticLevel(
8779 diag::warn_missing_variable_declarations,
8780 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008781 // Find a previous declaration that's not a definition.
8782 VarDecl *prev = var->getPreviousDecl();
8783 while (prev && prev->isThisDeclarationADefinition())
8784 prev = prev->getPreviousDecl();
8785
8786 if (!prev)
8787 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8788 }
8789
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008790 if (var->getTLSKind() == VarDecl::TLS_Static &&
8791 var->getType().isDestructedType()) {
8792 // GNU C++98 edits for __thread, [basic.start.term]p3:
8793 // The type of an object with thread storage duration shall not
8794 // have a non-trivial destructor.
8795 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8796 if (getLangOpts().CPlusPlus11)
8797 Diag(var->getLocation(), diag::note_use_thread_local);
8798 }
8799
John McCall8b7fd8f12011-01-19 11:48:09 +00008800 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008801 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008802
Richard Smithde63d362012-11-09 23:03:14 +00008803 QualType type = var->getType();
8804 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008805
8806 // __block variables might require us to capture a copy-initializer.
8807 if (var->hasAttr<BlocksAttr>()) {
8808 // It's currently invalid to ever have a __block variable with an
8809 // array type; should we diagnose that here?
8810
8811 // Regardless, we don't want to ignore array nesting when
8812 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008813 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008814 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008815 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008816 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008817 ExprResult result
8818 = PerformMoveOrCopyInitialization(
8819 InitializedEntity::InitializeBlock(poi, type, false),
8820 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008821 if (!result.isInvalid()) {
8822 result = MaybeCreateExprWithCleanups(result);
8823 Expr *init = result.takeAs<Expr>();
8824 Context.setBlockVarCopyInits(var, init);
8825 }
8826 }
8827 }
8828
Richard Smitheda3c842011-11-07 22:16:17 +00008829 Expr *Init = var->getInit();
8830 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008831 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008832
Richard Smithbf830092012-10-29 18:26:47 +00008833 if (!var->getDeclContext()->isDependentContext() &&
8834 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008835 if (IsGlobal && !var->isConstexpr() &&
8836 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8837 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008838 != DiagnosticsEngine::Ignored) {
8839 // Warn about globals which don't have a constant initializer. Don't
8840 // warn about globals with a non-trivial destructor because we already
8841 // warned about them.
8842 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8843 if (!(RD && !RD->hasTrivialDestructor()) &&
8844 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8845 Diag(var->getLocation(), diag::warn_global_constructor)
8846 << Init->getSourceRange();
8847 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008848
Richard Smithd0b4dd62011-12-19 06:19:21 +00008849 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008850 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008851 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8852 SourceLocation DiagLoc = var->getLocation();
8853 // If the note doesn't add any useful information other than a source
8854 // location, fold it into the primary diagnostic.
8855 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8856 diag::note_invalid_subexpr_in_const_expr) {
8857 DiagLoc = Notes[0].first;
8858 Notes.clear();
8859 }
8860 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8861 << var << Init->getSourceRange();
8862 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8863 Diag(Notes[I].first, Notes[I].second);
8864 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008865 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008866 // Check whether the initializer of a const variable of integral or
8867 // enumeration type is an ICE now, since we can't tell whether it was
8868 // initialized by a constant expression if we check later.
8869 var->checkInitIsICE();
8870 }
Richard Smitheda3c842011-11-07 22:16:17 +00008871 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008872
8873 // Require the destructor.
8874 if (const RecordType *recordType = baseType->getAs<RecordType>())
8875 FinalizeVarWithDestructor(var, recordType);
8876}
8877
Richard Smithb2bc2e62011-02-21 20:05:19 +00008878/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8879/// any semantic actions necessary after any initializer has been attached.
8880void
8881Sema::FinalizeDeclaration(Decl *ThisDecl) {
8882 // Note that we are no longer parsing the initializer for this declaration.
8883 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008884
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008885 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008886 if (!VD)
8887 return;
8888
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00008889 checkAttributesAfterMerging(*this, *VD);
8890
Rafael Espindola87198cd2013-08-16 23:18:50 +00008891 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8892 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008893 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008894 VD->dropAttr<UsedAttr>();
8895 }
8896 }
8897
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008898 if (!VD->isInvalidDecl() &&
8899 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8900 if (const VarDecl *Def = VD->getDefinition()) {
8901 if (Def->hasAttr<AliasAttr>()) {
8902 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8903 << VD->getDeclName();
8904 Diag(Def->getLocation(), diag::note_previous_definition);
8905 VD->setInvalidDecl();
8906 }
8907 }
8908 }
8909
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008910 const DeclContext *DC = VD->getDeclContext();
8911 // If there's a #pragma GCC visibility in scope, and this isn't a class
8912 // member, set the visibility of this variable.
Rafael Espindola3ae00052013-05-13 00:12:11 +00008913 if (!DC->isRecord() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008914 AddPushedVisibilityAttribute(VD);
8915
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008916 if (VD->isFileVarDecl())
8917 MarkUnusedFileScopedDecl(VD);
8918
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008919 // Now we have parsed the initializer and can update the table of magic
8920 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008921 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8922 !VD->getType()->isIntegralOrEnumerationType())
8923 return;
8924
8925 for (specific_attr_iterator<TypeTagForDatatypeAttr>
8926 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8927 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8928 I != E; ++I) {
8929 const Expr *MagicValueExpr = VD->getInit();
8930 if (!MagicValueExpr) {
8931 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008932 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008933 llvm::APSInt MagicValueInt;
8934 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8935 Diag(I->getRange().getBegin(),
8936 diag::err_type_tag_for_datatype_not_ice)
8937 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8938 continue;
8939 }
8940 if (MagicValueInt.getActiveBits() > 64) {
8941 Diag(I->getRange().getBegin(),
8942 diag::err_type_tag_for_datatype_too_large)
8943 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8944 continue;
8945 }
8946 uint64_t MagicValue = MagicValueInt.getZExtValue();
8947 RegisterTypeTagForDatatype(I->getArgumentKind(),
8948 MagicValue,
8949 I->getMatchingCType(),
8950 I->getLayoutCompatible(),
8951 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008952 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008953}
8954
Rafael Espindolaab417692013-07-09 12:05:01 +00008955Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8956 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008957 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008958
8959 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008960 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008961
David Majnemer50ce8352013-09-17 23:57:10 +00008962 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008963 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008964 if (Decl *D = Group[i]) {
8965 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8966 if (!FirstDeclaratorInGroup)
8967 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008968 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008969 }
Richard Smith2abf6762011-02-23 00:37:57 +00008970
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008971 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00008972 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008973 HandleTagNumbering(*this, Tag);
David Majnemer50ce8352013-09-17 23:57:10 +00008974 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8975 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8976 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008977 }
David Blaikie095deba2012-11-14 01:52:05 +00008978
Rafael Espindolaab417692013-07-09 12:05:01 +00008979 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00008980}
8981
8982/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8983/// group, performing any necessary semantic checking.
8984Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00008985Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00008986 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00008987 // C++0x [dcl.spec.auto]p7:
8988 // If the type deduced for the template parameter U is not the same in each
8989 // deduction, the program is ill-formed.
8990 // FIXME: When initializer-list support is added, a distinction is needed
8991 // between the deduced type U and the deduced type which 'auto' stands for.
8992 // auto a = 0, b = { 1, 2, 3 };
8993 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00008994 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00008995 QualType Deduced;
8996 CanQualType DeducedCanon;
8997 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008998 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00008999 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9000 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009001 // Don't reissue diagnostics when instantiating a template.
9002 if (AT && D->isInvalidDecl())
9003 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009004 QualType U = AT ? AT->getDeducedType() : QualType();
9005 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009006 CanQualType UCanon = Context.getCanonicalType(U);
9007 if (Deduced.isNull()) {
9008 Deduced = U;
9009 DeducedCanon = UCanon;
9010 DeducedDecl = D;
9011 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009012 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9013 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009014 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009015 << Deduced << DeducedDecl->getDeclName()
9016 << U << D->getDeclName()
9017 << DeducedDecl->getInit()->getSourceRange()
9018 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009019 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009020 break;
9021 }
9022 }
9023 }
9024 }
9025 }
9026
Rafael Espindolaab417692013-07-09 12:05:01 +00009027 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009028
Rafael Espindolaab417692013-07-09 12:05:01 +00009029 return DeclGroupPtrTy::make(
9030 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009031}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009032
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009033void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009034 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009035}
9036
Rafael Espindolaab417692013-07-09 12:05:01 +00009037void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009038 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009039 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009040 return;
9041
9042 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9043 Group[0]->getLocation())
9044 == DiagnosticsEngine::Ignored)
9045 return;
9046
Rafael Espindolaab417692013-07-09 12:05:01 +00009047 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009048 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009049 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009050 // additional declaration references:
9051 // 'typedef struct S {} S;'
9052 // 'typedef struct S *S;'
9053 // 'struct S *pS;'
9054 // FinalizeDeclaratorGroup adds these as separate declarations.
9055 Decl *MaybeTagDecl = Group[0];
9056 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009057 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009058 }
9059 }
9060
9061 // See if there are any new comments that are not attached to a decl.
9062 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9063 if (!Comments.empty() &&
9064 !Comments.back()->isAttached()) {
9065 // There is at least one comment that not attached to a decl.
9066 // Maybe it should be attached to one of these decls?
9067 //
9068 // Note that this way we pick up not only comments that precede the
9069 // declaration, but also comments that *follow* the declaration -- thanks to
9070 // the lookahead in the lexer: we've consumed the semicolon and looked
9071 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009072 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009073 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009074 }
9075}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009076
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009077/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9078/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009079Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009080 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009081
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009082 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009083
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009084 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009085 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009086 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009087 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009088 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009089 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9090 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009091 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009092 Diag(DS.getStorageClassSpecLoc(),
9093 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009094 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009095 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009096
Richard Smithb4a9e862013-04-12 22:46:28 +00009097 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9098 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9099 << DeclSpec::getSpecifierName(TSCS);
9100 if (DS.isConstexprSpecified())
9101 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009102 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009103
Richard Smithb4a9e862013-04-12 22:46:28 +00009104 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009105
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009106 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009107 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009108
David Blaikiebbafb8a2012-03-11 07:00:24 +00009109 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009110 // Check that there are no default arguments inside the type of this
9111 // parameter.
9112 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009113
9114 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9115 if (D.getCXXScopeSpec().isSet()) {
9116 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9117 << D.getCXXScopeSpec().getRange();
9118 D.getCXXScopeSpec().clear();
9119 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009120 }
9121
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009122 // Ensure we have a valid name
9123 IdentifierInfo *II = 0;
9124 if (D.hasName()) {
9125 II = D.getIdentifier();
9126 if (!II) {
9127 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009128 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009129 D.setInvalidType(true);
9130 }
9131 }
9132
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009133 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009134 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009135 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9136 ForRedeclaration);
9137 LookupName(R, S);
9138 if (R.isSingleResult()) {
9139 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009140 if (PrevDecl->isTemplateParameter()) {
9141 // Maybe we will complain about the shadowed template parameter.
9142 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9143 // Just pretend that we didn't see the previous declaration.
9144 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009145 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009146 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009147 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009148
Chris Lattnerd9773512009-01-21 02:38:50 +00009149 // Recover by removing the name
9150 II = 0;
9151 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009152 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009153 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009154 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009155 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009156
John McCallf7b2fb52010-01-22 00:28:27 +00009157 // Temporarily put parameter variables in the translation unit, not
9158 // the enclosing context. This prevents them from accidentally
9159 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009160 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009161 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009162 D.getIdentifierLoc(), II,
9163 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009164 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009165
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009166 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009167 New->setInvalidDecl();
9168
9169 assert(S->isFunctionPrototypeScope());
9170 assert(S->getFunctionPrototypeDepth() >= 1);
9171 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9172 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009173
Douglas Gregor91f84212008-12-11 16:49:14 +00009174 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009175 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009176 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009177 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009178
Douglas Gregor758a8692009-06-17 21:51:59 +00009179 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009180
Douglas Gregor41866812011-09-12 18:37:38 +00009181 if (D.getDeclSpec().isModulePrivateSpecified())
9182 Diag(New->getLocation(), diag::err_module_private_local)
9183 << 1 << New->getDeclName()
9184 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9185 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9186
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009187 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009188 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9189 }
John McCall48871652010-08-21 09:40:31 +00009190 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009191}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009192
John McCalla3ccba02010-06-04 11:21:44 +00009193/// \brief Synthesizes a variable for a parameter arising from a
9194/// typedef.
9195ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9196 SourceLocation Loc,
9197 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009198 /* FIXME: setting StartLoc == Loc.
9199 Would it be worth to modify callers so as to provide proper source
9200 location for the unnamed parameters, embedding the parameter's type? */
9201 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009202 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009203 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009204 Param->setImplicit();
9205 return Param;
9206}
9207
John McCallc5990642010-08-24 09:05:15 +00009208void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9209 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009210 // Don't diagnose unused-parameter errors in template instantiations; we
9211 // will already have done so in the template itself.
9212 if (!ActiveTemplateInstantiations.empty())
9213 return;
9214
9215 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009216 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009217 !(*Param)->hasAttr<UnusedAttr>()) {
9218 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9219 << (*Param)->getDeclName();
9220 }
9221 }
9222}
9223
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009224void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9225 ParmVarDecl * const *ParamEnd,
9226 QualType ReturnTy,
9227 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009228 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009229 return;
9230
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009231 // Warn if the return value is pass-by-value and larger than the specified
9232 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009233 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009234 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009235 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009236 Diag(D->getLocation(), diag::warn_return_value_size)
9237 << D->getDeclName() << Size;
9238 }
9239
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009240 // Warn if any parameter is pass-by-value and larger than the specified
9241 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009242 for (; Param != ParamEnd; ++Param) {
9243 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009244 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009245 continue;
9246 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009247 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009248 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9249 << (*Param)->getDeclName() << Size;
9250 }
9251}
9252
Abramo Bagnaradff19302011-03-08 08:55:46 +00009253ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9254 SourceLocation NameLoc, IdentifierInfo *Name,
9255 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009256 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009257 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009258 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009259 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009260 T->isObjCLifetimeType()) {
9261
9262 Qualifiers::ObjCLifetime lifetime;
9263
9264 // Special cases for arrays:
9265 // - if it's const, use __unsafe_unretained
9266 // - otherwise, it's an error
9267 if (T->isArrayType()) {
9268 if (!T.isConstQualified()) {
9269 DelayedDiagnostics.add(
9270 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009271 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009272 }
9273 lifetime = Qualifiers::OCL_ExplicitNone;
9274 } else {
9275 lifetime = T->getObjCARCImplicitLifetime();
9276 }
9277 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009278 }
9279
Abramo Bagnaradff19302011-03-08 08:55:46 +00009280 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009281 Context.getAdjustedParameterType(T),
9282 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009283 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009284
9285 // Parameters can not be abstract class types.
9286 // For record types, this is done by the AbstractClassUsageDiagnoser once
9287 // the class has been completely parsed.
9288 if (!CurContext->isRecord() &&
9289 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9290 AbstractParamType))
9291 New->setInvalidDecl();
9292
9293 // Parameter declarators cannot be interface types. All ObjC objects are
9294 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009295 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009296 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009297 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009298 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009299 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009300 T = Context.getObjCObjectPointerType(T);
9301 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009302 }
9303
9304 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9305 // duration shall not be qualified by an address-space qualifier."
9306 // Since all parameters have automatic store duration, they can not have
9307 // an address space.
9308 if (T.getAddressSpace() != 0) {
9309 Diag(NameLoc, diag::err_arg_with_address_space);
9310 New->setInvalidDecl();
9311 }
9312
9313 return New;
9314}
9315
Douglas Gregor170512f2009-04-01 23:51:29 +00009316void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9317 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009318 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009319
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009320 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9321 // for a K&R function.
9322 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009323 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9324 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009325 if (FTI.ArgInfo[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009326 SmallString<256> Code;
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009327 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00009328 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00009329 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00009330 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00009331 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00009332 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009333
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009334 // Implicitly declare the argument as type 'int' for lack of a better
9335 // type.
John McCall084e83d2011-03-24 11:26:52 +00009336 AttributeFactory attrs;
9337 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009338 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009339 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00009340 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009341 PrevSpec, DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009342 // Use the identifier location for the type source range.
9343 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9344 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009345 Declarator ParamD(DS, Declarator::KNRTypeListContext);
9346 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00009347 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009348 }
9349 }
Mike Stump11289f42009-09-09 15:08:12 +00009350 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009351}
9352
Richard Smith79a52e52012-04-17 22:30:01 +00009353Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009354 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009355 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009356 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009357
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009358 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009359 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009360 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009361}
9362
Anders Carlsson2a45e402012-12-18 01:29:20 +00009363static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9364 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009365 // Don't warn about invalid declarations.
9366 if (FD->isInvalidDecl())
9367 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009368
Anders Carlsson31c7e882009-12-09 03:30:09 +00009369 // Or declarations that aren't global.
9370 if (!FD->isGlobal())
9371 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009372
Anders Carlsson31c7e882009-12-09 03:30:09 +00009373 // Don't warn about C++ member functions.
9374 if (isa<CXXMethodDecl>(FD))
9375 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009376
Anders Carlsson31c7e882009-12-09 03:30:09 +00009377 // Don't warn about 'main'.
9378 if (FD->isMain())
9379 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009380
Anders Carlsson31c7e882009-12-09 03:30:09 +00009381 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009382 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009383 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009384
9385 // Don't warn about function templates.
9386 if (FD->getDescribedFunctionTemplate())
9387 return false;
9388
9389 // Don't warn about function template specializations.
9390 if (FD->isFunctionTemplateSpecialization())
9391 return false;
9392
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009393 // Don't warn for OpenCL kernels.
9394 if (FD->hasAttr<OpenCLKernelAttr>())
9395 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009396
Anders Carlsson31c7e882009-12-09 03:30:09 +00009397 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009398 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9399 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009400 // Ignore any declarations that occur in function or method
9401 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009402 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009403 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009404
Anders Carlsson31c7e882009-12-09 03:30:09 +00009405 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009406 if (FD->getNumParams() == 0)
9407 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009408 break;
9409 }
Richard Smith541b38b2013-09-20 01:15:31 +00009410
Anders Carlsson31c7e882009-12-09 03:30:09 +00009411 return MissingPrototype;
9412}
9413
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009414void
9415Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9416 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009417 // Don't complain if we're in GNU89 mode and the previous definition
9418 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009419 const FunctionDecl *Definition = EffectiveDefinition;
9420 if (!Definition)
9421 if (!FD->isDefined(Definition))
9422 return;
9423
9424 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009425 return;
9426
9427 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9428 Definition->getStorageClass() == SC_Extern)
9429 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009430 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009431 else
9432 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9433
9434 Diag(Definition->getLocation(), diag::note_previous_definition);
9435 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009436}
Faisal Valia17d19f2013-11-07 05:17:06 +00009437
9438
Faisal Valic1a6dc42013-10-23 16:10:50 +00009439static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9440 Sema &S) {
9441 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009442
9443 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009444 LSI->CallOperator = CallOperator;
9445 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009446 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009447 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9448
9449 if (LCD == LCD_None)
9450 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9451 else if (LCD == LCD_ByCopy)
9452 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9453 else if (LCD == LCD_ByRef)
9454 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9455 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9456
9457 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9458 LSI->Mutable = !CallOperator->isConst();
9459
Faisal Valia17d19f2013-11-07 05:17:06 +00009460 // Add the captures to the LSI so they can be noted as already
9461 // captured within tryCaptureVar.
9462 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9463 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9464 if (C->capturesVariable()) {
9465 VarDecl *VD = C->getCapturedVar();
9466 if (VD->isInitCapture())
9467 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9468 QualType CaptureType = VD->getType();
9469 const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9470 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9471 /*RefersToEnclosingLocal*/true, C->getLocation(),
9472 /*EllipsisLoc*/C->isPackExpansion()
9473 ? C->getEllipsisLoc() : SourceLocation(),
9474 CaptureType, /*Expr*/ 0);
9475
9476 } else if (C->capturesThis()) {
9477 LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9478 S.getCurrentThisType(), /*Expr*/ 0);
9479 }
9480 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009481}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009482
John McCall48871652010-08-21 09:40:31 +00009483Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009484 // Clear the last template instantiation error context.
9485 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9486
Douglas Gregor17a7c122009-06-24 00:54:41 +00009487 if (!D)
9488 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009489 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009490
John McCall48871652010-08-21 09:40:31 +00009491 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009492 FD = FunTmpl->getTemplatedDecl();
9493 else
John McCall48871652010-08-21 09:40:31 +00009494 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009495 // If we are instantiating a generic lambda call operator, push
9496 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009497 // that's already been calculated (ActOnLambdaExpr) to prime the current
9498 // LambdaScopeInfo.
9499 // When the template operator is being specialized, the LambdaScopeInfo,
9500 // has to be properly restored so that tryCaptureVariable doesn't try
9501 // and capture any new variables. In addition when calculating potential
9502 // captures during transformation of nested lambdas, it is necessary to
9503 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009504 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009505 assert(ActiveTemplateInstantiations.size() &&
9506 "There should be an active template instantiation on the stack "
9507 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009508 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009509 }
9510 else
9511 // Enter a new function scope
9512 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009513
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009514 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009515 if (!FD->isLateTemplateParsed())
9516 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009517
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009518 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009519 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009520 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9521 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009522 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009523 FD->setInvalidDecl();
9524 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009525 }
9526
Eli Friedman9ad72442009-03-04 07:30:59 +00009527 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009528 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009529 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009530 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009531 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009532 RequireCompleteType(FD->getLocation(), ResultType,
9533 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009534 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009535
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009536 // GNU warning -Wmissing-prototypes:
9537 // Warn if a global function is defined without a previous
9538 // prototype declaration. This warning is issued even if the
9539 // definition itself provides a prototype. The aim is to detect
9540 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009541 const FunctionDecl *PossibleZeroParamPrototype = 0;
9542 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009543 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009544
Anders Carlsson2a45e402012-12-18 01:29:20 +00009545 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009546 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009547 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009548 if (TypeSourceInfo *TI =
9549 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9550 TypeLoc TL = TI->getTypeLoc();
9551 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9552 Diag(PossibleZeroParamPrototype->getLocation(),
9553 diag::note_declaration_not_a_prototype)
9554 << PossibleZeroParamPrototype
9555 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9556 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009557 }
9558 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009559
Douglas Gregor67da0d92009-05-15 17:59:04 +00009560 if (FnBodyScope)
9561 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009562
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009563 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009564 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9565 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009566
9567 // Introduce our parameters into the function scope
9568 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9569 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00009570 Param->setOwningFunction(FD);
9571
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009572 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009573 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009574 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009575
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009576 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009577 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009578 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009579
James Molloy6f8780b2012-02-29 10:24:19 +00009580 // If we had any tags defined in the function prototype,
9581 // introduce them into the function scope.
9582 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009583 for (ArrayRef<NamedDecl *>::iterator
9584 I = FD->getDeclsInPrototypeScope().begin(),
9585 E = FD->getDeclsInPrototypeScope().end();
9586 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009587 NamedDecl *D = *I;
9588
9589 // Some of these decls (like enums) may have been pinned to the translation unit
9590 // for lack of a real context earlier. If so, remove from the translation unit
9591 // and reattach to the current context.
9592 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9593 // Is the decl actually in the context?
9594 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9595 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9596 if (*DI == D) {
9597 Context.getTranslationUnitDecl()->removeDecl(D);
9598 break;
9599 }
9600 }
9601 // Either way, reassign the lexical decl context to our FunctionDecl.
9602 D->setLexicalDeclContext(CurContext);
9603 }
9604
9605 // If the decl has a non-null name, make accessible in the current scope.
9606 if (!D->getName().empty())
9607 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9608
9609 // Similarly, dive into enums and fish their constants out, making them
9610 // accessible in this scope.
9611 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9612 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9613 EE = ED->enumerator_end(); EI != EE; ++EI)
David Blaikie40ed2972012-06-06 20:45:41 +00009614 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009615 }
9616 }
9617 }
9618
Richard Smith79a52e52012-04-17 22:30:01 +00009619 // Ensure that the function's exception specification is instantiated.
9620 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9621 ResolveExceptionSpec(D->getLocation(), FPT);
9622
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009623 // Checking attributes of current function definition
9624 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009625 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009626 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009627 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009628 // Microsoft accepts dllimport for functions defined within class scope.
9629 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009630 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009631 Diag(FD->getLocation(),
9632 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009633 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009634 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009635 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009636 }
9637
9638 // Visual C++ appears to not think this is an issue, so only issue
9639 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009640 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009641 // If a symbol previously declared dllimport is later defined, the
9642 // attribute is ignored in subsequent references, and a warning is
9643 // emitted.
9644 Diag(FD->getLocation(),
9645 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009646 << FD << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009647 }
9648 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009649 // We want to attach documentation to original Decl (which might be
9650 // a function template).
9651 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009652 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009653}
9654
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009655/// \brief Given the set of return statements within a function body,
9656/// compute the variables that are subject to the named return value
9657/// optimization.
9658///
9659/// Each of the variables that is subject to the named return value
9660/// optimization will be marked as NRVO variables in the AST, and any
9661/// return statement that has a marked NRVO variable as its NRVO candidate can
9662/// use the named return value optimization.
9663///
9664/// This function applies a very simplistic algorithm for NRVO: if every return
9665/// statement in the function has the same NRVO candidate, that candidate is
9666/// the NRVO variable.
9667///
9668/// FIXME: Employ a smarter algorithm that accounts for multiple return
9669/// statements and the lifetimes of the NRVO candidates. We should be able to
9670/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009671void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009672 ReturnStmt **Returns = Scope->Returns.data();
9673
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009674 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009675 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009676 if (!Returns[I]->getNRVOCandidate())
9677 return;
9678
9679 if (!NRVOCandidate)
9680 NRVOCandidate = Returns[I]->getNRVOCandidate();
9681 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9682 return;
9683 }
9684
9685 if (NRVOCandidate)
9686 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9687}
9688
Richard Smith1ab34b32012-11-19 21:13:18 +00009689bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009690 // We cannot skip the body of a function (or function template) which is
9691 // constexpr, since we may need to evaluate its body in order to parse the
9692 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009693 // We cannot skip the body of a function with an undeduced return type,
9694 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009695 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009696 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009697 return false;
9698 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009699}
9700
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009701Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009702 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009703 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009704 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009705 MD->setHasSkippedBody();
9706 return ActOnFinishFunctionBody(Decl, 0);
9707}
9708
John McCallfaf5fb42010-08-26 23:41:50 +00009709Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009710 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009711}
9712
John McCallb268a282010-08-23 23:25:46 +00009713Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9714 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009715 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009716
Ted Kremenek0b405322010-03-23 00:13:23 +00009717 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009718 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009719
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009720 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009721 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009722
Richard Smith7500ab22013-05-10 04:31:10 +00009723 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009724 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009725 // If the function has a deduced result type but contains no 'return'
9726 // statements, the result type as written must be exactly 'auto', and
9727 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009728 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009729 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009730 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009731 FD->setInvalidDecl();
9732 } else {
9733 // Substitute 'void' for the 'auto' in the type.
9734 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009735 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009736 Context.adjustDeducedFunctionResultType(
9737 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009738 }
9739 }
9740
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009741 // The only way to be included in UndefinedButUsed is if there is an
9742 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009743 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009744 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009745 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009746 UndefinedButUsed.erase(FD);
9747 else if (FD->isInlined() &&
9748 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9749 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9750 UndefinedButUsed.erase(FD);
9751 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009752
John McCall5ed3caf2012-02-14 19:50:52 +00009753 // If the function implicitly returns zero (like 'main') or is naked,
9754 // don't complain about missing return statements.
9755 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009756 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009757
Francois Pichet3abc9b82011-05-11 02:14:46 +00009758 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009759 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009760 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009761 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9762
Douglas Gregor88d292c2010-05-13 16:44:06 +00009763 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009764 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009765 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009766 FD->getReturnType(), FD);
9767
Douglas Gregor88d292c2010-05-13 16:44:06 +00009768 // If this is a constructor, we need a vtable.
9769 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9770 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009771
Jordan Rosed39e5f12012-07-02 21:19:23 +00009772 // Try to apply the named return value optimization. We have to check
9773 // if we can do this here because lambdas keep return statements around
9774 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009775 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009776 !FD->isDependentContext())
9777 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009778 }
9779
Douglas Gregor21f46922012-02-08 20:17:14 +00009780 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9781 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009782 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009783 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009784 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009785 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009786 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009787 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009788 MD->getReturnType(), MD);
9789
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009790 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009791 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009792 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009793 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009794 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9795 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009796 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009797 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009798 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9799 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009800 bool isDesignated =
9801 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009802 assert(isDesignated && InitMethod);
9803 (void)isDesignated;
9804 Diag(MD->getLocation(),
9805 diag::warn_objc_designated_init_missing_super_call);
9806 Diag(InitMethod->getLocation(),
9807 diag::note_objc_designated_init_marked_here);
9808 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9809 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009810 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9811 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9812 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9813 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009814 } else {
John McCall48871652010-08-21 09:40:31 +00009815 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009816 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009817
Jordan Rose2afd6612012-10-19 16:05:26 +00009818 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009819 "This should only be set for ObjC methods, which should have been "
9820 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009821
Chris Lattnere2473062007-05-28 06:28:18 +00009822 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009823 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009824 // C++ constructors that have function-try-blocks can't have return
9825 // statements in the handlers of that block. (C++ [except.handle]p14)
9826 // Verify this.
9827 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9828 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9829
Richard Smithdef8bdb2011-08-12 18:44:32 +00009830 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009831 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009832 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009833 !hasAnyUnrecoverableErrorsInThisFunction() &&
9834 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009835 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009836
John McCalldeb646e2010-08-04 01:04:25 +00009837 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9838 if (!Destructor->getParent()->isDependentType())
9839 CheckDestructor(Destructor);
9840
John McCalla6309952010-03-16 21:39:52 +00009841 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9842 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009843 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009844
9845 // If any errors have occurred, clear out any temporaries that may have
9846 // been leftover. This ensures that these temporaries won't be picked up for
9847 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009848 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009849 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009850 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009851 }
9852 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9853 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009854 // Since the body is valid, issue any analysis-based warnings that are
9855 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009856 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009857 }
9858
Richard Smith3607ffe2012-02-13 03:54:03 +00009859 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9860 (!CheckConstexprFunctionDecl(FD) ||
9861 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009862 FD->setInvalidDecl();
9863
John McCall28fc7092011-11-10 05:35:25 +00009864 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009865 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009866 assert(MaybeODRUseExprs.empty() &&
9867 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009868 }
9869
John McCalle99d5f32010-03-25 22:08:03 +00009870 if (!IsInstantiation)
9871 PopDeclContext();
9872
Eli Friedman71c80552012-01-05 03:35:19 +00009873 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009874 // If any errors have occurred, clear out any temporaries that may have
9875 // been leftover. This ensures that these temporaries won't be picked up for
9876 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009877 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009878 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009879 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009880
John McCall48871652010-08-21 09:40:31 +00009881 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009882}
9883
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009884
9885/// When we finish delayed parsing of an attribute, we must attach it to the
9886/// relevant Decl.
9887void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9888 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009889 // Always attach attributes to the underlying decl.
9890 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9891 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009892 ProcessDeclAttributeList(S, D, Attrs.getList());
9893
9894 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9895 if (Method->isStatic())
9896 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009897}
9898
9899
Chris Lattnerac18be92006-11-20 06:49:47 +00009900/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9901/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009902NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009903 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009904 // Before we produce a declaration for an implicitly defined
9905 // function, see whether there was a locally-scoped declaration of
9906 // this name as a function or variable. If so, use that
9907 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009908 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9909 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9910 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9911 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009912 }
9913
Chris Lattner00e26072008-05-05 21:18:06 +00009914 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009915 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009916 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009917 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009918 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009919 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009920 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009921 diag_id = diag::warn_implicit_function_decl;
9922 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009923
Hans Wennborg70a13242011-12-08 15:56:07 +00009924 // Because typo correction is expensive, only do it if the implicit
9925 // function declaration is going to be treated as an error.
9926 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9927 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009928 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009929 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009930 LookupOrdinaryName, S, 0, Validator)))
9931 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9932 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009933 }
9934
Chris Lattnerac18be92006-11-20 06:49:47 +00009935 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009936 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009937 AttributeFactory attrFactory;
9938 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009939 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009940 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9941 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009942 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009943 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009944 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009945 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009946 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9947 /*IsAmbiguous=*/false,
9948 /*RParenLoc=*/NoLoc,
9949 /*ArgInfo=*/0,
9950 /*NumArgs=*/0,
9951 /*EllipsisLoc=*/NoLoc,
9952 /*RParenLoc=*/NoLoc,
9953 /*TypeQuals=*/0,
9954 /*RefQualifierIsLvalueRef=*/true,
9955 /*RefQualifierLoc=*/NoLoc,
9956 /*ConstQualifierLoc=*/NoLoc,
9957 /*VolatileQualifierLoc=*/NoLoc,
9958 /*MutableLoc=*/NoLoc,
9959 EST_None,
9960 /*ESpecLoc=*/NoLoc,
9961 /*Exceptions=*/0,
9962 /*ExceptionRanges=*/0,
9963 /*NumExceptions=*/0,
9964 /*NoexceptExpr=*/0,
9965 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009966 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009967 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009968 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009969
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009970 // Insert this function into translation-unit scope.
9971
9972 DeclContext *PrevDC = CurContext;
9973 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009974
Jordan Rosed03d99d2013-03-05 01:27:54 +00009975 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00009976 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00009977
9978 CurContext = PrevDC;
9979
Douglas Gregore711f702009-02-14 18:57:46 +00009980 AddKnownFunctionAttributes(FD);
9981
Steve Naroff3913ea42008-04-04 14:32:09 +00009982 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00009983}
9984
Douglas Gregore711f702009-02-14 18:57:46 +00009985/// \brief Adds any function attributes that we know a priori based on
9986/// the declaration of this function.
9987///
9988/// These attributes can apply both to implicitly-declared builtins
9989/// (like __builtin___printf_chk) or to library-declared functions
9990/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00009991///
9992/// We need to check for duplicate attributes both here and where user-written
9993/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00009994void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9995 if (FD->isInvalidDecl())
9996 return;
9997
9998 // If this is a built-in function, map its builtin attributes to
9999 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010000 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010001 // Handle printf-formatting attributes.
10002 unsigned FormatIdx;
10003 bool HasVAListArg;
10004 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010005 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010006 const char *fmt = "printf";
10007 unsigned int NumParams = FD->getNumParams();
10008 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10009 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10010 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010011 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010012 &Context.Idents.get(fmt),
10013 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010014 HasVAListArg ? 0 : FormatIdx+2,
10015 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010016 }
Douglas Gregore711f702009-02-14 18:57:46 +000010017 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010018 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10019 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010020 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010021 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010022 &Context.Idents.get("scanf"),
10023 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010024 HasVAListArg ? 0 : FormatIdx+2,
10025 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010026 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010027
10028 // Mark const if we don't care about errno and that is the only
10029 // thing preventing the function from being const. This allows
10030 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010031 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010032 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010033 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010034 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010035 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010036
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010037 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010038 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010039 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10040 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010041 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010042 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010043 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010044 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010045 }
10046
10047 IdentifierInfo *Name = FD->getIdentifier();
10048 if (!Name)
10049 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010050 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010051 FD->getDeclContext()->isTranslationUnit()) ||
10052 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010053 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010054 LinkageSpecDecl::lang_c)) {
10055 // Okay: this could be a libc/libm/Objective-C function we know
10056 // about.
10057 } else
10058 return;
10059
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010060 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010061 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010062 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010063 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010064 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010065 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010066 Name->isStr("vasprintf") ? 0 : 3,
10067 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010068 }
Jordan Rose742c6072012-08-08 21:17:31 +000010069
10070 if (Name->isStr("__CFStringMakeConstantString")) {
10071 // We already have a __builtin___CFStringMakeConstantString,
10072 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010073 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010074 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10075 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010076 }
Douglas Gregore711f702009-02-14 18:57:46 +000010077}
Chris Lattner302b4be2006-11-19 02:31:38 +000010078
John McCall703a3f82009-10-24 08:00:42 +000010079TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010080 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010081 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010082 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010083
John McCallbcd03502009-12-07 02:54:59 +000010084 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010085 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010086 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010087 }
10088
Chris Lattner18b19622007-01-22 07:39:13 +000010089 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010090 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010091 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010092 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010093 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010094 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010095
John McCall04fcd0d2011-02-01 08:20:08 +000010096 // Bail out immediately if we have an invalid declaration.
10097 if (D.isInvalidType()) {
10098 NewTD->setInvalidDecl();
10099 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010100 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010101
Douglas Gregor41866812011-09-12 18:37:38 +000010102 if (D.getDeclSpec().isModulePrivateSpecified()) {
10103 if (CurContext->isFunctionOrMethod())
10104 Diag(NewTD->getLocation(), diag::err_module_private_local)
10105 << 2 << NewTD->getDeclName()
10106 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10107 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10108 else
10109 NewTD->setModulePrivate();
10110 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010111
John McCall04fcd0d2011-02-01 08:20:08 +000010112 // C++ [dcl.typedef]p8:
10113 // If the typedef declaration defines an unnamed class (or
10114 // enum), the first typedef-name declared by the declaration
10115 // to be that class type (or enum type) is used to denote the
10116 // class type (or enum type) for linkage purposes only.
10117 // We need to check whether the type was declared in the declaration.
10118 switch (D.getDeclSpec().getTypeSpecType()) {
10119 case TST_enum:
10120 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010121 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010122 case TST_union:
10123 case TST_class: {
10124 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10125
10126 // Do nothing if the tag is not anonymous or already has an
10127 // associated typedef (from an earlier typedef in this decl group).
10128 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010129 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010130
10131 // A well-formed anonymous tag must always be a TUK_Definition.
10132 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10133
10134 // The type must match the tag exactly; no qualifiers allowed.
10135 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10136 break;
10137
10138 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010139 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010140 break;
10141 }
10142
10143 default:
10144 break;
10145 }
10146
Steve Narofff93b6722007-08-28 20:14:24 +000010147 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010148}
10149
Douglas Gregord9034f02009-05-14 16:41:31 +000010150
Richard Smith4b38ded2012-03-14 23:13:10 +000010151/// \brief Check that this is a valid underlying type for an enum declaration.
10152bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10153 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10154 QualType T = TI->getType();
10155
Eli Friedman52f32b92012-12-18 02:37:32 +000010156 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010157 return false;
10158
Eli Friedman52f32b92012-12-18 02:37:32 +000010159 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10160 if (BT->isInteger())
10161 return false;
10162
Richard Smith4b38ded2012-03-14 23:13:10 +000010163 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10164 return true;
10165}
10166
10167/// Check whether this is a valid redeclaration of a previous enumeration.
10168/// \return true if the redeclaration was invalid.
10169bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10170 QualType EnumUnderlyingTy,
10171 const EnumDecl *Prev) {
10172 bool IsFixed = !EnumUnderlyingTy.isNull();
10173
10174 if (IsScoped != Prev->isScoped()) {
10175 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10176 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010177 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010178 return true;
10179 }
10180
10181 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010182 if (!EnumUnderlyingTy->isDependentType() &&
10183 !Prev->getIntegerType()->isDependentType() &&
10184 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010185 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010186 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010187 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10188 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010189 Diag(Prev->getLocation(), diag::note_previous_declaration)
10190 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010191 return true;
10192 }
10193 } else if (IsFixed != Prev->isFixed()) {
10194 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10195 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010196 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010197 return true;
10198 }
10199
10200 return false;
10201}
10202
Joao Matosdc86f942012-08-31 18:45:21 +000010203/// \brief Get diagnostic %select index for tag kind for
10204/// redeclaration diagnostic message.
10205/// WARNING: Indexes apply to particular diagnostics only!
10206///
10207/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010208static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010209 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010210 case TTK_Struct: return 0;
10211 case TTK_Interface: return 1;
10212 case TTK_Class: return 2;
10213 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010214 }
Joao Matosdc86f942012-08-31 18:45:21 +000010215}
10216
10217/// \brief Determine if tag kind is a class-key compatible with
10218/// class for redeclaration (class, struct, or __interface).
10219///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010220/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010221static bool isClassCompatTagKind(TagTypeKind Tag)
10222{
10223 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10224}
10225
Douglas Gregord9034f02009-05-14 16:41:31 +000010226/// \brief Determine whether a tag with a given kind is acceptable
10227/// as a redeclaration of the given tag declaration.
10228///
10229/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010230bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010231 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010232 SourceLocation NewTagLoc,
10233 const IdentifierInfo &Name) {
10234 // C++ [dcl.type.elab]p3:
10235 // The class-key or enum keyword present in the
10236 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010237 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010238 // refers. This rule also applies to the form of
10239 // elaborated-type-specifier that declares a class-name or
10240 // friend class since it can be construed as referring to the
10241 // definition of the class. Thus, in any
10242 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010243 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010244 // used to refer to a union (clause 9), and either the class or
10245 // struct class-key shall be used to refer to a class (clause 9)
10246 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010247 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010248 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010249 if (OldTag == NewTag)
10250 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010251
Joao Matosdc86f942012-08-31 18:45:21 +000010252 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010253 // Warn about the struct/class tag mismatch.
10254 bool isTemplate = false;
10255 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10256 isTemplate = Record->getDescribedClassTemplate();
10257
Richard Trieucaa33d32011-06-10 03:11:26 +000010258 if (!ActiveTemplateInstantiations.empty()) {
10259 // In a template instantiation, do not offer fix-its for tag mismatches
10260 // since they usually mess up the template instead of fixing the problem.
10261 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010262 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10263 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010264 return true;
10265 }
10266
10267 if (isDefinition) {
10268 // On definitions, check previous tags and issue a fix-it for each
10269 // one that doesn't match the current tag.
10270 if (Previous->getDefinition()) {
10271 // Don't suggest fix-its for redefinitions.
10272 return true;
10273 }
10274
10275 bool previousMismatch = false;
10276 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10277 E(Previous->redecls_end()); I != E; ++I) {
10278 if (I->getTagKind() != NewTag) {
10279 if (!previousMismatch) {
10280 previousMismatch = true;
10281 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010282 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10283 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010284 }
10285 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010286 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010287 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010288 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010289 }
10290 }
10291 return true;
10292 }
10293
10294 // Check for a previous definition. If current tag and definition
10295 // are same type, do nothing. If no definition, but disagree with
10296 // with previous tag type, give a warning, but no fix-it.
10297 const TagDecl *Redecl = Previous->getDefinition() ?
10298 Previous->getDefinition() : Previous;
10299 if (Redecl->getTagKind() == NewTag) {
10300 return true;
10301 }
10302
Douglas Gregord9034f02009-05-14 16:41:31 +000010303 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010304 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10305 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010306 Diag(Redecl->getLocation(), diag::note_previous_use);
10307
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010308 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010309 if (Previous->getDefinition()) {
10310 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010311 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010312 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010313 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010314 }
10315
Douglas Gregord9034f02009-05-14 16:41:31 +000010316 return true;
10317 }
10318 return false;
10319}
10320
Steve Naroff30d242c2007-09-15 18:49:24 +000010321/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010322/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010323/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010324/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010325///
10326/// IsTypeSpecifier is true if this is a type-specifier (or
10327/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010328Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010329 SourceLocation KWLoc, CXXScopeSpec &SS,
10330 IdentifierInfo *Name, SourceLocation NameLoc,
10331 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010332 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010333 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010334 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010335 SourceLocation ScopedEnumKWLoc,
10336 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010337 TypeResult UnderlyingType,
10338 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010339 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010340 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010341 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010342 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010343 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010344
Douglas Gregord6ab8742009-05-28 23:31:59 +000010345 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010346 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010347 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010348
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010349 // FIXME: Check explicit specializations more carefully.
10350 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010351 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010352
10353 // We only need to do this matching if we have template parameters
10354 // or a scope specifier, which also conveniently avoids this work
10355 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010356 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010357 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010358 if (TemplateParameterList *TemplateParams =
10359 MatchTemplateParametersToScopeSpecifier(
10360 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10361 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010362 if (Kind == TTK_Enum) {
10363 Diag(KWLoc, diag::err_enum_template);
10364 return 0;
10365 }
10366
Douglas Gregor3dad8422009-09-26 06:47:28 +000010367 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010368 // This is a declaration or definition of a class template (which may
10369 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010370
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010371 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010372 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010373
Douglas Gregore93e46c2009-07-22 23:48:44 +000010374 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010375 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010376 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010377 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010378 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010379 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010380 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010381 return Result.get();
10382 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010383 // The "template<>" header is extraneous.
10384 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010385 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010386 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010387 }
Mike Stump11289f42009-09-09 15:08:12 +000010388 }
10389 }
10390
Douglas Gregor0bf31402010-10-08 23:50:27 +000010391 // Figure out the underlying type if this a enum declaration. We need to do
10392 // this early, because it's needed to detect if this is an incompatible
10393 // redeclaration.
10394 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10395
10396 if (Kind == TTK_Enum) {
10397 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10398 // No underlying type explicitly specified, or we failed to parse the
10399 // type, default to int.
10400 EnumUnderlying = Context.IntTy.getTypePtr();
10401 else if (UnderlyingType.get()) {
10402 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10403 // integral type; any cv-qualification is ignored.
10404 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010405 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010406 EnumUnderlying = TI;
10407
Richard Smith4b38ded2012-03-14 23:13:10 +000010408 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010409 // Recover by falling back to int.
10410 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010411
Richard Smith4b38ded2012-03-14 23:13:10 +000010412 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010413 UPPC_FixedUnderlyingType))
10414 EnumUnderlying = Context.IntTy.getTypePtr();
10415
Alp Tokerbfa39342014-01-14 12:51:41 +000010416 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010417 // Microsoft enums are always of int type.
10418 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010419 }
10420
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010421 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010422 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010423 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010424
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010425 RedeclarationKind Redecl = ForRedeclaration;
10426 if (TUK == TUK_Friend || TUK == TUK_Reference)
10427 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010428
10429 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010430 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010431 if (Name && SS.isNotEmpty()) {
10432 // We have a nested-name tag ('struct foo::bar').
10433
10434 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010435 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010436 Name = 0;
10437 goto CreateNewDecl;
10438 }
10439
John McCall7f41d982009-09-11 04:59:25 +000010440 // If this is a friend or a reference to a class in a dependent
10441 // context, don't try to make a decl for it.
10442 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10443 DC = computeDeclContext(SS, false);
10444 if (!DC) {
10445 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010446 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010447 }
John McCall0b66eb32010-05-01 00:40:08 +000010448 } else {
10449 DC = computeDeclContext(SS, true);
10450 if (!DC) {
10451 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10452 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010453 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010454 }
John McCall7f41d982009-09-11 04:59:25 +000010455 }
10456
John McCall0b66eb32010-05-01 00:40:08 +000010457 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010458 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010459
Douglas Gregor8761da52009-02-03 00:34:39 +000010460 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010461 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010462 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010463
John McCall1f82f242009-11-18 22:49:29 +000010464 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010465 return 0;
John McCall6538c932009-10-10 05:48:19 +000010466
John McCall1f82f242009-11-18 22:49:29 +000010467 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010468 // Name lookup did not find anything. However, if the
10469 // nested-name-specifier refers to the current instantiation,
10470 // and that current instantiation has any dependent base
10471 // classes, we might find something at instantiation time: treat
10472 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010473 // But this only makes any sense for reference-like lookups.
10474 if (Previous.wasNotFoundInCurrentInstantiation() &&
10475 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010476 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010477 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010478 }
10479
10480 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010481 Diag(NameLoc, diag::err_not_tag_in_scope)
10482 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010483 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010484 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010485 goto CreateNewDecl;
10486 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010487 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010488 // If this is a named struct, check to see if there was a previous forward
10489 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010490 // FIXME: We're looking into outer scopes here, even when we
10491 // shouldn't be. Doing so can result in ambiguities that we
10492 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010493 LookupName(Previous, S);
10494
John McCall3c581bf2013-03-20 01:53:00 +000010495 // When declaring or defining a tag, ignore ambiguities introduced
10496 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010497 if (Previous.isAmbiguous() &&
10498 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010499 LookupResult::Filter F = Previous.makeFilter();
10500 while (F.hasNext()) {
10501 NamedDecl *ND = F.next();
10502 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10503 F.erase();
10504 }
10505 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010506 }
John McCall3c581bf2013-03-20 01:53:00 +000010507
10508 // C++11 [namespace.memdef]p3:
10509 // If the name in a friend declaration is neither qualified nor
10510 // a template-id and the declaration is a function or an
10511 // elaborated-type-specifier, the lookup to determine whether
10512 // the entity has been previously declared shall not consider
10513 // any scopes outside the innermost enclosing namespace.
10514 //
10515 // Does it matter that this should be by scope instead of by
10516 // semantic context?
10517 if (!Previous.empty() && TUK == TUK_Friend) {
10518 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10519 LookupResult::Filter F = Previous.makeFilter();
10520 while (F.hasNext()) {
10521 NamedDecl *ND = F.next();
10522 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010523 if (DC->isFileContext() &&
10524 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010525 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010526 FriendSawTagOutsideEnclosingNamespace = true;
10527 }
John McCall3c581bf2013-03-20 01:53:00 +000010528 }
10529 F.done();
10530 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010531
John McCall1f82f242009-11-18 22:49:29 +000010532 // Note: there used to be some attempt at recovery here.
10533 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010534 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010535
David Blaikiebbafb8a2012-03-11 07:00:24 +000010536 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010537 // FIXME: This makes sure that we ignore the contexts associated
10538 // with C structs, unions, and enums when looking for a matching
10539 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010540 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010541 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10542 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010543 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010544 } else if (S->isFunctionPrototypeScope()) {
10545 // If this is an enum declaration in function prototype scope, set its
10546 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010547 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010548 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010549 }
10550
John McCall1f82f242009-11-18 22:49:29 +000010551 if (Previous.isSingleResult() &&
10552 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010553 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010554 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010555 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010556 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010557 }
10558
David Blaikiebbafb8a2012-03-11 07:00:24 +000010559 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010560 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010561 // This is a declaration of or a reference to "std::bad_alloc".
10562 isStdBadAlloc = true;
10563
John McCall1f82f242009-11-18 22:49:29 +000010564 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010565 // std::bad_alloc has been implicitly declared (but made invisible to
10566 // name lookup). Fill in this implicit declaration as the previous
10567 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010568 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010569 }
10570 }
John McCall1f82f242009-11-18 22:49:29 +000010571
John McCalle9eaf8e2010-03-25 21:28:06 +000010572 // If we didn't find a previous declaration, and this is a reference
10573 // (or friend reference), move to the correct scope. In C++, we
10574 // also need to do a redeclaration lookup there, just in case
10575 // there's a shadow friend decl.
10576 if (Name && Previous.empty() &&
10577 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10578 if (Invalid) goto CreateNewDecl;
10579 assert(SS.isEmpty());
10580
10581 if (TUK == TUK_Reference) {
10582 // C++ [basic.scope.pdecl]p5:
10583 // -- for an elaborated-type-specifier of the form
10584 //
10585 // class-key identifier
10586 //
10587 // if the elaborated-type-specifier is used in the
10588 // decl-specifier-seq or parameter-declaration-clause of a
10589 // function defined in namespace scope, the identifier is
10590 // declared as a class-name in the namespace that contains
10591 // the declaration; otherwise, except as a friend
10592 // declaration, the identifier is declared in the smallest
10593 // non-class, non-function-prototype scope that contains the
10594 // declaration.
10595 //
10596 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10597 // C structs and unions.
10598 //
10599 // It is an error in C++ to declare (rather than define) an enum
10600 // type, including via an elaborated type specifier. We'll
10601 // diagnose that later; for now, declare the enum in the same
10602 // scope as we would have picked for any other tag type.
10603 //
10604 // GNU C also supports this behavior as part of its incomplete
10605 // enum types extension, while GNU C++ does not.
10606 //
10607 // Find the context where we'll be declaring the tag.
10608 // FIXME: We would like to maintain the current DeclContext as the
10609 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010610 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010611 SearchDC = SearchDC->getParent();
10612
10613 // Find the scope where we'll be declaring the tag.
10614 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010615 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010616 S->isFunctionPrototypeScope()) ||
10617 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010618 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010619 S = S->getParent();
10620 } else {
10621 assert(TUK == TUK_Friend);
10622 // C++ [namespace.memdef]p3:
10623 // If a friend declaration in a non-local class first declares a
10624 // class or function, the friend class or function is a member of
10625 // the innermost enclosing namespace.
10626 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010627 }
10628
John McCalle87beb22010-04-23 18:46:30 +000010629 // In C++, we need to do a redeclaration lookup to properly
10630 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010631 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010632 Previous.setRedeclarationKind(ForRedeclaration);
10633 LookupQualifiedName(Previous, SearchDC);
10634 }
10635 }
10636
John McCall1f82f242009-11-18 22:49:29 +000010637 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010638 NamedDecl *PrevDecl = Previous.getFoundDecl();
10639 NamedDecl *DirectPrevDecl =
10640 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010641
10642 // It's okay to have a tag decl in the same scope as a typedef
10643 // which hides a tag decl in the same scope. Finding this
10644 // insanity with a redeclaration lookup can only actually happen
10645 // in C++.
10646 //
10647 // This is also okay for elaborated-type-specifiers, which is
10648 // technically forbidden by the current standard but which is
10649 // okay according to the likely resolution of an open issue;
10650 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010651 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010652 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010653 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10654 TagDecl *Tag = TT->getDecl();
10655 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010656 Tag->getDeclContext()->getRedeclContext()
10657 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010658 PrevDecl = Tag;
10659 Previous.clear();
10660 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010661 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010662 }
10663 }
10664 }
10665 }
10666
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010667 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010668 // If this is a use of a previous tag, or if the tag is already declared
10669 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010670 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010671 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010672 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010673 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010674 // Make sure that this wasn't declared as an enum and now used as a
10675 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010676 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10677 TUK == TUK_Definition, KWLoc,
10678 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010679 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010680 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10681 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010682 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010683 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010684 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010685 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10686 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010687 else
10688 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010689 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010690
Mike Stump11289f42009-09-09 15:08:12 +000010691 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010692 Kind = PrevTagDecl->getTagKind();
10693 else {
10694 // Recover by making this an anonymous redefinition.
10695 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010696 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010697 Invalid = true;
10698 }
10699 }
10700
Douglas Gregor0bf31402010-10-08 23:50:27 +000010701 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10702 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10703
Richard Smith0f8ee222012-01-10 01:33:14 +000010704 // If this is an elaborated-type-specifier for a scoped enumeration,
10705 // the 'class' keyword is not necessary and not permitted.
10706 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10707 if (ScopedEnum)
10708 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10709 << PrevEnum->isScoped()
10710 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10711 return PrevTagDecl;
10712 }
10713
Richard Smith4b38ded2012-03-14 23:13:10 +000010714 QualType EnumUnderlyingTy;
10715 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010716 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010717 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10718 EnumUnderlyingTy = QualType(T, 0);
10719
Douglas Gregor0bf31402010-10-08 23:50:27 +000010720 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010721 // returning the previous declaration, unless this is a definition,
10722 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010723 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10724 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010725 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010726 }
10727
David Majnemer55890bf2013-06-11 03:51:23 +000010728 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010729 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010730 // except that a nested class or member class template can be declared
10731 // and then later defined.
10732 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10733 S->isDeclScope(PrevDecl)) {
10734 Diag(NameLoc, diag::ext_member_redeclared);
10735 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10736 }
10737
Douglas Gregor170512f2009-04-01 23:51:29 +000010738 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010739 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010740
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010741 // FIXME: In the future, return a variant or some other clue
10742 // for the consumer of this Decl to know it doesn't own it.
10743 // For our current ASTs this shouldn't be a problem, but will
10744 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010745 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010746 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010747 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010748
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010749 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010750 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010751 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010752 // If we're defining a specialization and the previous definition
10753 // is from an implicit instantiation, don't emit an error
10754 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010755 bool IsExplicitSpecializationAfterInstantiation = false;
10756 if (isExplicitSpecialization) {
10757 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10758 IsExplicitSpecializationAfterInstantiation =
10759 RD->getTemplateSpecializationKind() !=
10760 TSK_ExplicitSpecialization;
10761 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10762 IsExplicitSpecializationAfterInstantiation =
10763 ED->getTemplateSpecializationKind() !=
10764 TSK_ExplicitSpecialization;
10765 }
10766
10767 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010768 // A redeclaration in function prototype scope in C isn't
10769 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010770 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010771 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10772 else
10773 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010774 Diag(Def->getLocation(), diag::note_previous_definition);
10775 // If this is a redefinition, recover by making this
10776 // struct be anonymous, which will make any later
10777 // references get the previous definition.
10778 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010779 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010780 Invalid = true;
10781 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010782 } else {
10783 // If the type is currently being defined, complain
10784 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010785 const TagType *Tag
10786 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010787 if (Tag->isBeingDefined()) {
10788 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010789 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010790 diag::note_previous_definition);
10791 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010792 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010793 Invalid = true;
10794 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010795 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010796
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010797 // Okay, this is definition of a previously declared or referenced
10798 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010799 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010800 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010801 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010802 // have a definition. Just create a new decl.
10803
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010804 } else {
10805 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010806 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010807 // new decl/type. We set PrevDecl to NULL so that the entities
10808 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010809 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010810 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010811 // If we get here, we're going to create a new Decl. If PrevDecl
10812 // is non-NULL, it's a definition of the tag declared by
10813 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010814
10815
10816 // Otherwise, PrevDecl is not a tag, but was found with tag
10817 // lookup. This is only actually possible in C++, where a few
10818 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010819 } else {
John McCalle87beb22010-04-23 18:46:30 +000010820 // Use a better diagnostic if an elaborated-type-specifier
10821 // found the wrong kind of type on the first
10822 // (non-redeclaration) lookup.
10823 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10824 !Previous.isForRedeclaration()) {
10825 unsigned Kind = 0;
10826 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010827 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10828 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010829 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10830 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10831 Invalid = true;
10832
10833 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010834 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10835 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010836 // do nothing
10837
10838 // Diagnose implicit declarations introduced by elaborated types.
10839 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10840 unsigned Kind = 0;
10841 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010842 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10843 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010844 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10845 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10846 Invalid = true;
10847
10848 // Otherwise it's a declaration. Call out a particularly common
10849 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010850 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10851 unsigned Kind = 0;
10852 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010853 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010854 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010855 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10856 Invalid = true;
10857
10858 // Otherwise, diagnose.
10859 } else {
10860 // The tag name clashes with something else in the target scope,
10861 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010862 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010863 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010864 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010865 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010866 }
John McCalle87beb22010-04-23 18:46:30 +000010867
10868 // The existing declaration isn't relevant to us; we're in a
10869 // new scope, so clear out the previous declaration.
10870 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010871 }
Chris Lattner18b19622007-01-22 07:39:13 +000010872 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010873
Chris Lattner438e5012008-12-17 07:13:27 +000010874CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010875
John McCall1f82f242009-11-18 22:49:29 +000010876 TagDecl *PrevDecl = 0;
10877 if (Previous.isSingleResult())
10878 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10879
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010880 // If there is an identifier, use the location of the identifier as the
10881 // location of the decl, otherwise use the location of the struct/union
10882 // keyword.
10883 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010884
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010885 // Otherwise, create a new declaration. If there is a previous
10886 // declaration of the same entity, the two will be linked via
10887 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010888 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010889
Douglas Gregor0bf31402010-10-08 23:50:27 +000010890 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010891 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010892 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10893 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010894 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010895 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010896 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010897 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010898 if (TUK != TUK_Definition && !Invalid) {
10899 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010900 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10901 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010902 // C++0x: 7.2p2: opaque-enum-declaration.
10903 // Conflicts are diagnosed above. Do nothing.
10904 }
10905 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010906 Diag(Loc, diag::ext_forward_ref_enum_def)
10907 << New;
10908 Diag(Def->getLocation(), diag::note_previous_definition);
10909 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010910 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000010911 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000010912 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010913 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010914 DiagID = diag::err_forward_ref_enum;
10915 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010916
10917 // If this is a forward-declared reference to an enumeration, make a
10918 // note of it; we won't actually be introducing the declaration into
10919 // the declaration context.
10920 if (TUK == TUK_Reference)
10921 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010922 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010923 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010924
10925 if (EnumUnderlying) {
10926 EnumDecl *ED = cast<EnumDecl>(New);
10927 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10928 ED->setIntegerTypeSourceInfo(TI);
10929 else
10930 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10931 ED->setPromotionType(ED->getIntegerType());
10932 }
10933
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010934 } else {
10935 // struct/union/class
10936
Chris Lattner776fac82007-06-09 00:53:06 +000010937 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10938 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010939 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010940 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010941 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010942 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010943
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010944 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010945 StdBadAlloc = cast<CXXRecordDecl>(New);
10946 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010947 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010948 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000010949 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010950
Richard Smith649c7b062014-01-08 00:56:48 +000010951 // C++11 [dcl.type]p3:
10952 // A type-specifier-seq shall not define a class or enumeration [...].
10953 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
10954 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
10955 << Context.getTagDeclType(New);
10956 Invalid = true;
10957 }
10958
John McCall3e11ebe2010-03-15 10:12:16 +000010959 // Maybe add qualifier info.
10960 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010961 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010962 // If this is either a declaration or a definition, check the
10963 // nested-name-specifier against the current context. We don't do this
10964 // for explicit specializations, because they have similar checking
10965 // (with more specific diagnostics) in the call to
10966 // CheckMemberSpecialization, below.
10967 if (!isExplicitSpecialization &&
10968 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10969 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10970 Invalid = true;
10971
Douglas Gregor14454802011-02-25 02:25:35 +000010972 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000010973 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000010974 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000010975 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010976 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000010977 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000010978 }
10979 else
10980 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000010981 }
10982
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000010983 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10984 // Add alignment attributes if necessary; these attributes are checked when
10985 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010986 //
10987 // It is important for implementing the correct semantics that this
10988 // happen here (in act on tag decl). The #pragma pack stack is
10989 // maintained as a result of parser callbacks which can occur at
10990 // many points during the parsing of a struct declaration (because
10991 // the #pragma tokens are effectively skipped over during the
10992 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000010993 if (TUK == TUK_Definition) {
10994 AddAlignmentAttributesForRecord(RD);
10995 AddMsStructLayoutForRecord(RD);
10996 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010997 }
10998
Douglas Gregor21823bf2011-12-20 18:11:52 +000010999 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011000 if (isExplicitSpecialization)
11001 Diag(New->getLocation(), diag::err_module_private_specialization)
11002 << 2
11003 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011004 // __module_private__ does not apply to local classes. However, we only
11005 // diagnose this as an error when the declaration specifiers are
11006 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011007 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011008 New->setModulePrivate();
11009 }
11010
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011011 // If this is a specialization of a member class (of a class template),
11012 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011013 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011014 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011015
Douglas Gregordee1be82009-01-17 00:42:38 +000011016 if (Invalid)
11017 New->setInvalidDecl();
11018
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011019 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011020 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011021
Douglas Gregordee1be82009-01-17 00:42:38 +000011022 // If we're declaring or defining a tag in function prototype scope
11023 // in C, note that this type can only be used within the function.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011024 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
Douglas Gregor658b9552009-01-09 22:42:13 +000011025 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11026
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011027 // Set the lexical context. If the tag has a C++ scope specifier, the
11028 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011029 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011030
John McCallaa74a0c2009-08-28 07:59:38 +000011031 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011032 // In Microsoft mode, a friend declaration also acts as a forward
11033 // declaration so we always pass true to setObjectOfFriendDecl to make
11034 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011035 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011036 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11037 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011038
Anders Carlsson5558ca12009-03-26 01:19:02 +000011039 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011040 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011041 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011042
John McCall9bb74a52009-07-31 02:45:11 +000011043 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011044 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011045
Chris Lattner18b19622007-01-22 07:39:13 +000011046 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011047 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011048 // We might be replacing an existing declaration in the lookup tables;
11049 // if so, borrow its access specifier.
11050 if (PrevDecl)
11051 New->setAccess(PrevDecl->getAccess());
11052
Sebastian Redl50c68252010-08-31 00:36:30 +000011053 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011054 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011055 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011056 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11057 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011058 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011059 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011060 PushOnScopeChains(New, S, !IsForwardReference);
11061 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011062 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011063
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011064 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011065 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011066 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011067
Douglas Gregor27821ce2009-07-07 16:35:42 +000011068 // If this is the C FILE type, notify the AST context.
11069 if (IdentifierInfo *II = New->getIdentifier())
11070 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011071 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011072 II->isStr("FILE"))
11073 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011074
James Molloy6f8780b2012-02-29 10:24:19 +000011075 // If we were in function prototype scope (and not in C++ mode), add this
11076 // tag to the list of decls to inject into the function definition scope.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011077 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
James Molloy6f8780b2012-02-29 10:24:19 +000011078 InFunctionDeclarator && Name)
11079 DeclsInPrototypeScope.push_back(New);
11080
Rafael Espindolac67f2232012-05-10 02:50:16 +000011081 if (PrevDecl)
11082 mergeDeclAttributes(New, PrevDecl);
11083
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011084 // If there's a #pragma GCC visibility in scope, set the visibility of this
11085 // record.
11086 AddPushedVisibilityAttribute(New);
11087
Douglas Gregord6ab8742009-05-28 23:31:59 +000011088 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011089 // In C++, don't return an invalid declaration. We can't recover well from
11090 // the cases where we make the type anonymous.
11091 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011092}
Chris Lattner1300fb92007-01-23 23:42:53 +000011093
John McCall48871652010-08-21 09:40:31 +000011094void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011095 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011096 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011097
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011098 // Enter the tag context.
11099 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011100
11101 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011102
11103 // If there's a #pragma GCC visibility in scope, set the visibility of this
11104 // record.
11105 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011106}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011107
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011108Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011109 assert(isa<ObjCContainerDecl>(IDecl) &&
11110 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11111 DeclContext *OCD = cast<DeclContext>(IDecl);
11112 assert(getContainingDC(OCD) == CurContext &&
11113 "The next DeclContext should be lexically contained in the current one.");
11114 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011115 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011116}
11117
John McCall48871652010-08-21 09:40:31 +000011118void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011119 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011120 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011121 SourceLocation LBraceLoc) {
11122 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011123 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011124
John McCall1c7e6ec2009-12-20 07:58:13 +000011125 FieldCollector->StartClass();
11126
11127 if (!Record->getIdentifier())
11128 return;
11129
Anders Carlsson30f29442011-03-25 14:31:08 +000011130 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011131 Record->addAttr(new (Context)
11132 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11133
John McCall1c7e6ec2009-12-20 07:58:13 +000011134 // C++ [class]p2:
11135 // [...] The class-name is also inserted into the scope of the
11136 // class itself; this is known as the injected-class-name. For
11137 // purposes of access checking, the injected-class-name is treated
11138 // as if it were a public member name.
11139 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011140 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11141 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011142 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011143 /*PrevDecl=*/0,
11144 /*DelayTypeCreation=*/true);
11145 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011146 InjectedClassName->setImplicit();
11147 InjectedClassName->setAccess(AS_public);
11148 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11149 InjectedClassName->setDescribedClassTemplate(Template);
11150 PushOnScopeChains(InjectedClassName, S);
11151 assert(InjectedClassName->isInjectedClassName() &&
11152 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011153}
11154
John McCall48871652010-08-21 09:40:31 +000011155void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011156 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011157 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011158 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011159 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011160
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011161 // Make sure we "complete" the definition even it is invalid.
11162 if (Tag->isBeingDefined()) {
11163 assert(Tag->isInvalidDecl() && "We should already have completed it");
11164 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11165 RD->completeDefinition();
11166 }
11167
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011168 if (isa<CXXRecordDecl>(Tag))
11169 FieldCollector->FinishClass();
11170
11171 // Exit this scope of this tag's definition.
11172 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011173
11174 if (getCurLexicalContext()->isObjCContainer() &&
11175 Tag->getDeclContext()->isFileContext())
11176 Tag->setTopLevelDeclInObjCContainer();
11177
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011178 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011179 if (!Tag->isInvalidDecl())
11180 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011181}
Chris Lattner535b8302008-06-21 19:39:06 +000011182
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011183void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011184 // Exit this scope of this interface definition.
11185 PopDeclContext();
11186}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011187
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011188void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011189 assert(DC == CurContext && "Mismatch of container contexts");
11190 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011191 ActOnObjCContainerFinishDefinition();
11192}
11193
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011194void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11195 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011196 OriginalLexicalContext = 0;
11197}
11198
John McCall48871652010-08-21 09:40:31 +000011199void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011200 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011201 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011202 Tag->setInvalidDecl();
11203
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011204 // Make sure we "complete" the definition even it is invalid.
11205 if (Tag->isBeingDefined()) {
11206 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11207 RD->completeDefinition();
11208 }
11209
John McCall71ba5f22010-03-17 19:25:57 +000011210 // We're undoing ActOnTagStartDefinition here, not
11211 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11212 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011213
11214 PopDeclContext();
11215}
11216
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011217// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011218ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11219 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011220 QualType FieldTy, bool IsMsStruct,
11221 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011222 // Default to true; that shouldn't confuse checks for emptiness
11223 if (ZeroWidth)
11224 *ZeroWidth = true;
11225
Chris Lattner73bf7b42009-03-05 22:45:59 +000011226 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011227 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011228 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011229 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011230 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011231 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011232 if (FieldName)
11233 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11234 << FieldName << FieldTy << BitWidth->getSourceRange();
11235 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11236 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011237 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11238 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011239 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011240
11241 // If the bit-width is type- or value-dependent, don't try to check
11242 // it now.
11243 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011244 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011245
Anders Carlsson5df391e2008-12-06 20:33:04 +000011246 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011247 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11248 if (ICE.isInvalid())
11249 return ICE;
11250 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011251
Eli Friedmanc96d4962009-08-15 21:55:26 +000011252 if (Value != 0 && ZeroWidth)
11253 *ZeroWidth = false;
11254
Chris Lattner81ed6802008-12-12 04:56:04 +000011255 // Zero-width bitfield is ok for anonymous field.
11256 if (Value == 0 && FieldName)
11257 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011258
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011259 if (Value.isSigned() && Value.isNegative()) {
11260 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011261 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011262 << FieldName << Value.toString(10);
11263 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11264 << Value.toString(10);
11265 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011266
Douglas Gregor1efa4372009-03-11 18:59:21 +000011267 if (!FieldTy->isDependentType()) {
11268 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011269 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011270 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11271 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011272 if (FieldName)
11273 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11274 << FieldName << (unsigned)Value.getZExtValue()
11275 << (unsigned)TypeSize;
11276
11277 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11278 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11279 }
11280
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011281 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011282 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11283 << FieldName << (unsigned)Value.getZExtValue()
11284 << (unsigned)TypeSize;
11285 else
11286 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11287 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011288 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011289 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011290
Richard Smithf4c51d92012-02-04 09:53:13 +000011291 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011292}
11293
Richard Smith938f40b2011-06-11 17:19:42 +000011294/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011295/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011296Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011297 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011298 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011299 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011300 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011301 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011302}
11303
11304/// HandleField - Analyze a field of a C struct or a C++ data member.
11305///
11306FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11307 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011308 Declarator &D, Expr *BitWidth,
11309 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011310 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011311 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011312 SourceLocation Loc = DeclStart;
11313 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011314
John McCall8cb7bdf2010-06-04 23:28:52 +000011315 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11316 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011317 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011318 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011319
Douglas Gregora02a72a2010-12-15 23:18:36 +000011320 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11321 UPPC_DataMemberType)) {
11322 D.setInvalidType();
11323 T = Context.IntTy;
11324 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11325 }
11326 }
11327
Matt Arsenault376f7202013-02-26 21:16:00 +000011328 // TR 18037 does not allow fields to be declared with address spaces.
11329 if (T.getQualifiers().hasAddressSpace()) {
11330 Diag(Loc, diag::err_field_with_address_space);
11331 D.setInvalidType();
11332 }
11333
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011334 // OpenCL 1.2 spec, s6.9 r:
11335 // The event type cannot be used to declare a structure or union field.
11336 if (LangOpts.OpenCL && T->isEventT()) {
11337 Diag(Loc, diag::err_event_t_struct_field);
11338 D.setInvalidType();
11339 }
11340
Richard Smithb1402ae2013-03-18 22:52:47 +000011341 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011342
Richard Smithb4a9e862013-04-12 22:46:28 +000011343 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11344 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11345 diag::err_invalid_thread)
11346 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011347
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011348 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011349 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011350 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11351 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011352 switch (Previous.getResultKind()) {
11353 case LookupResult::Found:
11354 case LookupResult::FoundUnresolvedValue:
11355 PrevDecl = Previous.getAsSingle<NamedDecl>();
11356 break;
11357
11358 case LookupResult::FoundOverloaded:
11359 PrevDecl = Previous.getRepresentativeDecl();
11360 break;
11361
11362 case LookupResult::NotFound:
11363 case LookupResult::NotFoundInCurrentInstantiation:
11364 case LookupResult::Ambiguous:
11365 break;
11366 }
11367 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011368
11369 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11370 // Maybe we will complain about the shadowed template parameter.
11371 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11372 // Just pretend that we didn't see the previous declaration.
11373 PrevDecl = 0;
11374 }
11375
Douglas Gregor1efa4372009-03-11 18:59:21 +000011376 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11377 PrevDecl = 0;
11378
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011379 bool Mutable
11380 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011381 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011382 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011383 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011384 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011385
11386 if (NewFD->isInvalidDecl())
11387 Record->setInvalidDecl();
11388
Douglas Gregor3baa6702011-09-12 16:11:24 +000011389 if (D.getDeclSpec().isModulePrivateSpecified())
11390 NewFD->setModulePrivate();
11391
Douglas Gregor1efa4372009-03-11 18:59:21 +000011392 if (NewFD->isInvalidDecl() && PrevDecl) {
11393 // Don't introduce NewFD into scope; there's already something
11394 // with the same name in the same scope.
11395 } else if (II) {
11396 PushOnScopeChains(NewFD, S);
11397 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011398 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011399
11400 return NewFD;
11401}
11402
11403/// \brief Build a new FieldDecl and check its well-formedness.
11404///
11405/// This routine builds a new FieldDecl given the fields name, type,
11406/// record, etc. \p PrevDecl should refer to any previous declaration
11407/// with the same name and in the same scope as the field to be
11408/// created.
11409///
11410/// \returns a new FieldDecl.
11411///
Mike Stump11289f42009-09-09 15:08:12 +000011412/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011413FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011414 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011415 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011416 bool Mutable, Expr *BitWidth,
11417 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011418 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011419 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011420 Declarator *D) {
11421 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011422 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011423 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011424
Douglas Gregor1efa4372009-03-11 18:59:21 +000011425 // If we receive a broken type, recover by assuming 'int' and
11426 // marking this declaration as invalid.
11427 if (T.isNull()) {
11428 InvalidDecl = true;
11429 T = Context.IntTy;
11430 }
11431
Eli Friedmand0e8de22009-12-07 00:22:08 +000011432 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011433 if (!EltTy->isDependentType()) {
11434 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11435 // Fields of incomplete type force their record to be invalid.
11436 Record->setInvalidDecl();
11437 InvalidDecl = true;
11438 } else {
11439 NamedDecl *Def;
11440 EltTy->isIncompleteType(&Def);
11441 if (Def && Def->isInvalidDecl()) {
11442 Record->setInvalidDecl();
11443 InvalidDecl = true;
11444 }
11445 }
John McCall2677e102010-08-16 23:42:35 +000011446 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011447
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011448 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11449 if (BitWidth && getLangOpts().OpenCL) {
11450 Diag(Loc, diag::err_opencl_bitfields);
11451 InvalidDecl = true;
11452 }
11453
Steve Naroff8eeeb132007-05-08 21:09:37 +000011454 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11455 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011456 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011457 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011458 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011459
11460 TypeSourceInfo *FixedTInfo =
11461 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11462 SizeIsNegative,
11463 Oversized);
11464 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011465 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011466 TInfo = FixedTInfo;
11467 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011468 } else {
11469 if (SizeIsNegative)
11470 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011471 else if (Oversized.getBoolValue())
11472 Diag(Loc, diag::err_array_too_large)
11473 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011474 else
11475 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011476 InvalidDecl = true;
11477 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011478 }
Mike Stump11289f42009-09-09 15:08:12 +000011479
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011480 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011481 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11482 diag::err_abstract_type_in_decl,
11483 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011484 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011485
Eli Friedmanc96d4962009-08-15 21:55:26 +000011486 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011487 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011488 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011489 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11490 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011491 if (!BitWidth) {
11492 InvalidDecl = true;
11493 BitWidth = 0;
11494 ZeroWidth = false;
11495 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011496 }
Mike Stump11289f42009-09-09 15:08:12 +000011497
John McCallb1cd7da2010-06-04 08:34:12 +000011498 // Check that 'mutable' is consistent with the type of the declaration.
11499 if (!InvalidDecl && Mutable) {
11500 unsigned DiagID = 0;
11501 if (T->isReferenceType())
11502 DiagID = diag::err_mutable_reference;
11503 else if (T.isConstQualified())
11504 DiagID = diag::err_mutable_const;
11505
11506 if (DiagID) {
11507 SourceLocation ErrLoc = Loc;
11508 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11509 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11510 Diag(ErrLoc, DiagID);
11511 Mutable = false;
11512 InvalidDecl = true;
11513 }
11514 }
11515
Richard Smithab44d5b2013-12-10 08:25:00 +000011516 // C++11 [class.union]p8 (DR1460):
11517 // At most one variant member of a union may have a
11518 // brace-or-equal-initializer.
11519 if (InitStyle != ICIS_NoInit)
11520 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11521
Abramo Bagnaradff19302011-03-08 08:55:46 +000011522 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011523 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011524 if (InvalidDecl)
11525 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011526
Douglas Gregor1efa4372009-03-11 18:59:21 +000011527 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11528 Diag(Loc, diag::err_duplicate_member) << II;
11529 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11530 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011531 }
11532
David Blaikiebbafb8a2012-03-11 07:00:24 +000011533 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011534 if (Record->isUnion()) {
11535 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11536 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11537 if (RDecl->getDefinition()) {
11538 // C++ [class.union]p1: An object of a class with a non-trivial
11539 // constructor, a non-trivial copy constructor, a non-trivial
11540 // destructor, or a non-trivial copy assignment operator
11541 // cannot be a member of a union, nor can an array of such
11542 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011543 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011544 NewFD->setInvalidDecl();
11545 }
11546 }
11547
11548 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011549 // the program is ill-formed, except when compiling with MSVC extensions
11550 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011551 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011552 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11553 diag::ext_union_member_of_reference_type :
11554 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011555 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011556 if (!getLangOpts().MicrosoftExt)
11557 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011558 }
11559 }
11560 }
11561
Douglas Gregor1efa4372009-03-11 18:59:21 +000011562 // FIXME: We need to pass in the attributes given an AST
11563 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011564 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011565 // FIXME: The current scope is almost... but not entirely... correct here.
11566 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011567
Richard Smith848e1f12013-02-01 08:12:08 +000011568 if (NewFD->hasAttrs())
11569 CheckAlignasUnderalignment(NewFD);
11570 }
11571
John McCall31168b02011-06-15 23:02:42 +000011572 // In auto-retain/release, infer strong retension for fields of
11573 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011574 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011575 NewFD->setInvalidDecl();
11576
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011577 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011578 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011579
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011580 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011581 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011582}
11583
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011584bool Sema::CheckNontrivialField(FieldDecl *FD) {
11585 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011586 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011587
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011588 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11589 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011590
11591 QualType EltTy = Context.getBaseElementType(FD->getType());
11592 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011593 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011594 if (RDecl->getDefinition()) {
11595 // We check for copy constructors before constructors
11596 // because otherwise we'll never get complaints about
11597 // copy constructors.
11598
11599 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011600 // We're required to check for any non-trivial constructors. Since the
11601 // implicit default constructor is suppressed if there are any
11602 // user-declared constructors, we just need to check that there is a
11603 // trivial default constructor and a trivial copy constructor. (We don't
11604 // worry about move constructors here, since this is a C++98 check.)
11605 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011606 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011607 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011608 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011609 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011610 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011611 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011612 member = CXXDestructor;
11613
11614 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011615 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011616 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011617 // Objective-C++ ARC: it is an error to have a non-trivial field of
11618 // a union. However, system headers in Objective-C programs
11619 // occasionally have Objective-C lifetime objects within unions,
11620 // and rather than cause the program to fail, we make those
11621 // members unavailable.
11622 SourceLocation Loc = FD->getLocation();
11623 if (getSourceManager().isInSystemHeader(Loc)) {
11624 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011625 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11626 "this system field has retaining ownership",
11627 Loc));
John McCall31168b02011-06-15 23:02:42 +000011628 return false;
11629 }
11630 }
Richard Smithf720df02011-10-19 20:41:51 +000011631
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011632 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011633 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11634 diag::err_illegal_union_or_anon_struct_member)
11635 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011636 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011637 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011638 }
11639 }
11640 }
Richard Smith92f241f2012-12-08 02:53:02 +000011641
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011642 return false;
11643}
11644
Mike Stump11289f42009-09-09 15:08:12 +000011645/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011646/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011647static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011648TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011649 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011650 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011651 case tok::objc_private: return ObjCIvarDecl::Private;
11652 case tok::objc_public: return ObjCIvarDecl::Public;
11653 case tok::objc_protected: return ObjCIvarDecl::Protected;
11654 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011655 }
11656}
11657
Mike Stump11289f42009-09-09 15:08:12 +000011658/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011659/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011660Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011661 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011662 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011663 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011664
Fariborz Jahaniande615832008-04-10 23:32:45 +000011665 IdentifierInfo *II = D.getIdentifier();
11666 Expr *BitWidth = (Expr*)BitfieldWidth;
11667 SourceLocation Loc = DeclStart;
11668 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011669
Fariborz Jahaniande615832008-04-10 23:32:45 +000011670 // FIXME: Unnamed fields can be handled in various different ways, for
11671 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011672
John McCall8cb7bdf2010-06-04 23:28:52 +000011673 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11674 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011675
Fariborz Jahaniande615832008-04-10 23:32:45 +000011676 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011677 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011678 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011679 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011680 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011681 } else {
11682 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011683
Fariborz Jahaniande615832008-04-10 23:32:45 +000011684 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011685
Fariborz Jahaniande615832008-04-10 23:32:45 +000011686 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011687 if (T->isReferenceType()) {
11688 Diag(Loc, diag::err_ivar_reference_type);
11689 D.setInvalidType();
11690 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011691 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11692 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011693 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011694 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011695 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011696 }
Mike Stump11289f42009-09-09 15:08:12 +000011697
Ted Kremenek73295fa2008-07-23 18:04:17 +000011698 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011699 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011700 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11701 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011702 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011703 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011704 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11705 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011706 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011707 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011708 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011709 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011710 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011711 EnclosingContext = IMPDecl->getClassInterface();
11712 assert(EnclosingContext && "Implementation has no class interface!");
11713 }
11714 else
11715 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011716 } else {
11717 if (ObjCCategoryDecl *CDecl =
11718 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011719 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011720 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011721 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011722 }
11723 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011724 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011725 }
Mike Stump11289f42009-09-09 15:08:12 +000011726
Ted Kremenek73295fa2008-07-23 18:04:17 +000011727 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011728 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11729 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011730 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011731
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011732 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011733 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011734 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011735 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011736 && !isa<TagDecl>(PrevDecl)) {
11737 Diag(Loc, diag::err_duplicate_member) << II;
11738 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11739 NewID->setInvalidDecl();
11740 }
11741 }
11742
Ted Kremenek73295fa2008-07-23 18:04:17 +000011743 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011744 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011745
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011746 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011747 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011748
John McCall31168b02011-06-15 23:02:42 +000011749 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011750 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011751 NewID->setInvalidDecl();
11752
Douglas Gregor3baa6702011-09-12 16:11:24 +000011753 if (D.getDeclSpec().isModulePrivateSpecified())
11754 NewID->setModulePrivate();
11755
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011756 if (II) {
11757 // FIXME: When interfaces are DeclContexts, we'll need to add
11758 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011759 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011760 IdResolver.AddDecl(NewID);
11761 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011762
John McCall5fb5df92012-06-20 06:18:46 +000011763 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011764 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011765 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011766
John McCall48871652010-08-21 09:40:31 +000011767 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011768}
11769
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011770/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011771/// class and class extensions. For every class \@interface and class
11772/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011773/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011774void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011775 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011776 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011777 return;
11778
11779 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11780 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11781
Richard Smithcaf33902011-10-10 18:28:20 +000011782 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011783 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011784 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011785 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011786 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011787 if (!CD->IsClassExtension())
11788 return;
11789 }
11790 // No need to add this to end of @implementation.
11791 else
11792 return;
11793 }
11794 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011795 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11796 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011797
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011798 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011799 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011800 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011801 Context.getTrivialTypeSourceInfo(Context.CharTy,
11802 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011803 ObjCIvarDecl::Private, BW,
11804 true);
11805 AllIvarDecls.push_back(Ivar);
11806}
11807
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011808void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11809 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11810 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011811 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011812
Eric Christopher7457aaf2012-07-19 22:22:51 +000011813 // If this is an Objective-C @implementation or category and we have
11814 // new fields here we should reset the layout of the interface since
11815 // it will now change.
11816 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11817 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11818 switch (DC->getKind()) {
11819 default: break;
11820 case Decl::ObjCCategory:
11821 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11822 break;
11823 case Decl::ObjCImplementation:
11824 Context.
11825 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11826 break;
11827 }
11828 }
11829
Eli Friedmana7679412012-02-07 05:00:47 +000011830 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11831
11832 // Start counting up the number of named members; make sure to include
11833 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011834 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011835 if (Record) {
11836 for (RecordDecl::decl_iterator i = Record->decls_begin(),
11837 e = Record->decls_end(); i != e; i++) {
11838 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11839 if (IFD->getDeclName())
11840 ++NumNamedMembers;
11841 }
11842 }
11843
11844 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011845 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011846
John McCall31168b02011-06-15 23:02:42 +000011847 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011848 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011849 i != end; ++i) {
11850 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011851
Chris Lattner720a0542007-01-25 00:44:24 +000011852 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011853 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011854
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011855 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011856 // Remember all fields written by the user.
11857 RecFields.push_back(FD);
11858 }
Mike Stump11289f42009-09-09 15:08:12 +000011859
Chris Lattner73bf7b42009-03-05 22:45:59 +000011860 // If the field is already invalid for some reason, don't emit more
11861 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011862 if (FD->isInvalidDecl()) {
11863 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011864 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011865 }
Mike Stump11289f42009-09-09 15:08:12 +000011866
Douglas Gregorac1fb652009-03-24 19:52:54 +000011867 // C99 6.7.2.1p2:
11868 // A structure or union shall not contain a member with
11869 // incomplete or function type (hence, a structure shall not
11870 // contain an instance of itself, but may contain a pointer to
11871 // an instance of itself), except that the last member of a
11872 // structure with more than one named member may have incomplete
11873 // array type; such a structure (and any union containing,
11874 // possibly recursively, a member that is such a structure)
11875 // shall not be a member of a structure or an element of an
11876 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011877 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011878 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011879 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011880 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011881 FD->setInvalidDecl();
11882 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011883 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011884 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011885 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011886 ((getLangOpts().MicrosoftExt ||
11887 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011888 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011889 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011890 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011891 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011892 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011893 unsigned DiagID = 0;
11894 if (Record->isUnion())
11895 DiagID = getLangOpts().MicrosoftExt
11896 ? diag::ext_flexible_array_union_ms
11897 : getLangOpts().CPlusPlus
11898 ? diag::ext_flexible_array_union_gnu
11899 : diag::err_flexible_array_union;
11900 else if (Fields.size() == 1)
11901 DiagID = getLangOpts().MicrosoftExt
11902 ? diag::ext_flexible_array_empty_aggregate_ms
11903 : getLangOpts().CPlusPlus
11904 ? diag::ext_flexible_array_empty_aggregate_gnu
11905 : NumNamedMembers < 1
11906 ? diag::err_flexible_array_empty_aggregate
11907 : 0;
11908
11909 if (DiagID)
11910 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11911 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011912 // While the layout of types that contain virtual bases is not specified
11913 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11914 // virtual bases after the derived members. This would make a flexible
11915 // array member declared at the end of an object not adjacent to the end
11916 // of the type.
11917 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11918 if (RD->getNumVBases() != 0)
11919 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11920 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011921 if (!getLangOpts().C99)
11922 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11923 << FD->getDeclName() << Record->getTagKind();
11924
Richard Smith6fa28ff2014-01-11 00:53:35 +000011925 // If the element type has a non-trivial destructor, we would not
11926 // implicitly destroy the elements, so disallow it for now.
11927 //
11928 // FIXME: GCC allows this. We should probably either implicitly delete
11929 // the destructor of the containing class, or just allow this.
11930 QualType BaseElem = Context.getBaseElementType(FD->getType());
11931 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11932 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011933 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011934 FD->setInvalidDecl();
11935 EnclosingDecl->setInvalidDecl();
11936 continue;
11937 }
Chris Lattner720a0542007-01-25 00:44:24 +000011938 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011939 if (Record)
11940 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011941 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011942 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011943 diag::err_field_incomplete)) {
11944 // Incomplete type
11945 FD->setInvalidDecl();
11946 EnclosingDecl->setInvalidDecl();
11947 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011948 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011949 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11950 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011951 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000011952 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011953 } else {
11954 // If this is a struct/class and this is not the last element, reject
11955 // it. Note that GCC supports variable sized arrays in the middle of
11956 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000011957 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011958 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000011959 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000011960 else {
11961 // We support flexible arrays at the end of structs in
11962 // other structs as an extension.
11963 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11964 << FD->getDeclName();
11965 if (Record)
11966 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000011967 }
Chris Lattner720a0542007-01-25 00:44:24 +000011968 }
11969 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000011970 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11971 RequireNonAbstractType(FD->getLocation(), FD->getType(),
11972 diag::err_abstract_type_in_decl,
11973 AbstractIvarType)) {
11974 // Ivars can not have abstract class types
11975 FD->setInvalidDecl();
11976 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000011977 if (Record && FDTTy->getDecl()->hasObjectMember())
11978 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000011979 if (Record && FDTTy->getDecl()->hasVolatileMember())
11980 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000011981 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011982 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000011983 Diag(FD->getLocation(), diag::err_statically_allocated_object)
11984 << FixItHint::CreateInsertion(FD->getLocation(), "*");
11985 QualType T = Context.getObjCObjectPointerType(FD->getType());
11986 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000011987 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11988 (!getLangOpts().CPlusPlus || Record->isUnion())) {
11989 // It's an error in ARC if a field has lifetime.
11990 // We don't want to report this in a system header, though,
11991 // so we just make the field unavailable.
11992 // FIXME: that's really not sufficient; we need to make the type
11993 // itself invalid to, say, initialize or copy.
11994 QualType T = FD->getType();
11995 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11996 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11997 SourceLocation loc = FD->getLocation();
11998 if (getSourceManager().isInSystemHeader(loc)) {
11999 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012000 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12001 "this system field has retaining ownership",
12002 loc));
John McCall31168b02011-06-15 23:02:42 +000012003 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012004 } else {
12005 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012006 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012007 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012008 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012009 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012010 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012011 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012012 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012013 if (FD->getType()->isObjCObjectPointerType() ||
12014 FD->getType().isObjCGCStrong())
12015 Record->setHasObjectMember(true);
12016 else if (Context.getAsArrayType(FD->getType())) {
12017 QualType BaseType = Context.getBaseElementType(FD->getType());
12018 if (BaseType->isRecordType() &&
12019 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012020 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012021 else if (BaseType->isObjCObjectPointerType() ||
12022 BaseType.isObjCGCStrong())
12023 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012024 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012025 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012026 if (Record && FD->getType().isVolatileQualified())
12027 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012028 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012029 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012030 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012031 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012032
Chris Lattner82625602007-01-24 02:26:21 +000012033 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012034 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012035 bool Completed = false;
12036 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12037 if (!CXXRecord->isInvalidDecl()) {
12038 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012039 for (CXXRecordDecl::conversion_iterator
12040 I = CXXRecord->conversion_begin(),
12041 E = CXXRecord->conversion_end(); I != E; ++I)
12042 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012043
12044 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012045 if (CXXRecord->hasUserDeclaredDestructor()) {
12046 // Adjust user-defined destructor exception spec.
12047 if (getLangOpts().CPlusPlus11)
12048 AdjustDestructorExceptionSpec(CXXRecord,
12049 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012050 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012051
Douglas Gregor8fb95122010-09-29 00:15:42 +000012052 // Add any implicitly-declared members to this class.
12053 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12054
12055 // If we have virtual base classes, we may end up finding multiple
12056 // final overriders for a given virtual function. Check for this
12057 // problem now.
12058 if (CXXRecord->getNumVBases()) {
12059 CXXFinalOverriderMap FinalOverriders;
12060 CXXRecord->getFinalOverriders(FinalOverriders);
12061
12062 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12063 MEnd = FinalOverriders.end();
12064 M != MEnd; ++M) {
12065 for (OverridingMethods::iterator SO = M->second.begin(),
12066 SOEnd = M->second.end();
12067 SO != SOEnd; ++SO) {
12068 assert(SO->second.size() > 0 &&
12069 "Virtual function without overridding functions?");
12070 if (SO->second.size() == 1)
12071 continue;
12072
12073 // C++ [class.virtual]p2:
12074 // In a derived class, if a virtual member function of a base
12075 // class subobject has more than one final overrider the
12076 // program is ill-formed.
12077 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012078 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012079 Diag(M->first->getLocation(),
12080 diag::note_overridden_virtual_function);
12081 for (OverridingMethods::overriding_iterator
12082 OM = SO->second.begin(),
12083 OMEnd = SO->second.end();
12084 OM != OMEnd; ++OM)
12085 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012086 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012087
12088 Record->setInvalidDecl();
12089 }
12090 }
12091 CXXRecord->completeDefinition(&FinalOverriders);
12092 Completed = true;
12093 }
12094 }
12095 }
12096 }
12097
12098 if (!Completed)
12099 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012100
Richard Smith848e1f12013-02-01 08:12:08 +000012101 if (Record->hasAttrs())
12102 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012103
Serge Pavlov3cb80222013-11-14 02:13:03 +000012104 // Check if the structure/union declaration is a type that can have zero
12105 // size in C. For C this is a language extension, for C++ it may cause
12106 // compatibility problems.
12107 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012108 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012109 CheckForZeroSize = true;
12110 } else {
12111 // For C++ filter out types that cannot be referenced in C code.
12112 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12113 CheckForZeroSize =
12114 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12115 !CXXRecord->isDependentType() &&
12116 CXXRecord->isCLike();
12117 }
12118 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012119 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012120 bool IsEmpty = true;
12121 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012122 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012123 E = Record->field_end();
12124 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12125 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012126 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012127 if (I->getBitWidthValue(Context) > 0)
12128 ZeroSize = false;
12129 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012130 ++NonBitFields;
12131 QualType FieldType = I->getType();
12132 if (FieldType->isIncompleteType() ||
12133 !Context.getTypeSizeInChars(FieldType).isZero())
12134 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012135 }
12136 }
12137
Serge Pavlov3cb80222013-11-14 02:13:03 +000012138 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12139 // allowed in C++, but warn if its declaration is inside
12140 // extern "C" block.
12141 if (ZeroSize) {
12142 Diag(RecLoc, getLangOpts().CPlusPlus ?
12143 diag::warn_zero_size_struct_union_in_extern_c :
12144 diag::warn_zero_size_struct_union_compat)
12145 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12146 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012147
Serge Pavlov3cb80222013-11-14 02:13:03 +000012148 // Structs without named members are extension in C (C99 6.7.2.1p7),
12149 // but are accepted by GCC.
12150 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12151 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12152 diag::ext_no_named_members_in_struct_union)
12153 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012154 }
12155 }
Chris Lattner622c1932008-02-06 00:51:33 +000012156 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012157 ObjCIvarDecl **ClsFields =
12158 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012159 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012160 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012161 // Add ivar's to class's DeclContext.
12162 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12163 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012164 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012165 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012166 // Must enforce the rule that ivars in the base classes may not be
12167 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012168 if (ID->getSuperClass())
12169 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012170 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012171 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012172 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012173 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12174 // Ivar declared in @implementation never belongs to the implementation.
12175 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012176 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012177 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012178 IMPDecl->setIvarLBraceLoc(LBrac);
12179 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012180 } else if (ObjCCategoryDecl *CDecl =
12181 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012182 // case of ivars in class extension; all other cases have been
12183 // reported as errors elsewhere.
12184 // FIXME. Class extension does not have a LocEnd field.
12185 // CDecl->setLocEnd(RBrac);
12186 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012187 // Diagnose redeclaration of private ivars.
12188 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012189 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012190 if (IDecl) {
12191 if (const ObjCIvarDecl *ClsIvar =
12192 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12193 Diag(ClsFields[i]->getLocation(),
12194 diag::err_duplicate_ivar_declaration);
12195 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12196 continue;
12197 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012198 for (ObjCInterfaceDecl::known_extensions_iterator
12199 Ext = IDecl->known_extensions_begin(),
12200 ExtEnd = IDecl->known_extensions_end();
12201 Ext != ExtEnd; ++Ext) {
12202 if (const ObjCIvarDecl *ClsExtIvar
12203 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012204 Diag(ClsFields[i]->getLocation(),
12205 diag::err_duplicate_ivar_declaration);
12206 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12207 continue;
12208 }
12209 }
12210 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012211 ClsFields[i]->setLexicalDeclContext(CDecl);
12212 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012213 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012214 CDecl->setIvarLBraceLoc(LBrac);
12215 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012216 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012217 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012218
12219 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012220 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012221}
12222
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012223/// \brief Determine whether the given integral value is representable within
12224/// the given type T.
12225static bool isRepresentableIntegerValue(ASTContext &Context,
12226 llvm::APSInt &Value,
12227 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012228 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012229 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012230
Douglas Gregor0bf31402010-10-08 23:50:27 +000012231 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012232 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012233 --BitWidth;
12234 return Value.getActiveBits() <= BitWidth;
12235 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012236 return Value.getMinSignedBits() <= BitWidth;
12237}
12238
12239// \brief Given an integral type, return the next larger integral type
12240// (or a NULL type of no such type exists).
12241static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12242 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12243 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012244 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012245 const unsigned NumTypes = 4;
12246 QualType SignedIntegralTypes[NumTypes] = {
12247 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12248 };
12249 QualType UnsignedIntegralTypes[NumTypes] = {
12250 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12251 Context.UnsignedLongLongTy
12252 };
12253
12254 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012255 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12256 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012257 for (unsigned I = 0; I != NumTypes; ++I)
12258 if (Context.getTypeSize(Types[I]) > BitWidth)
12259 return Types[I];
12260
12261 return QualType();
12262}
12263
Douglas Gregor954f6b272009-03-17 19:05:46 +000012264EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12265 EnumConstantDecl *LastEnumConst,
12266 SourceLocation IdLoc,
12267 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012268 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012269 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012270 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012271 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012272
12273 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12274 Val = 0;
12275
Eli Friedman7c6515a2011-12-06 00:10:34 +000012276 if (Val)
12277 Val = DefaultLvalueConversion(Val).take();
12278
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012279 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012280 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012281 EltTy = Context.DependentTy;
12282 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012283 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012284 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012285 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012286 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12287 // constant-expression in the enumerator-definition shall be a converted
12288 // constant expression of the underlying type.
12289 EltTy = Enum->getIntegerType();
12290 ExprResult Converted =
12291 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12292 CCEK_Enumerator);
12293 if (Converted.isInvalid())
12294 Val = 0;
12295 else
12296 Val = Converted.take();
12297 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012298 !(Val = VerifyIntegerConstantExpression(Val,
12299 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012300 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012301 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012302 if (Enum->isFixed()) {
12303 EltTy = Enum->getIntegerType();
12304
Richard Smithf8379a02012-01-18 23:55:52 +000012305 // In Obj-C and Microsoft mode, require the enumeration value to be
12306 // representable in the underlying type of the enumeration. In C++11,
12307 // we perform a non-narrowing conversion as part of converted constant
12308 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012309 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012310 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012311 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012312 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012313 } else
12314 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012315 } else
John Wiegley01296292011-04-08 18:41:53 +000012316 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012317 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012318 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012319 // If the underlying type is not fixed, the type of each enumerator
12320 // is the type of its initializing value:
12321 // - If an initializer is specified for an enumerator, the
12322 // initializing value has the same type as the expression.
12323 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012324 } else {
12325 // C99 6.7.2.2p2:
12326 // The expression that defines the value of an enumeration constant
12327 // shall be an integer constant expression that has a value
12328 // representable as an int.
12329
12330 // Complain if the value is not representable in an int.
12331 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12332 Diag(IdLoc, diag::ext_enum_value_not_int)
12333 << EnumVal.toString(10) << Val->getSourceRange()
12334 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12335 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12336 // Force the type of the expression to 'int'.
12337 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12338 }
12339 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012340 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012341 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012342 }
12343 }
Mike Stump11289f42009-09-09 15:08:12 +000012344
Douglas Gregor954f6b272009-03-17 19:05:46 +000012345 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012346 if (Enum->isDependentType())
12347 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012348 else if (!LastEnumConst) {
12349 // C++0x [dcl.enum]p5:
12350 // If the underlying type is not fixed, the type of each enumerator
12351 // is the type of its initializing value:
12352 // - If no initializer is specified for the first enumerator, the
12353 // initializing value has an unspecified integral type.
12354 //
12355 // GCC uses 'int' for its unspecified integral type, as does
12356 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012357 if (Enum->isFixed()) {
12358 EltTy = Enum->getIntegerType();
12359 }
12360 else {
12361 EltTy = Context.IntTy;
12362 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012363 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012364 // Assign the last value + 1.
12365 EnumVal = LastEnumConst->getInitVal();
12366 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012367 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012368
12369 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012370 if (EnumVal < LastEnumConst->getInitVal()) {
12371 // C++0x [dcl.enum]p5:
12372 // If the underlying type is not fixed, the type of each enumerator
12373 // is the type of its initializing value:
12374 //
12375 // - Otherwise the type of the initializing value is the same as
12376 // the type of the initializing value of the preceding enumerator
12377 // unless the incremented value is not representable in that type,
12378 // in which case the type is an unspecified integral type
12379 // sufficient to contain the incremented value. If no such type
12380 // exists, the program is ill-formed.
12381 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012382 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012383 // There is no integral type larger enough to represent this
12384 // value. Complain, then allow the value to wrap around.
12385 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012386 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012387 ++EnumVal;
12388 if (Enum->isFixed())
12389 // When the underlying type is fixed, this is ill-formed.
12390 Diag(IdLoc, diag::err_enumerator_wrapped)
12391 << EnumVal.toString(10)
12392 << EltTy;
12393 else
12394 Diag(IdLoc, diag::warn_enumerator_too_large)
12395 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012396 } else {
12397 EltTy = T;
12398 }
12399
12400 // Retrieve the last enumerator's value, extent that type to the
12401 // type that is supposed to be large enough to represent the incremented
12402 // value, then increment.
12403 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012404 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012405 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012406 ++EnumVal;
12407
12408 // If we're not in C++, diagnose the overflow of enumerator values,
12409 // which in C99 means that the enumerator value is not representable in
12410 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12411 // permits enumerator values that are representable in some larger
12412 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012413 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012414 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012415 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012416 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12417 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12418 Diag(IdLoc, diag::ext_enum_value_not_int)
12419 << EnumVal.toString(10) << 1;
12420 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012421 }
12422 }
Mike Stump11289f42009-09-09 15:08:12 +000012423
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012424 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012425 // Make the enumerator value match the signedness and size of the
12426 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012427 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012428 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012429 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012430
Douglas Gregor954f6b272009-03-17 19:05:46 +000012431 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012432 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012433}
12434
12435
John McCall811a0f52010-10-22 23:36:17 +000012436Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12437 SourceLocation IdLoc, IdentifierInfo *Id,
12438 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012439 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012440 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012441 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012442 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012443
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012444 // The scope passed in may not be a decl scope. Zip up the scope tree until
12445 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012446 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012447
Chris Lattner8116d1b2007-01-25 22:38:29 +000012448 // Verify that there isn't already something declared with this name in this
12449 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012450 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012451 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012452 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012453 // Maybe we will complain about the shadowed template parameter.
12454 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12455 // Just pretend that we didn't see the previous declaration.
12456 PrevDecl = 0;
12457 }
12458
12459 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012460 // When in C++, we may get a TagDecl with the same name; in this case the
12461 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012462 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012463 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012464 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012465 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012466 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012467 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012468 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012469 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012470 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012471 }
12472 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012473
Aaron Ballman24a10472012-07-19 03:12:23 +000012474 // C++ [class.mem]p15:
12475 // If T is the name of a class, then each of the following shall have a name
12476 // different from T:
12477 // - every enumerator of every member of class T that is an unscoped
12478 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012479 if (CXXRecordDecl *Record
12480 = dyn_cast<CXXRecordDecl>(
12481 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012482 if (!TheEnumDecl->isScoped() &&
12483 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012484 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12485
John McCall811a0f52010-10-22 23:36:17 +000012486 EnumConstantDecl *New =
12487 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012488
John McCall553c0792010-01-23 00:46:32 +000012489 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012490 // Process attributes.
12491 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12492
12493 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012494 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012495 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012496 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012497
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012498 ActOnDocumentableDecl(New);
12499
John McCall48871652010-08-21 09:40:31 +000012500 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012501}
12502
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012503// Returns true when the enum initial expression does not trigger the
12504// duplicate enum warning. A few common cases are exempted as follows:
12505// Element2 = Element1
12506// Element2 = Element1 + 1
12507// Element2 = Element1 - 1
12508// Where Element2 and Element1 are from the same enum.
12509static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12510 Expr *InitExpr = ECD->getInitExpr();
12511 if (!InitExpr)
12512 return true;
12513 InitExpr = InitExpr->IgnoreImpCasts();
12514
12515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12516 if (!BO->isAdditiveOp())
12517 return true;
12518 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12519 if (!IL)
12520 return true;
12521 if (IL->getValue() != 1)
12522 return true;
12523
12524 InitExpr = BO->getLHS();
12525 }
12526
12527 // This checks if the elements are from the same enum.
12528 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12529 if (!DRE)
12530 return true;
12531
12532 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12533 if (!EnumConstant)
12534 return true;
12535
12536 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12537 Enum)
12538 return true;
12539
12540 return false;
12541}
12542
12543struct DupKey {
12544 int64_t val;
12545 bool isTombstoneOrEmptyKey;
12546 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12547 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12548};
12549
12550static DupKey GetDupKey(const llvm::APSInt& Val) {
12551 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12552 false);
12553}
12554
12555struct DenseMapInfoDupKey {
12556 static DupKey getEmptyKey() { return DupKey(0, true); }
12557 static DupKey getTombstoneKey() { return DupKey(1, true); }
12558 static unsigned getHashValue(const DupKey Key) {
12559 return (unsigned)(Key.val * 37);
12560 }
12561 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12562 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12563 LHS.val == RHS.val;
12564 }
12565};
12566
12567// Emits a warning when an element is implicitly set a value that
12568// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012569static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12570 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012571 QualType EnumType) {
12572 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12573 Enum->getLocation()) ==
12574 DiagnosticsEngine::Ignored)
12575 return;
12576 // Avoid anonymous enums
12577 if (!Enum->getIdentifier())
12578 return;
12579
12580 // Only check for small enums.
12581 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12582 return;
12583
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012584 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12585 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012586
12587 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12588 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12589 ValueToVectorMap;
12590
12591 DuplicatesVector DupVector;
12592 ValueToVectorMap EnumMap;
12593
12594 // Populate the EnumMap with all values represented by enum constants without
12595 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012596 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012597 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012598
12599 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12600 // this constant. Skip this enum since it may be ill-formed.
12601 if (!ECD) {
12602 return;
12603 }
12604
12605 if (ECD->getInitExpr())
12606 continue;
12607
12608 DupKey Key = GetDupKey(ECD->getInitVal());
12609 DeclOrVector &Entry = EnumMap[Key];
12610
12611 // First time encountering this value.
12612 if (Entry.isNull())
12613 Entry = ECD;
12614 }
12615
12616 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012617 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012618 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12619 if (!ValidDuplicateEnum(ECD, Enum))
12620 continue;
12621
12622 DupKey Key = GetDupKey(ECD->getInitVal());
12623
12624 DeclOrVector& Entry = EnumMap[Key];
12625 if (Entry.isNull())
12626 continue;
12627
12628 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12629 // Ensure constants are different.
12630 if (D == ECD)
12631 continue;
12632
12633 // Create new vector and push values onto it.
12634 ECDVector *Vec = new ECDVector();
12635 Vec->push_back(D);
12636 Vec->push_back(ECD);
12637
12638 // Update entry to point to the duplicates vector.
12639 Entry = Vec;
12640
12641 // Store the vector somewhere we can consult later for quick emission of
12642 // diagnostics.
12643 DupVector.push_back(Vec);
12644 continue;
12645 }
12646
12647 ECDVector *Vec = Entry.get<ECDVector*>();
12648 // Make sure constants are not added more than once.
12649 if (*Vec->begin() == ECD)
12650 continue;
12651
12652 Vec->push_back(ECD);
12653 }
12654
12655 // Emit diagnostics.
12656 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12657 DupVectorEnd = DupVector.end();
12658 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12659 ECDVector *Vec = *DupVectorIter;
12660 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12661
12662 // Emit warning for one enum constant.
12663 ECDVector::iterator I = Vec->begin();
12664 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12665 << (*I)->getName() << (*I)->getInitVal().toString(10)
12666 << (*I)->getSourceRange();
12667 ++I;
12668
12669 // Emit one note for each of the remaining enum constants with
12670 // the same value.
12671 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12672 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12673 << (*I)->getName() << (*I)->getInitVal().toString(10)
12674 << (*I)->getSourceRange();
12675 delete Vec;
12676 }
12677}
12678
Mike Stump6814d1c2009-05-16 07:06:02 +000012679void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012680 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012681 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012682 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012683 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012684 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012685
12686 if (Attr)
12687 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012688
Eli Friedmand0e60972009-12-11 01:34:50 +000012689 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012690 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012691 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012692 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012693 if (!ECD) continue;
12694
12695 ECD->setType(EnumType);
12696 }
12697
John McCall9aa35be2010-05-06 08:49:23 +000012698 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012699 return;
12700 }
12701
Chris Lattner67933c02007-08-28 05:10:31 +000012702 // TODO: If the result value doesn't fit in an int, it must be a long or long
12703 // long value. ISO C does not support this, but GCC does as an extension,
12704 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012705 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12706 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12707 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012708
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012709 // Verify that all the values are okay, compute the size of the values, and
12710 // reverse the list.
12711 unsigned NumNegativeBits = 0;
12712 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012713
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012714 // Keep track of whether all elements have type int.
12715 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012716
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012717 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012718 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012719 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012720 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012721
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012722 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012723
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012724 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012725 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012726 NumPositiveBits = std::max(NumPositiveBits,
12727 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012728 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012729 NumNegativeBits = std::max(NumNegativeBits,
12730 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012731
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012732 // Keep track of whether every enum element has type int (very commmon).
12733 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012734 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012735 }
Mike Stump11289f42009-09-09 15:08:12 +000012736
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012737 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012738 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012739 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012740
John McCall56774992009-12-09 09:09:27 +000012741 // C++0x N3000 [conv.prom]p3:
12742 // An rvalue of an unscoped enumeration type whose underlying
12743 // type is not fixed can be converted to an rvalue of the first
12744 // of the following types that can represent all the values of
12745 // the enumeration: int, unsigned int, long int, unsigned long
12746 // int, long long int, or unsigned long long int.
12747 // C99 6.4.4.3p2:
12748 // An identifier declared as an enumeration constant has type int.
12749 // The C99 rule is modified by a gcc extension
12750 QualType BestPromotionType;
12751
Aaron Ballman9ead1242013-12-19 02:39:40 +000012752 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012753 // -fshort-enums is the equivalent to specifying the packed attribute on all
12754 // enum definitions.
12755 if (LangOpts.ShortEnums)
12756 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012757
Douglas Gregor0bf31402010-10-08 23:50:27 +000012758 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012759 BestType = Enum->getIntegerType();
12760 if (BestType->isPromotableIntegerType())
12761 BestPromotionType = Context.getPromotedIntegerType(BestType);
12762 else
12763 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012764 // We don't need to set BestWidth, because BestType is going to be the type
12765 // of the enumerators, but we do anyway because otherwise some compilers
12766 // warn that it might be used uninitialized.
12767 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012768 }
12769 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012770 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012771 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012772 // If it's packed, check also if it fits a char or a short.
12773 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012774 BestType = Context.SignedCharTy;
12775 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012776 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012777 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012778 BestType = Context.ShortTy;
12779 BestWidth = ShortWidth;
12780 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012781 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012782 BestWidth = IntWidth;
12783 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012784 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012785
John McCall56774992009-12-09 09:09:27 +000012786 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012787 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012788 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012789 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012790
Chris Lattner3a370bf2007-08-29 17:31:48 +000012791 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012792 Diag(Enum->getLocation(), diag::warn_enum_too_large);
12793 BestType = Context.LongLongTy;
12794 }
12795 }
John McCall56774992009-12-09 09:09:27 +000012796 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012797 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012798 // If there is no negative value, figure out the smallest type that fits
12799 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012800 // If it's packed, check also if it fits a char or a short.
12801 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012802 BestType = Context.UnsignedCharTy;
12803 BestPromotionType = Context.IntTy;
12804 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012805 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012806 BestType = Context.UnsignedShortTy;
12807 BestPromotionType = Context.IntTy;
12808 BestWidth = ShortWidth;
12809 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012810 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012811 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012812 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012813 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012814 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012815 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012816 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012817 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012818 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012819 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012820 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012821 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012822 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012823 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012824 "How could an initializer get larger than ULL?");
12825 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012826 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012827 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012828 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012829 }
12830 }
Mike Stump11289f42009-09-09 15:08:12 +000012831
Chris Lattner3a370bf2007-08-29 17:31:48 +000012832 // Loop over all of the enumerator constants, changing their types to match
12833 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012834 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012835 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012836 if (!ECD) continue; // Already issued a diagnostic.
12837
12838 // Standard C says the enumerators have int type, but we allow, as an
12839 // extension, the enumerators to be larger than int size. If each
12840 // enumerator value fits in an int, type it as an int, otherwise type it the
12841 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12842 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012843
12844 // Determine whether the value fits into an int.
12845 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012846
12847 // If it fits into an integer type, force it. Otherwise force it to match
12848 // the enum decl type.
12849 QualType NewTy;
12850 unsigned NewWidth;
12851 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012852 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012853 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012854 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012855 NewTy = Context.IntTy;
12856 NewWidth = IntWidth;
12857 NewSign = true;
12858 } else if (ECD->getType() == BestType) {
12859 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012860 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012861 // C++ [dcl.enum]p4: Following the closing brace of an
12862 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012863 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012864 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012865 continue;
12866 } else {
12867 NewTy = BestType;
12868 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012869 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012870 }
12871
12872 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012873 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012874 InitVal.setIsSigned(NewSign);
12875 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012876
Chris Lattner3a370bf2007-08-29 17:31:48 +000012877 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012878 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012879 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012880 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012881 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012882 ECD->getInitExpr(),
12883 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012884 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012885 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012886 // C++ [dcl.enum]p4: Following the closing brace of an
12887 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012888 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012889 ECD->setType(EnumType);
12890 else
12891 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012892 }
Mike Stump11289f42009-09-09 15:08:12 +000012893
John McCall9aa35be2010-05-06 08:49:23 +000012894 Enum->completeDefinition(BestType, BestPromotionType,
12895 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012896
12897 // If we're declaring a function, ensure this decl isn't forgotten about -
12898 // it needs to go into the function scope.
12899 if (InFunctionDeclarator)
12900 DeclsInPrototypeScope.push_back(Enum);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012901
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012902 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012903
12904 // Now that the enum type is defined, ensure it's not been underaligned.
12905 if (Enum->hasAttrs())
12906 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012907}
Chris Lattner1300fb92007-01-23 23:42:53 +000012908
Abramo Bagnara348823a2011-03-03 14:20:18 +000012909Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12910 SourceLocation StartLoc,
12911 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012912 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012913
Douglas Gregor278f52e2009-05-30 00:08:05 +000012914 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012915 AsmString, StartLoc,
12916 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012917 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012918 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012919}
Eli Friedman5ed51982009-06-05 02:44:36 +000012920
Douglas Gregor22d09742012-01-03 18:04:46 +000012921DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12922 SourceLocation ImportLoc,
12923 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000012924 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000012925 Module::AllVisible,
12926 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000012927 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000012928 return true;
12929
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012930 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000012931 Module *ModCheck = Mod;
12932 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12933 // If we've run out of module parents, just drop the remaining identifiers.
12934 // We need the length to be consistent.
12935 if (!ModCheck)
12936 break;
12937 ModCheck = ModCheck->Parent;
12938
12939 IdentifierLocs.push_back(Path[I].second);
12940 }
12941
12942 ImportDecl *Import = ImportDecl::Create(Context,
12943 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000012944 AtLoc.isValid()? AtLoc : ImportLoc,
12945 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000012946 Context.getTranslationUnitDecl()->addDecl(Import);
12947 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000012948}
12949
Richard Smithce587f52013-11-15 04:24:58 +000012950void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12951 // FIXME: Should we synthesize an ImportDecl here?
12952 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12953 /*Complain=*/true);
12954}
12955
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012956void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12957 // Create the implicit import declaration.
12958 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12959 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12960 Loc, Mod, Loc);
12961 TU->addDecl(ImportD);
12962 Consumer.HandleImplicitImportDecl(ImportD);
12963
12964 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000012965 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12966 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000012967}
12968
David Chisnall0867d9c2012-02-18 16:12:34 +000012969void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12970 IdentifierInfo* AliasName,
12971 SourceLocation PragmaLoc,
12972 SourceLocation NameLoc,
12973 SourceLocation AliasNameLoc) {
12974 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12975 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000012976 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
12977 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000012978
12979 if (PrevDecl)
12980 PrevDecl->addAttr(Attr);
12981 else
12982 (void)ExtnameUndeclaredIdentifiers.insert(
12983 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12984}
12985
Eli Friedman5ed51982009-06-05 02:44:36 +000012986void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12987 SourceLocation PragmaLoc,
12988 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012989 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000012990
Eli Friedman5ed51982009-06-05 02:44:36 +000012991 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012992 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000012993 } else {
12994 (void)WeakUndeclaredIdentifiers.insert(
12995 std::pair<IdentifierInfo*,WeakInfo>
12996 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000012997 }
Eli Friedman5ed51982009-06-05 02:44:36 +000012998}
12999
13000void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13001 IdentifierInfo* AliasName,
13002 SourceLocation PragmaLoc,
13003 SourceLocation NameLoc,
13004 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013005 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13006 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013007 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013008
Eli Friedman5ed51982009-06-05 02:44:36 +000013009 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013010 if (!PrevDecl->hasAttr<AliasAttr>())
13011 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013012 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013013 } else {
13014 (void)WeakUndeclaredIdentifiers.insert(
13015 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013016 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013017}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013018
13019Decl *Sema::getObjCDeclContext() const {
13020 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13021}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013022
13023AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013024 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013025 // If we are within an Objective-C method, we should consult
13026 // both the availability of the method as well as the
13027 // enclosing class. If the class is (say) deprecated,
13028 // the entire method is considered deprecated from the
13029 // purpose of checking if the current context is deprecated.
13030 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13031 AvailabilityResult R = MD->getAvailability();
13032 if (R != AR_Available)
13033 return R;
13034 D = MD->getClassInterface();
13035 }
13036 // If we are within an Objective-c @implementation, it
13037 // gets the same availability context as the @interface.
13038 else if (const ObjCImplementationDecl *ID =
13039 dyn_cast<ObjCImplementationDecl>(D)) {
13040 D = ID->getClassInterface();
13041 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013042 return D->getAvailability();
13043}