blob: 876b0785c1d65f8b11fbb7f1f983c52ed44cc28f [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 Uhrain67b44c92014-02-13 20:14:07 +000065 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66 bool AllowTemplates=false)
67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68 AllowClassTemplates(AllowTemplates) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000069 WantExpressionKeywords = false;
70 WantCXXNamedCasts = false;
71 WantRemainingKeywords = false;
72 }
73
Craig Toppere14c0f82014-03-12 04:55:44 +000074 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000075 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78 return (IsType || AllowedTemplate) &&
79 (AllowInvalidDecl || !ND->isInvalidDecl());
80 }
81 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000082 }
83
84 private:
85 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000086 bool WantClassName;
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000087 bool AllowClassTemplates;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000088};
89
90}
91
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000092/// \brief Determine whether the token kind starts a simple-type-specifier.
93bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94 switch (Kind) {
95 // FIXME: Take into account the current language when deciding whether a
96 // token kind is a valid type specifier
97 case tok::kw_short:
98 case tok::kw_long:
99 case tok::kw___int64:
100 case tok::kw___int128:
101 case tok::kw_signed:
102 case tok::kw_unsigned:
103 case tok::kw_void:
104 case tok::kw_char:
105 case tok::kw_int:
106 case tok::kw_half:
107 case tok::kw_float:
108 case tok::kw_double:
109 case tok::kw_wchar_t:
110 case tok::kw_bool:
111 case tok::kw___underlying_type:
112 return true;
113
114 case tok::annot_typename:
115 case tok::kw_char16_t:
116 case tok::kw_char32_t:
117 case tok::kw_typeof:
David Majnemera5e92552013-09-22 01:24:26 +0000118 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +0000119 case tok::kw_decltype:
120 return getLangOpts().CPlusPlus;
121
122 default:
123 break;
124 }
125
126 return false;
127}
128
Douglas Gregorec6e1892009-02-04 19:16:12 +0000129/// \brief If the identifier refers to a type name within this scope,
130/// return the declaration of that type.
131///
132/// This routine performs ordinary name lookup of the identifier II
133/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000134/// determine whether the name refers to a type. If so, returns an
135/// opaque pointer (actually a QualType) corresponding to that
136/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000137ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000138 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000139 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000140 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000141 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000142 bool WantNontrivialTypeSourceInfo,
143 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000144 // Determine where we will perform name lookup.
145 DeclContext *LookupCtx = 0;
146 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000147 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000148 if (ObjectType->isRecordType())
149 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000150 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000151 LookupCtx = computeDeclContext(*SS, false);
152
153 if (!LookupCtx) {
154 if (isDependentScopeSpecifier(*SS)) {
155 // C++ [temp.res]p3:
156 // A qualified-id that refers to a type and in which the
157 // nested-name-specifier depends on a template-parameter (14.6.2)
158 // shall be prefixed by the keyword typename to indicate that the
159 // qualified-id denotes a type, forming an
160 // elaborated-type-specifier (7.1.5.3).
161 //
162 // We therefore do not perform any name lookup if the result would
163 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000164 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000165 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000166
John McCallc392f372010-06-11 00:33:02 +0000167 // We know from the grammar that this name refers to a type,
168 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000169 if (WantNontrivialTypeSourceInfo)
170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171
172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000173 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000175 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000176
177 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000178 }
179
John McCallba7bf592010-08-24 05:47:05 +0000180 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000181 }
182
John McCall0b66eb32010-05-01 00:40:08 +0000183 if (!LookupCtx->isDependentContext() &&
184 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000185 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000186 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000187
188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189 // lookup for class-names.
190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191 LookupOrdinaryName;
192 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000193 if (LookupCtx) {
194 // Perform "qualified" name lookup into the declaration context we
195 // computed, which is either the type of the base of a member access
196 // expression or the declaration context associated with a prior
197 // nested-name-specifier.
198 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000199
Douglas Gregora25d65d2009-11-20 22:03:38 +0000200 if (ObjectTypePtr && Result.empty()) {
201 // C++ [basic.lookup.classref]p3:
202 // If the unqualified-id is ~type-name, the type-name is looked up
203 // in the context of the entire postfix-expression. If the type T of
204 // the object expression is of a class type C, the type-name is also
205 // looked up in the scope of class C. At least one of the lookups shall
206 // find a name that refers to (possibly cv-qualified) T.
207 LookupName(Result, S);
208 }
209 } else {
210 // Perform unqualified name lookup.
211 LookupName(Result, S);
212 }
213
Chris Lattnera3778332009-02-16 22:07:16 +0000214 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000215 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000216 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000217 case LookupResult::NotFoundInCurrentInstantiation:
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000218 if (CorrectedII) {
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +0000219 TypeNameValidatorCCC Validator(true, isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000221 Kind, S, SS, Validator);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000222 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
223 TemplateTy Template;
224 bool MemberOfUnknownSpecialization;
225 UnqualifiedId TemplateName;
226 TemplateName.setIdentifier(NewII, NameLoc);
227 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
228 CXXScopeSpec NewSS, *NewSSPtr = SS;
229 if (SS && NNS) {
230 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
231 NewSSPtr = &NewSS;
232 }
233 if (Correction && (NNS || NewII != &II) &&
234 // Ignore a correction to a template type as the to-be-corrected
235 // identifier is not a template (typo correction for template names
236 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000237 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000238 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
239 false, Template, MemberOfUnknownSpecialization))) {
240 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
241 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000242 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000243 WantNontrivialTypeSourceInfo);
244 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000245 diagnoseTypo(Correction,
246 PDiag(diag::err_unknown_type_or_class_name_suggest)
247 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000248 if (SS && NNS)
249 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
250 *CorrectedII = NewII;
251 return Ty;
252 }
253 }
254 }
255 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000256 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000257 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000258 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000259 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000260
Chris Lattnere40853a2009-10-25 22:09:09 +0000261 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000262 // Recover from type-hiding ambiguities by hiding the type. We'll
263 // do the lookup again when looking for an object, and we can
264 // diagnose the error then. If we don't do this, then the error
265 // about hiding the type will be immediately followed by an error
266 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000267 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
268 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000269 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000270 }
John McCall6538c932009-10-10 05:48:19 +0000271
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000272 // Look to see if we have a type anywhere in the list of results.
273 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
274 Res != ResEnd; ++Res) {
275 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000276 if (!IIDecl ||
277 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000278 IIDecl->getLocation().getRawEncoding())
279 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000280 }
281 }
282
283 if (!IIDecl) {
284 // None of the entities we found is a type, so there is no way
285 // to even assume that the result is a type. In this case, don't
286 // complain about the ambiguity. The parser will either try to
287 // perform this lookup again (e.g., as an object name), which
288 // will produce the ambiguity, or will complain that it expected
289 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000290 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000291 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000292 }
293
294 // We found a type within the ambiguous lookup; diagnose the
295 // ambiguity and then return that type. This might be the right
296 // answer, or it might not be, but it suppresses any attempt to
297 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000298 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000299
Chris Lattnera3778332009-02-16 22:07:16 +0000300 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000301 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000302 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000303 }
304
Chris Lattner17e15f12009-10-25 17:16:46 +0000305 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000306
Chris Lattner17e15f12009-10-25 17:16:46 +0000307 QualType T;
308 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000309 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000310
Chris Lattner17e15f12009-10-25 17:16:46 +0000311 if (T.isNull())
312 T = Context.getTypeDeclType(TD);
Abramo Bagnara4244b432012-01-27 08:46:19 +0000313
314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315 // constructor or destructor name (in such a case, the scope specifier
316 // will be attached to the enclosing Expr or Decl node).
317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregor844cb502011-03-01 18:12:44 +0000318 if (WantNontrivialTypeSourceInfo) {
319 // Construct a type with type-source information.
320 TypeLocBuilder Builder;
321 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322
323 T = getElaboratedType(ETK_None, *SS, T);
324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000325 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregor844cb502011-03-01 18:12:44 +0000326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328 } else {
329 T = getElaboratedType(ETK_None, *SS, T);
330 }
331 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000333 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000334 if (!HasTrailingDot)
335 T = Context.getObjCInterfaceType(IDecl);
336 }
337
338 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000339 // If it's not plausibly a type, suppress diagnostics.
340 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000341 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000342 }
John McCallba7bf592010-08-24 05:47:05 +0000343 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000344}
345
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000346/// isTagName() - This method is called *for error recovery purposes only*
347/// to determine if the specified name is a valid tag name ("struct foo"). If
348/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000349/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
350/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000351DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
352 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000353 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
354 LookupName(R, S, false);
355 R.suppressDiagnostics();
356 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000357 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000358 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000359 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000360 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000361 case TTK_Union: return DeclSpec::TST_union;
362 case TTK_Class: return DeclSpec::TST_class;
363 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000364 }
365 }
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000367 return DeclSpec::TST_unspecified;
368}
369
Francois Pichet48c946e2011-04-13 02:38:49 +0000370/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
371/// if a CXXScopeSpec's type is equal to the type of one of the base classes
372/// then downgrade the missing typename error to a warning.
373/// This is needed for MSVC compatibility; Example:
374/// @code
375/// template<class T> class A {
376/// public:
377/// typedef int TYPE;
378/// };
379/// template<class T> class B : public A<T> {
380/// public:
381/// A<T>::TYPE a; // no typename required because A<T> is a base class.
382/// };
383/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000384bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000385 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000386 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000387
388 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
Aaron Ballman574705e2014-03-13 15:41:46 +0000389 for (const auto &Base : RD->bases())
390 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
Francois Pichet48c946e2011-04-13 02:38:49 +0000391 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000392 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000393 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000394 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000395}
396
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000397bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000398 SourceLocation IILoc,
399 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000400 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000401 ParsedType &SuggestedType,
402 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000403 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000404 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000405
Douglas Gregor2d435302009-12-30 17:04:44 +0000406 // There may have been a typo in the name of the type. Look up typo
407 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000408 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000409 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000410 LookupOrdinaryName, S, SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000411 Validator)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000412 if (Corrected.isKeyword()) {
413 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000414 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
415 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000416 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000417 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000418 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000419 diagnoseTypo(Corrected,
420 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000421 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000422 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
423 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000424 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000425 diagnoseTypo(Corrected,
426 PDiag(diag::err_unknown_nested_typename_suggest)
427 << II << DC << DroppedSpecifier << SS->getRange());
428 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000429 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000430 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000431
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000432 CXXScopeSpec tmpSS;
433 if (Corrected.getCorrectionSpecifier())
434 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
435 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000436 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000437 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
438 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000439 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000440 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000441 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000442 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000443 }
444
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000446 // See if II is a class template that the user forgot to pass arguments to.
447 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000448 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000449 CXXScopeSpec EmptySS;
450 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000451 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000452 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000453 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000454 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000455 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000456 Diag(IILoc, diag::err_template_missing_args) << TplName;
457 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
458 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
459 << TplDecl->getTemplateParameters()->getSourceRange();
460 }
461 return true;
462 }
463 }
464
Douglas Gregor15e56022009-10-13 23:27:22 +0000465 // FIXME: Should we move the logic that tries to recover from a missing tag
466 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
467
Douglas Gregor2d435302009-12-30 17:04:44 +0000468 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000469 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000470 else if (DeclContext *DC = computeDeclContext(*SS, false))
471 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000472 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000473 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000474 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000475 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Francois Pichet93921652011-04-22 08:25:24 +0000476 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000477
478 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000479 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000480 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000481 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000482 SuggestedType = ActOnTypenameType(S, SourceLocation(),
483 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000484 } else {
485 assert(SS && SS->isInvalid() &&
486 "Invalid scope specifier has already been diagnosed");
487 }
488
489 return true;
490}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000491
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000492/// \brief Determine whether the given result set contains either a type name
493/// or
494static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000495 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000496 NextToken.is(tok::less);
497
498 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
499 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
500 return true;
501
502 if (CheckTemplate && isa<TemplateDecl>(*I))
503 return true;
504 }
505
506 return false;
507}
508
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000509static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
510 Scope *S, CXXScopeSpec &SS,
511 IdentifierInfo *&Name,
512 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000513 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
514 SemaRef.LookupParsedName(R, S, &SS);
515 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000516 const char *TagName = 0;
517 const char *FixItTagName = 0;
518 switch (Tag->getTagKind()) {
519 case TTK_Class:
520 TagName = "class";
521 FixItTagName = "class ";
522 break;
523
524 case TTK_Enum:
525 TagName = "enum";
526 FixItTagName = "enum ";
527 break;
528
529 case TTK_Struct:
530 TagName = "struct";
531 FixItTagName = "struct ";
532 break;
533
Joao Matosdc86f942012-08-31 18:45:21 +0000534 case TTK_Interface:
535 TagName = "__interface";
536 FixItTagName = "__interface ";
537 break;
538
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000539 case TTK_Union:
540 TagName = "union";
541 FixItTagName = "union ";
542 break;
543 }
544
545 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
546 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
547 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
548
Richard Smithaa31b4b2012-09-06 01:37:56 +0000549 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
550 I != IEnd; ++I)
551 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
552 << Name << TagName;
553
554 // Replace lookup results with just the tag decl.
555 Result.clear(Sema::LookupTagName);
556 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000557 return true;
558 }
559
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000560 return false;
561}
562
Richard Smith4f605af2012-08-18 00:55:03 +0000563/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
564static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
565 QualType T, SourceLocation NameLoc) {
566 ASTContext &Context = S.Context;
567
568 TypeLocBuilder Builder;
569 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
570
571 T = S.getElaboratedType(ETK_None, SS, T);
572 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
573 ElabTL.setElaboratedKeywordLoc(SourceLocation());
574 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
575 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
576}
577
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000578Sema::NameClassification Sema::ClassifyName(Scope *S,
579 CXXScopeSpec &SS,
580 IdentifierInfo *&Name,
581 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000582 const Token &NextToken,
583 bool IsAddressOfOperand,
584 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000585 DeclarationNameInfo NameInfo(Name, NameLoc);
586 ObjCMethodDecl *CurMethod = getCurMethodDecl();
587
588 if (NextToken.is(tok::coloncolon)) {
589 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
590 QualType(), false, SS, 0, false);
591
592 }
593
594 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
595 LookupParsedName(Result, S, &SS, !CurMethod);
596
597 // Perform lookup for Objective-C instance variables (including automatically
598 // synthesized instance variables), if we're in an Objective-C method.
599 // FIXME: This lookup really, really needs to be folded in to the normal
600 // unqualified lookup mechanism.
601 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
602 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000603 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000604 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000605 }
606
607 bool SecondTry = false;
608 bool IsFilteredTemplateName = false;
609
610Corrected:
611 switch (Result.getResultKind()) {
612 case LookupResult::NotFound:
613 // If an unqualified-id is followed by a '(', then we have a function
614 // call.
615 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
616 // In C++, this is an ADL-only call.
617 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000618 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000619 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
620
621 // C90 6.3.2.2:
622 // If the expression that precedes the parenthesized argument list in a
623 // function call consists solely of an identifier, and if no
624 // declaration is visible for this identifier, the identifier is
625 // implicitly declared exactly as if, in the innermost block containing
626 // the function call, the declaration
627 //
628 // extern int identifier ();
629 //
630 // appeared.
631 //
632 // We also allow this in C99 as an extension.
633 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
634 Result.addDecl(D);
635 Result.resolveKind();
636 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
637 }
638 }
639
640 // In C, we first see whether there is a tag type by the same name, in
641 // which case it's likely that the user just forget to write "enum",
642 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000643 if (!getLangOpts().CPlusPlus && !SecondTry &&
644 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
645 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000646 }
647
648 // Perform typo correction to determine if there is another name that is
649 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000650 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000651 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000652 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000653 Result.getLookupKind(), S,
Richard Smith4f605af2012-08-18 00:55:03 +0000654 &SS, *CCC)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000655 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
656 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000657
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000658 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000659 NamedDecl *UnderlyingFirstDecl
660 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000661 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000662 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000663 UnqualifiedDiag = diag::err_no_template_suggest;
664 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000665 } else if (UnderlyingFirstDecl &&
666 (isa<TypeDecl>(UnderlyingFirstDecl) ||
667 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
668 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000669 UnqualifiedDiag = diag::err_unknown_typename_suggest;
670 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
671 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000672
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000673 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000674 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000675 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000676 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
677 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000678 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000679 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
680 << Name << computeDeclContext(SS, false)
681 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000682 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000683
684 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000685 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000686
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000687 // Typo correction corrected to a keyword.
688 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000689 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000690
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000691 // Also update the LookupResult...
692 // FIXME: This should probably go away at some point
693 Result.clear();
694 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000695 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000696 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000697
698 // If we found an Objective-C instance variable, let
699 // LookupInObjCMethod build the appropriate expression to
700 // reference the ivar.
701 // FIXME: This is a gross hack.
702 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
703 Result.clear();
704 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000705 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000706 }
707
708 goto Corrected;
709 }
710 }
711
712 // We failed to correct; just fall through and let the parser deal with it.
713 Result.suppressDiagnostics();
714 return NameClassification::Unknown();
715
Abramo Bagnara7945c982012-01-27 09:46:47 +0000716 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000717 // We performed name lookup into the current instantiation, and there were
718 // dependent bases, so we treat this result the same way as any other
719 // dependent nested-name-specifier.
720
721 // C++ [temp.res]p2:
722 // A name used in a template declaration or definition and that is
723 // dependent on a template-parameter is assumed not to name a type
724 // unless the applicable name lookup finds a type name or the name is
725 // qualified by the keyword typename.
726 //
727 // FIXME: If the next token is '<', we might want to ask the parser to
728 // perform some heroics to see if we actually have a
729 // template-argument-list, which would indicate a missing 'template'
730 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000731 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
732 NameInfo, IsAddressOfOperand,
733 /*TemplateArgs=*/0);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000734 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000735
736 case LookupResult::Found:
737 case LookupResult::FoundOverloaded:
738 case LookupResult::FoundUnresolvedValue:
739 break;
740
741 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000742 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000743 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000744 // C++ [temp.local]p3:
745 // A lookup that finds an injected-class-name (10.2) can result in an
746 // ambiguity in certain cases (for example, if it is found in more than
747 // one base class). If all of the injected-class-names that are found
748 // refer to specializations of the same class template, and if the name
749 // is followed by a template-argument-list, the reference refers to the
750 // class template itself and not a specialization thereof, and is not
751 // ambiguous.
752 //
753 // This filtering can make an ambiguous result into an unambiguous one,
754 // so try again after filtering out template names.
755 FilterAcceptableTemplateNames(Result);
756 if (!Result.isAmbiguous()) {
757 IsFilteredTemplateName = true;
758 break;
759 }
760 }
761
762 // Diagnose the ambiguity and return an error.
763 return NameClassification::Error();
764 }
765
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000767 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
768 // C++ [temp.names]p3:
769 // After name lookup (3.4) finds that a name is a template-name or that
770 // an operator-function-id or a literal- operator-id refers to a set of
771 // overloaded functions any member of which is a function template if
772 // this is followed by a <, the < is always taken as the delimiter of a
773 // template-argument-list and never as the less-than operator.
774 if (!IsFilteredTemplateName)
775 FilterAcceptableTemplateNames(Result);
776
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000777 if (!Result.empty()) {
778 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000779 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000780 TemplateName Template;
781 if (Result.end() - Result.begin() > 1) {
782 IsFunctionTemplate = true;
783 Template = Context.getOverloadedTemplateName(Result.begin(),
784 Result.end());
785 } else {
786 TemplateDecl *TD
787 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
788 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000789 IsVarTemplate = isa<VarTemplateDecl>(TD);
790
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000791 if (SS.isSet() && !SS.isInvalid())
792 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000793 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000794 TD);
795 else
796 Template = TemplateName(TD);
797 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000798
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000799 if (IsFunctionTemplate) {
800 // Function templates always go through overload resolution, at which
801 // point we'll perform the various checks (e.g., accessibility) we need
802 // to based on which function we selected.
803 Result.suppressDiagnostics();
804
805 return NameClassification::FunctionTemplate(Template);
806 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000807
808 return IsVarTemplate ? NameClassification::VarTemplate(Template)
809 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000810 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000811 }
Richard Smith4f605af2012-08-18 00:55:03 +0000812
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000813 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000814 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
815 DiagnoseUseOfDecl(Type, NameLoc);
816 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000817 if (SS.isNotEmpty())
818 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000819 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000820 }
Richard Smith4f605af2012-08-18 00:55:03 +0000821
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000822 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
823 if (!Class) {
824 // FIXME: It's unfortunate that we don't have a Type node for handling this.
825 if (ObjCCompatibleAliasDecl *Alias
826 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
827 Class = Alias->getClassInterface();
828 }
829
830 if (Class) {
831 DiagnoseUseOfDecl(Class, NameLoc);
832
833 if (NextToken.is(tok::period)) {
834 // Interface. <something> is parsed as a property reference expression.
835 // Just return "unknown" as a fall-through for now.
836 Result.suppressDiagnostics();
837 return NameClassification::Unknown();
838 }
839
840 QualType T = Context.getObjCInterfaceType(Class);
841 return ParsedType::make(T);
842 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000843
Richard Smith4f605af2012-08-18 00:55:03 +0000844 // We can have a type template here if we're classifying a template argument.
845 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
846 return NameClassification::TypeTemplate(
847 TemplateName(cast<TemplateDecl>(FirstDecl)));
848
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000849 // Check for a tag type hidden by a non-type decl in a few cases where it
850 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000851 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
852 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000853 (NextIsOp &&
854 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000855 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
856 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
857 DiagnoseUseOfDecl(Type, NameLoc);
858 QualType T = Context.getTypeDeclType(Type);
859 if (SS.isNotEmpty())
860 return buildNestedType(*this, SS, T, NameLoc);
861 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000862 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000863
Richard Smith4f605af2012-08-18 00:55:03 +0000864 if (FirstDecl->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +0000865 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000866
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000867 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
868 return BuildDeclarationNameExpr(SS, Result, ADL);
869}
870
John McCall5ed6e8f2009-08-18 00:00:49 +0000871// Determines the context to return to after temporarily entering a
872// context. This depends in an unnecessarily complicated way on the
873// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000874DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000875
John McCall5ed6e8f2009-08-18 00:00:49 +0000876 // Functions defined inline within classes aren't parsed until we've
877 // finished parsing the top-level class, so the top-level class is
878 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000879 // A Lambda call operator whose parent is a class must not be treated
880 // as an inline member function. A Lambda can be used legally
881 // either as an in-class member initializer or a default argument. These
882 // are parsed once the class has been marked complete and so the containing
883 // context would be the nested class (when the lambda is defined in one);
884 // If the class is not complete, then the lambda is being used in an
885 // ill-formed fashion (such as to specify the width of a bit-field, or
886 // in an array-bound) - in which case we still want to return the
887 // lexically containing DC (which could be a nested class).
888 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000889 DC = DC->getLexicalParent();
890
891 // A function not defined within a class will always return to its
892 // lexical context.
893 if (!isa<CXXRecordDecl>(DC))
894 return DC;
895
896 // A C++ inline method/friend is parsed *after* the topmost class
897 // it was declared in is fully parsed ("complete"); the topmost
898 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000899 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900 DC = RD;
901
902 // Return the declaration context of the topmost class the inline method is
903 // declared in.
904 return DC;
905 }
906
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000907 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000908}
909
Douglas Gregor91f84212008-12-11 16:49:14 +0000910void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000911 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000912 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000913 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000914 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000915}
916
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000917void Sema::PopDeclContext() {
918 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000919
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000920 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000921 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000922}
923
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000924/// EnterDeclaratorContext - Used when we must lookup names in the context
925/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000926///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000927void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000928 // C++0x [basic.lookup.unqual]p13:
929 // A name used in the definition of a static data member of class
930 // X (after the qualified-id of the static member) is looked up as
931 // if the name was used in a member function of X.
932 // C++0x [basic.lookup.unqual]p14:
933 // If a variable member of a namespace is defined outside of the
934 // scope of its namespace then any name used in the definition of
935 // the variable member (after the declarator-id) is looked up as
936 // if the definition of the variable member occurred in its
937 // namespace.
938 // Both of these imply that we should push a scope whose context
939 // is the semantic context of the declaration. We can't use
940 // PushDeclContext here because that context is not necessarily
941 // lexically contained in the current context. Fortunately,
942 // the containing scope should have the appropriate information.
943
944 assert(!S->getEntity() && "scope already has entity");
945
946#ifndef NDEBUG
947 Scope *Ancestor = S->getParent();
948 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
949 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
950#endif
951
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000952 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000953 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000954}
955
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000956void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000957 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000958
John McCall6df5fef2009-12-19 10:49:29 +0000959 // Switch back to the lexical context. The safety of this is
960 // enforced by an assert in EnterDeclaratorContext.
961 Scope *Ancestor = S->getParent();
962 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +0000963 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +0000964
965 // We don't need to do anything with the scope, which is going to
966 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000967}
968
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000969
970void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +0000971 // We assume that the caller has already called
972 // ActOnReenterTemplateScope so getTemplatedDecl() works.
973 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000974 if (!FD)
975 return;
976
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000977 // Same implementation as PushDeclContext, but enters the context
978 // from the lexical parent, rather than the top-level class.
979 assert(CurContext == FD->getLexicalParent() &&
980 "The next DeclContext should be lexically contained in the current one.");
981 CurContext = FD;
982 S->setEntity(CurContext);
983
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000984 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
985 ParmVarDecl *Param = FD->getParamDecl(P);
986 // If the parameter has an identifier, then add it to the scope
987 if (Param->getIdentifier()) {
988 S->AddDecl(Param);
989 IdResolver.AddDecl(Param);
990 }
991 }
992}
993
994
DeLesley Hutchins6f860042012-04-06 15:10:17 +0000995void Sema::ActOnExitFunctionContext() {
996 // Same implementation as PopDeclContext, but returns to the lexical parent,
997 // rather than the top-level class.
998 assert(CurContext && "DeclContext imbalance!");
999 CurContext = CurContext->getLexicalParent();
1000 assert(CurContext && "Popped translation unit!");
1001}
1002
1003
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001004/// \brief Determine whether we allow overloading of the function
1005/// PrevDecl with another declaration.
1006///
1007/// This routine determines whether overloading is possible, not
1008/// whether some new function is actually an overload. It will return
1009/// true in C++ (where we can always provide overloads) or, as an
1010/// extension, in C when the previous function is already an
1011/// overloaded function declaration or has the "overloadable"
1012/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001013static bool AllowOverloadingOfFunction(LookupResult &Previous,
1014 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001015 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001016 return true;
1017
John McCall1f82f242009-11-18 22:49:29 +00001018 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001019 return true;
1020
John McCall1f82f242009-11-18 22:49:29 +00001021 return (Previous.getResultKind() == LookupResult::Found
1022 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001023}
1024
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001025/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001026void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001027 // Move up the scope chain until we find the nearest enclosing
1028 // non-transparent context. The declaration will be introduced into this
1029 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001030 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001031 S = S->getParent();
1032
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001033 // Add scoped declarations into their context, so that they can be
1034 // found later. Declarations without a context won't be inserted
1035 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001036 if (AddToContext)
1037 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001038
Richard Smith541b38b2013-09-20 01:15:31 +00001039 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1040 // are function-local declarations.
1041 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001042 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001043 D->getLexicalDeclContext()->getRedeclContext()) &&
1044 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001045 return;
1046
1047 // Template instantiations should also not be pushed into scope.
1048 if (isa<FunctionDecl>(D) &&
1049 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001050 return;
1051
John McCall9f3059a2009-10-09 21:13:30 +00001052 // If this replaces anything in the current scope,
1053 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1054 IEnd = IdResolver.end();
1055 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001056 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1057 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001058 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001059
John McCall9f3059a2009-10-09 21:13:30 +00001060 // Should only need to replace one decl.
1061 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001062 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001063 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
John McCall48871652010-08-21 09:40:31 +00001065 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001066
1067 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1068 // Implicitly-generated labels may end up getting generated in an order that
1069 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1070 // the label at the appropriate place in the identifier chain.
1071 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001072 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001073 if (IDC == CurContext) {
1074 if (!S->isDeclScope(*I))
1075 continue;
1076 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001077 break;
1078 }
1079
Douglas Gregor46c04e72011-03-16 16:39:03 +00001080 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001081 } else {
1082 IdResolver.AddDecl(D);
1083 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001084}
1085
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001086void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1087 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1088 TUScope->AddDecl(D);
1089}
1090
Richard Smith1c34fb72013-08-13 18:18:50 +00001091bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001092 bool AllowInlineNamespace) {
1093 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001094}
1095
John McCallcc14d1f2010-08-24 08:50:51 +00001096Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1097 DeclContext *TargetDC = DC->getPrimaryContext();
1098 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001099 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001100 if (ScopeDC->getPrimaryContext() == TargetDC)
1101 return S;
1102 } while ((S = S->getParent()));
1103
1104 return 0;
1105}
1106
John McCall1f82f242009-11-18 22:49:29 +00001107static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1108 DeclContext*,
1109 ASTContext&);
1110
1111/// Filters out lookup results that don't fall within the given scope
1112/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001113void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001114 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001115 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001116 LookupResult::Filter F = R.makeFilter();
1117 while (F.hasNext()) {
1118 NamedDecl *D = F.next();
1119
Richard Smith72bcaec2013-12-05 04:30:04 +00001120 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001121 continue;
1122
Richard Smith72bcaec2013-12-05 04:30:04 +00001123 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001124 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001125
John McCall1f82f242009-11-18 22:49:29 +00001126 F.erase();
1127 }
1128
1129 F.done();
1130}
1131
1132static bool isUsingDecl(NamedDecl *D) {
1133 return isa<UsingShadowDecl>(D) ||
1134 isa<UnresolvedUsingTypenameDecl>(D) ||
1135 isa<UnresolvedUsingValueDecl>(D);
1136}
1137
1138/// Removes using shadow declarations from the lookup results.
1139static void RemoveUsingDecls(LookupResult &R) {
1140 LookupResult::Filter F = R.makeFilter();
1141 while (F.hasNext())
1142 if (isUsingDecl(F.next()))
1143 F.erase();
1144
1145 F.done();
1146}
1147
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001148/// \brief Check for this common pattern:
1149/// @code
1150/// class S {
1151/// S(const S&); // DO NOT IMPLEMENT
1152/// void operator=(const S&); // DO NOT IMPLEMENT
1153/// };
1154/// @endcode
1155static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1156 // FIXME: Should check for private access too but access is set after we get
1157 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001158 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001159 return false;
1160
1161 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1162 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1164 return Method->isCopyAssignmentOperator();
1165 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001166}
1167
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001168// We need this to handle
1169//
1170// typedef struct {
1171// void *foo() { return 0; }
1172// } A;
1173//
1174// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1175// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001176// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001177// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001178// Callers should verify at the end of the TU if it D has external linkage or
1179// not.
1180bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1181 const DeclContext *DC = D->getDeclContext();
1182 while (!DC->isTranslationUnit()) {
1183 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1184 if (!RD->hasNameForLinkage())
1185 return true;
1186 }
1187 DC = DC->getParent();
1188 }
1189
Rafael Espindola3ae00052013-05-13 00:12:11 +00001190 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001191}
1192
Eli Friedman5ef21752013-09-10 03:05:56 +00001193// FIXME: This needs to be refactored; some other isInMainFile users want
1194// these semantics.
1195static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1196 if (S.TUKind != TU_Complete)
1197 return false;
1198 return S.SourceMgr.isInMainFile(Loc);
1199}
1200
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001201bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1202 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001203
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001204 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1205 return false;
1206
1207 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001208 if (D->getDeclContext()->isDependentContext() ||
1209 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001210 return false;
1211
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001212 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001213 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1214 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001215
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1217 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1218 return false;
1219 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001220 // 'static inline' functions are defined in headers; don't warn.
1221 if (FD->isInlineSpecified() &&
1222 !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001223 return false;
1224 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001225
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001226 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001227 Context.DeclMustBeEmitted(FD))
1228 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001229 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001230 // Constants and utility variables are defined in headers with internal
1231 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1232 // like "inline".)
1233 if (!isMainFileLoc(*this, VD->getLocation()))
1234 return false;
1235
Eli Friedman5ef21752013-09-10 03:05:56 +00001236 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001237 return false;
1238
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001239 if (VD->isStaticDataMember() &&
1240 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1241 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001242 } else {
1243 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001244 }
1245
John McCalld37d35b2010-10-27 01:41:35 +00001246 // Only warn for unused decls internal to the translation unit.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001247 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001248}
1249
1250void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001251 if (!D)
1252 return;
1253
1254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001255 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001256 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1257 return; // First should already be in the vector.
1258 }
1259
1260 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001261 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001262 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1263 return; // First should already be in the vector.
1264 }
1265
David Blaikie3d8edc22012-05-26 05:35:39 +00001266 if (ShouldWarnIfUnusedFileScopedDecl(D))
1267 UnusedFileScopedDecls.push_back(D);
1268}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001269
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001270static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001271 if (D->isInvalidDecl())
1272 return false;
1273
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001274 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1275 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001276 return false;
John McCall67da35c2010-02-04 22:26:26 +00001277
Chris Lattnercab02a62011-02-17 20:34:02 +00001278 if (isa<LabelDecl>(D))
1279 return true;
1280
John McCall67da35c2010-02-04 22:26:26 +00001281 // White-list anything that isn't a local variable.
1282 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1283 !D->getDeclContext()->isFunctionOrMethod())
1284 return false;
1285
1286 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001287 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001288
1289 // White-list anything with an __attribute__((unused)) type.
1290 QualType Ty = VD->getType();
1291
1292 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001293 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001294 if (TT->getDecl()->hasAttr<UnusedAttr>())
1295 return false;
1296 }
1297
Douglas Gregor14f232e2010-05-08 23:05:03 +00001298 // If we failed to complete the type for some reason, or if the type is
1299 // dependent, don't diagnose the variable.
1300 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001301 return false;
1302
John McCallcef15822010-03-31 02:47:45 +00001303 if (const TagType *TT = Ty->getAs<TagType>()) {
1304 const TagDecl *Tag = TT->getDecl();
1305 if (Tag->hasAttr<UnusedAttr>())
1306 return false;
1307
1308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001309 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001310 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001311
1312 if (const Expr *Init = VD->getInit()) {
David Blaikiea9d4a932012-10-24 21:29:06 +00001313 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1314 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001315 const CXXConstructExpr *Construct =
1316 dyn_cast<CXXConstructExpr>(Init);
1317 if (Construct && !Construct->isElidable()) {
1318 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001319 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001320 return false;
1321 }
1322 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001323 }
1324 }
John McCallcef15822010-03-31 02:47:45 +00001325
1326 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001327 }
1328
John McCall67da35c2010-02-04 22:26:26 +00001329 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001330}
1331
Anna Zaks964f4c62011-07-28 20:52:06 +00001332static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1333 FixItHint &Hint) {
1334 if (isa<LabelDecl>(D)) {
1335 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001337 if (AfterColon.isInvalid())
1338 return;
1339 Hint = FixItHint::CreateRemoval(CharSourceRange::
1340 getCharRange(D->getLocStart(), AfterColon));
1341 }
1342 return;
1343}
1344
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001345/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1346/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001347void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
Anna Zaks964f4c62011-07-28 20:52:06 +00001348 FixItHint Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001349 if (!ShouldDiagnoseUnusedDecl(D))
1350 return;
1351
Anna Zaks964f4c62011-07-28 20:52:06 +00001352 GenerateFixForUnusedDecl(D, Context, Hint);
1353
Chris Lattnercab02a62011-02-17 20:34:02 +00001354 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001355 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001356 DiagID = diag::warn_unused_exception_param;
1357 else if (isa<LabelDecl>(D))
1358 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001359 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001360 DiagID = diag::warn_unused_variable;
1361
Anna Zaks964f4c62011-07-28 20:52:06 +00001362 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001363}
1364
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001365static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1366 // Verify that we have no forward references left. If so, there was a goto
1367 // or address of a label taken, but no definition of it. Label fwd
1368 // definitions are indicated with a null substmt.
1369 if (L->getStmt() == 0)
1370 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1371}
1372
Steve Naroffc62adb62007-10-09 22:01:59 +00001373void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001374 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001375 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001376 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001377
Chris Lattner302b4be2006-11-19 02:31:38 +00001378 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1379 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001380 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001381 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001382
Douglas Gregor91f84212008-12-11 16:49:14 +00001383 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1384 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001385
Douglas Gregor91f84212008-12-11 16:49:14 +00001386 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001387
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001388 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001389 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001390 DiagnoseUnusedDecl(D);
1391
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001392 // If this was a forward reference to a label, verify it was defined.
1393 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1394 CheckPoppedLabel(LD, *this);
1395
Douglas Gregor91f84212008-12-11 16:49:14 +00001396 // Remove this name from our lexical scope.
1397 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001398 }
1399}
1400
Douglas Gregor1c283312010-08-11 12:19:30 +00001401/// \brief Look for an Objective-C class in the translation unit.
1402///
1403/// \param Id The name of the Objective-C class we're looking for. If
1404/// typo-correction fixes this name, the Id will be updated
1405/// to the fixed name.
1406///
1407/// \param IdLoc The location of the name in the translation unit.
1408///
James Dennett41725122012-06-22 10:16:05 +00001409/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001410/// if there is no class with the given name.
1411///
1412/// \returns The declaration of the named Objective-C class, or NULL if the
1413/// class could not be found.
1414ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1415 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001416 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001417 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1418 // creation from this context.
1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1420
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001421 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001422 // Perform typo correction at the given location, but only if we
1423 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001424 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1426 LookupOrdinaryName, TUScope, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001427 Validator)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001430 Id = IDecl->getIdentifier();
1431 }
1432 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1434 // This routine must always return a class definition, if any.
1435 if (Def && Def->getDefinition())
1436 Def = Def->getDefinition();
1437 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001438}
1439
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001440/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1441/// from S, where a non-field would be declared. This routine copes
1442/// with the difference between C and C++ scoping rules in structs and
1443/// unions. For example, the following code is well-formed in C but
1444/// ill-formed in C++:
1445/// @code
1446/// struct S6 {
1447/// enum { BAR } e;
1448/// };
Mike Stump11289f42009-09-09 15:08:12 +00001449///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001450/// void test_S6() {
1451/// struct S6 a;
1452/// a.e = BAR;
1453/// }
1454/// @endcode
1455/// For the declaration of BAR, this routine will return a different
1456/// scope. The scope S will be the scope of the unnamed enumeration
1457/// within S6. In C++, this routine will return the scope associated
1458/// with S6, because the enumeration's scope is a transparent
1459/// context but structures can contain non-field names. In C, this
1460/// routine will return the translation unit scope, since the
1461/// enumeration's scope is a transparent context and structures cannot
1462/// contain non-field names.
1463Scope *Sema::getNonFieldDeclScope(Scope *S) {
1464 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001465 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001466 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001467 S = S->getParent();
1468 return S;
1469}
1470
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001471/// \brief Looks up the declaration of "struct objc_super" and
1472/// saves it for later use in building builtin declaration of
1473/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1474/// pre-existing declaration exists no action takes place.
1475static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1476 IdentifierInfo *II) {
1477 if (!II->isStr("objc_msgSendSuper"))
1478 return;
1479 ASTContext &Context = ThisSema.Context;
1480
1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1482 SourceLocation(), Sema::LookupTagName);
1483 ThisSema.LookupName(Result, S);
1484 if (Result.getResultKind() == LookupResult::Found)
1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1486 Context.setObjCSuperType(Context.getTagDeclType(TD));
1487}
1488
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001489/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1490/// file scope. lazily create a decl for it. ForRedeclaration is true
1491/// if we're creating this built-in in anticipation of redeclaring the
1492/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001493NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001494 Scope *S, bool ForRedeclaration,
1495 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001496 LookupPredefedObjCSuperType(*this, S, II);
1497
Chris Lattner9561a0b2007-01-28 08:20:04 +00001498 Builtin::ID BID = (Builtin::ID)bid;
1499
Chris Lattnerecd79c62009-06-14 00:45:47 +00001500 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001501 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001502 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001503 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001504 // Okay
1505 break;
1506
Mike Stump93246cc2009-07-28 23:57:15 +00001507 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001508 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001509 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001510 << Context.BuiltinInfo.GetName(BID);
1511 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001512
Mike Stump93246cc2009-07-28 23:57:15 +00001513 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001514 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001516 << Context.BuiltinInfo.GetName(BID);
1517 return 0;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001518
1519 case ASTContext::GE_Missing_ucontext:
1520 if (ForRedeclaration)
1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1522 << Context.BuiltinInfo.GetName(BID);
1523 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001524 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001525
1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1527 Diag(Loc, diag::ext_implicit_lib_function_decl)
1528 << Context.BuiltinInfo.GetName(BID)
1529 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001530 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
David Blaikie9c902b52011-09-25 23:23:43 +00001532 != DiagnosticsEngine::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001533 Diag(Loc, diag::note_please_include_header)
1534 << Context.BuiltinInfo.getHeaderName(BID)
1535 << Context.BuiltinInfo.GetName(BID);
1536 }
1537
Warren Hunt445d83e2013-11-01 23:46:51 +00001538 DeclContext *Parent = Context.getTranslationUnitDecl();
1539 if (getLangOpts().CPlusPlus) {
1540 LinkageSpecDecl *CLinkageDecl =
1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1542 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001543 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001544 Parent->addDecl(CLinkageDecl);
1545 Parent = CLinkageDecl;
1546 }
1547
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001548 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001549 Parent,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001550 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001551 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001552 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001553 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001554 New->setImplicit();
1555
Chris Lattner4dd27102008-05-05 22:18:14 +00001556 // Create Decl objects for each parameter, adding them to the
1557 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001558 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001559 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001560 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001561 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001562 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1563 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001564 parm->setScopeInfo(0, i);
1565 Params.push_back(parm);
1566 }
David Blaikie9c70e042011-09-21 18:16:56 +00001567 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
1570 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001571 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001573 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001574 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1575 // relate Scopes to DeclContexts, and probably eliminate CurContext
1576 // entirely, but we're not there yet.
1577 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001578 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001579 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001580 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001581 return New;
1582}
1583
Douglas Gregor3552dab2013-01-09 00:47:56 +00001584/// \brief Filter out any previous declarations that the given declaration
1585/// should not consider because they are not permitted to conflict, e.g.,
1586/// because they come from hidden sub-modules and do not refer to the same
1587/// entity.
1588static void filterNonConflictingPreviousDecls(ASTContext &context,
1589 NamedDecl *decl,
1590 LookupResult &previous){
1591 // This is only interesting when modules are enabled.
1592 if (!context.getLangOpts().Modules)
1593 return;
1594
1595 // Empty sets are uninteresting.
1596 if (previous.empty())
1597 return;
1598
Douglas Gregor3552dab2013-01-09 00:47:56 +00001599 LookupResult::Filter filter = previous.makeFilter();
1600 while (filter.hasNext()) {
1601 NamedDecl *old = filter.next();
1602
1603 // Non-hidden declarations are never ignored.
1604 if (!old->isHidden())
1605 continue;
1606
Rafael Espindola3ae00052013-05-13 00:12:11 +00001607 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001608 filter.erase();
1609 }
1610
1611 filter.done();
1612}
1613
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001614bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1615 QualType OldType;
1616 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1617 OldType = OldTypedef->getUnderlyingType();
1618 else
1619 OldType = Context.getTypeDeclType(Old);
1620 QualType NewType = New->getUnderlyingType();
1621
Douglas Gregoraab36982012-01-11 22:33:48 +00001622 if (NewType->isVariablyModifiedType()) {
1623 // Must not redefine a typedef with a variably-modified type.
1624 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1625 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1626 << Kind << NewType;
1627 if (Old->getLocation().isValid())
1628 Diag(Old->getLocation(), diag::note_previous_definition);
1629 New->setInvalidDecl();
1630 return true;
1631 }
1632
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001633 if (OldType != NewType &&
1634 !OldType->isDependentType() &&
1635 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001636 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1638 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1639 << Kind << NewType << OldType;
1640 if (Old->getLocation().isValid())
1641 Diag(Old->getLocation(), diag::note_previous_definition);
1642 New->setInvalidDecl();
1643 return true;
1644 }
1645 return false;
1646}
1647
Richard Smithdda56e42011-04-15 14:24:37 +00001648/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001649/// same name and scope as a previous declaration 'Old'. Figure out
1650/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001651/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001652///
Richard Smithdda56e42011-04-15 14:24:37 +00001653void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001654 // If the new decl is known invalid already, don't bother doing any
1655 // merging checks.
1656 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroff44cfcb62008-09-09 14:32:20 +00001658 // Allow multiple definitions for ObjC built-in typedefs.
1659 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001661 const IdentifierInfo *TypeID = New->getIdentifier();
1662 switch (TypeID->getLength()) {
1663 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001664 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001665 {
1666 if (!TypeID->isStr("id"))
1667 break;
1668 QualType T = New->getUnderlyingType();
1669 if (!T->isPointerType())
1670 break;
1671 if (!T->isVoidPointerType()) {
1672 QualType PT = T->getAs<PointerType>()->getPointeeType();
1673 if (!PT->isStructureType())
1674 break;
1675 }
1676 Context.setObjCIdRedefinitionType(T);
1677 // Install the built-in type for 'id', ignoring the current definition.
1678 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1679 return;
1680 }
Chris Lattner66e32812008-11-20 05:41:43 +00001681 case 5:
1682 if (!TypeID->isStr("Class"))
1683 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001684 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001685 // Install the built-in type for 'Class', ignoring the current definition.
1686 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001687 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001688 case 3:
1689 if (!TypeID->isStr("SEL"))
1690 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001691 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001692 // Install the built-in type for 'SEL', ignoring the current definition.
1693 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001694 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001695 }
1696 // Fall through - the typedef name was not a builtin type.
1697 }
John McCall1f82f242009-11-18 22:49:29 +00001698
Douglas Gregorfb034662009-01-28 17:15:10 +00001699 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001700 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1701 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001702 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001703 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001704
1705 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001706 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001707 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001708
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001709 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001710 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001711
John McCall1f82f242009-11-18 22:49:29 +00001712 // If the old declaration is invalid, just give up here.
1713 if (Old->isInvalidDecl())
1714 return New->setInvalidDecl();
1715
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001716 // If the typedef types are not identical, reject them in all languages and
1717 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001718 if (isIncompatibleTypedef(Old, New))
1719 return;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001721 // The types match. Link up the redeclaration chain and merge attributes if
1722 // the old declaration was a typedef.
1723 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001724 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001725 mergeDeclAttributes(New, Old);
1726 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001727
David Blaikiebbafb8a2012-03-11 07:00:24 +00001728 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001729 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001730
David Blaikiebbafb8a2012-03-11 07:00:24 +00001731 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001732 // C++ [dcl.typedef]p2:
1733 // In a given non-class scope, a typedef specifier can be used to
1734 // redefine the name of any type declared in that scope to refer
1735 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001736 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001737 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001738
1739 // C++0x [dcl.typedef]p4:
1740 // In a given class scope, a typedef specifier can be used to redefine
1741 // any class-name declared in that scope that is not also a typedef-name
1742 // to refer to the type to which it already refers.
1743 //
1744 // This wording came in via DR424, which was a correction to the
1745 // wording in DR56, which accidentally banned code like:
1746 //
1747 // struct S {
1748 // typedef struct A { } A;
1749 // };
1750 //
1751 // in the C++03 standard. We implement the C++0x semantics, which
1752 // allow the above but disallow
1753 //
1754 // struct S {
1755 // typedef int I;
1756 // typedef int I;
1757 // };
1758 //
1759 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001760 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001761 return;
1762
Chris Lattner2581fc32009-04-17 22:04:20 +00001763 Diag(New->getLocation(), diag::err_redefinition)
1764 << New->getDeclName();
1765 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001766 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001767 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001768
Douglas Gregor7363fb02012-01-11 04:25:01 +00001769 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001770 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001771 return;
1772
Chris Lattner2581fc32009-04-17 22:04:20 +00001773 // If we have a redefinition of a typedef in C, emit a warning. This warning
1774 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001775 // -Wtypedef-redefinition. If either the original or the redefinition is
1776 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001777 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001778 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1779 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001780 return;
Mike Stump11289f42009-09-09 15:08:12 +00001781
Chris Lattner2581fc32009-04-17 22:04:20 +00001782 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1783 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001784 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001785 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001786}
1787
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001788/// DeclhasAttr - returns true if decl Declaration already has the target
1789/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001790static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001791 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001792 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001793 for (const auto *i : D->attrs())
1794 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001795 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001796 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001797 return true;
1798 continue;
1799 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001800 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001801 if (OA && isa<OwnershipAttr>(i))
1802 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001803 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001804 }
Chris Lattner84966392008-03-03 03:28:21 +00001805
1806 return false;
1807}
1808
Richard Smithbc8caaf2013-02-22 04:55:39 +00001809static bool isAttributeTargetADefinition(Decl *D) {
1810 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1811 return VD->isThisDeclarationADefinition();
1812 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1813 return TD->isCompleteDefinition() || TD->isBeingDefined();
1814 return true;
1815}
1816
1817/// Merge alignment attributes from \p Old to \p New, taking into account the
1818/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1819///
1820/// \return \c true if any attributes were added to \p New.
1821static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1822 // Look for alignas attributes on Old, and pick out whichever attribute
1823 // specifies the strictest alignment requirement.
1824 AlignedAttr *OldAlignasAttr = 0;
1825 AlignedAttr *OldStrictestAlignAttr = 0;
1826 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001827 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001828 // FIXME: We have no way of representing inherited dependent alignments
1829 // in a case like:
1830 // template<int A, int B> struct alignas(A) X;
1831 // template<int A, int B> struct alignas(B) X {};
1832 // For now, we just ignore any alignas attributes which are not on the
1833 // definition in such a case.
1834 if (I->isAlignmentDependent())
1835 return false;
1836
1837 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001838 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001839
1840 unsigned Align = I->getAlignment(S.Context);
1841 if (Align > OldAlign) {
1842 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001843 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001844 }
1845 }
1846
1847 // Look for alignas attributes on New.
1848 AlignedAttr *NewAlignasAttr = 0;
1849 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001850 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001851 if (I->isAlignmentDependent())
1852 return false;
1853
1854 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001855 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001856
1857 unsigned Align = I->getAlignment(S.Context);
1858 if (Align > NewAlign)
1859 NewAlign = Align;
1860 }
1861
1862 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1863 // Both declarations have 'alignas' attributes. We require them to match.
1864 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1865 // fall short. (If two declarations both have alignas, they must both match
1866 // every definition, and so must match each other if there is a definition.)
1867
1868 // If either declaration only contains 'alignas(0)' specifiers, then it
1869 // specifies the natural alignment for the type.
1870 if (OldAlign == 0 || NewAlign == 0) {
1871 QualType Ty;
1872 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1873 Ty = VD->getType();
1874 else
1875 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1876
1877 if (OldAlign == 0)
1878 OldAlign = S.Context.getTypeAlign(Ty);
1879 if (NewAlign == 0)
1880 NewAlign = S.Context.getTypeAlign(Ty);
1881 }
1882
1883 if (OldAlign != NewAlign) {
1884 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1885 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1886 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1887 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1888 }
1889 }
1890
1891 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1892 // C++11 [dcl.align]p6:
1893 // if any declaration of an entity has an alignment-specifier,
1894 // every defining declaration of that entity shall specify an
1895 // equivalent alignment.
1896 // C11 6.7.5/7:
1897 // If the definition of an object does not have an alignment
1898 // specifier, any other declaration of that object shall also
1899 // have no alignment specifier.
1900 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001901 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001902 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001903 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001904 }
1905
1906 bool AnyAdded = false;
1907
1908 // Ensure we have an attribute representing the strictest alignment.
1909 if (OldAlign > NewAlign) {
1910 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1911 Clone->setInherited(true);
1912 New->addAttr(Clone);
1913 AnyAdded = true;
1914 }
1915
1916 // Ensure we have an alignas attribute if the old declaration had one.
1917 if (OldAlignasAttr && !NewAlignasAttr &&
1918 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1919 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1920 Clone->setInherited(true);
1921 New->addAttr(Clone);
1922 AnyAdded = true;
1923 }
1924
1925 return AnyAdded;
1926}
1927
1928static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1929 bool Override) {
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001930 InheritableAttr *NewAttr = NULL;
Michael Han99315932013-01-24 16:46:58 +00001931 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Rafael Espindola19de5612013-01-12 06:42:30 +00001932 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001933 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1934 AA->getIntroduced(), AA->getDeprecated(),
1935 AA->getObsoleted(), AA->getUnavailable(),
1936 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001937 AttrSpellingListIndex);
Richard Smithbc8caaf2013-02-22 04:55:39 +00001938 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1939 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1940 AttrSpellingListIndex);
1941 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1942 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1943 AttrSpellingListIndex);
Rafael Espindola19de5612013-01-12 06:42:30 +00001944 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1946 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001947 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001948 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1949 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001950 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001951 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1952 FA->getFormatIdx(), FA->getFirstArg(),
1953 AttrSpellingListIndex);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001954 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001955 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1956 AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00001957 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00001958 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1959 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00001960 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00001961 else if (isa<AlignedAttr>(Attr))
1962 // AlignedAttrs are handled separately, because we need to handle all
1963 // such attributes on a declaration at the same time.
1964 NewAttr = 0;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001965 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001966 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00001967
Rafael Espindolae200f1c2012-05-13 03:25:18 +00001968 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00001969 NewAttr->setInherited(true);
1970 D->addAttr(NewAttr);
1971 return true;
1972 }
1973
1974 return false;
1975}
1976
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001977static const Decl *getDefinition(const Decl *D) {
1978 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00001979 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1981 const VarDecl *Def = VD->getDefinition();
1982 if (Def)
1983 return Def;
1984 return VD->getActingDefinition();
1985 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00001986 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00001987 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001988 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00001989 return Def;
1990 }
1991 return NULL;
1992}
1993
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001994static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001995 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001996 if (Attribute->getKind() == Kind)
1997 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00001998 return false;
1999}
2000
2001/// checkNewAttributesAfterDef - If we already have a definition, check that
2002/// there are no new attributes in this declaration.
2003static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2004 if (!New->hasAttrs())
2005 return;
2006
2007 const Decl *Def = getDefinition(Old);
2008 if (!Def || Def == New)
2009 return;
2010
2011 AttrVec &NewAttributes = New->getAttrs();
2012 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2013 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002014
2015 if (isa<AliasAttr>(NewAttribute)) {
2016 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2017 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2018 else {
2019 VarDecl *VD = cast<VarDecl>(New);
2020 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2021 VarDecl::TentativeDefinition
2022 ? diag::err_alias_after_tentative
2023 : diag::err_redefinition;
2024 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2025 S.Diag(Def->getLocation(), diag::note_previous_definition);
2026 VD->setInvalidDecl();
2027 }
2028 ++I;
2029 continue;
2030 }
2031
2032 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2033 // Tentative definitions are only interesting for the alias check above.
2034 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2035 ++I;
2036 continue;
2037 }
2038 }
2039
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002040 if (hasAttribute(Def, NewAttribute->getKind())) {
2041 ++I;
2042 continue; // regular attr merging will take care of validating this.
2043 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002044
Richard Smithdebc59d2013-01-30 05:45:05 +00002045 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002046 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002047 ++I;
2048 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002049 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2050 if (AA->isAlignas()) {
2051 // C++11 [dcl.align]p6:
2052 // if any declaration of an entity has an alignment-specifier,
2053 // every defining declaration of that entity shall specify an
2054 // equivalent alignment.
2055 // C11 6.7.5/7:
2056 // If the definition of an object does not have an alignment
2057 // specifier, any other declaration of that object shall also
2058 // have no alignment specifier.
2059 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002060 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002061 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002062 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002063 NewAttributes.erase(NewAttributes.begin() + I);
2064 --E;
2065 continue;
2066 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002067 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002068
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002069 S.Diag(NewAttribute->getLocation(),
2070 diag::warn_attribute_precede_definition);
2071 S.Diag(Def->getLocation(), diag::note_previous_definition);
2072 NewAttributes.erase(NewAttributes.begin() + I);
2073 --E;
2074 }
2075}
2076
John McCallf79e87d2011-03-02 04:00:57 +00002077/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002078void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002079 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2081 UsedAttr *NewAttr = OldAttr->clone(Context);
2082 NewAttr->setInherited(true);
2083 New->addAttr(NewAttr);
2084 }
2085
Richard Smithe233fbf2013-01-28 22:42:45 +00002086 if (!Old->hasAttrs() && !New->hasAttrs())
2087 return;
2088
Rafael Espindola36191042012-05-18 01:47:00 +00002089 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002090 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002091
Douglas Gregor32c17572012-01-01 20:30:41 +00002092 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002093 return;
John McCallf79e87d2011-03-02 04:00:57 +00002094
Douglas Gregor32c17572012-01-01 20:30:41 +00002095 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002096
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002097 // Ensure that any moving of objects within the allocated map is done before
2098 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002099 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002100
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002101 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002102 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002103 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002104 if (isa<DeprecatedAttr>(I) ||
2105 isa<UnavailableAttr>(I) ||
2106 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002107 switch (AMK) {
2108 case AMK_None:
2109 continue;
John McCalld2930c22011-07-22 02:45:48 +00002110
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002111 case AMK_Redeclaration:
2112 break;
2113
2114 case AMK_Override:
2115 Override = true;
2116 break;
2117 }
2118 }
2119
Rafael Espindolab0938852013-10-25 01:28:12 +00002120 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002121 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002122 continue;
2123
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002124 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002125 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002126 }
John McCallf79e87d2011-03-02 04:00:57 +00002127
Richard Smithbc8caaf2013-02-22 04:55:39 +00002128 if (mergeAlignedAttrs(*this, New, Old))
2129 foundAny = true;
2130
Douglas Gregor32c17572012-01-01 20:30:41 +00002131 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002132}
2133
2134/// mergeParamDeclAttributes - Copy attributes from the old parameter
2135/// to the new one.
2136static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2137 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002138 Sema &S) {
2139 // C++11 [dcl.attr.depend]p2:
2140 // The first declaration of a function shall specify the
2141 // carries_dependency attribute for its declarator-id if any declaration
2142 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002143 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2144 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2145 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002146 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2147 // Find the first declaration of the parameter.
2148 // FIXME: Should we build redeclaration chains for function parameters?
2149 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002150 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002151 const ParmVarDecl *FirstVD =
2152 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2153 S.Diag(FirstVD->getLocation(),
2154 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2155 }
2156
John McCallf79e87d2011-03-02 04:00:57 +00002157 if (!oldDecl->hasAttrs())
2158 return;
2159
2160 bool foundAny = newDecl->hasAttrs();
2161
2162 // Ensure that any moving of objects within the allocated map is
2163 // done before we process them.
2164 if (!foundAny) newDecl->setAttrs(AttrVec());
2165
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002166 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2167 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002168 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002169 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002170 newAttr->setInherited(true);
2171 newDecl->addAttr(newAttr);
2172 foundAny = true;
2173 }
2174 }
2175
2176 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002177}
2178
Dan Gohman28ade552010-07-26 21:25:24 +00002179namespace {
2180
Douglas Gregora74a2972009-03-06 22:43:54 +00002181/// Used in MergeFunctionDecl to keep track of function parameters in
2182/// C.
2183struct GNUCompatibleParamWarning {
2184 ParmVarDecl *OldParm;
2185 ParmVarDecl *NewParm;
2186 QualType PromotedType;
2187};
2188
Dan Gohman28ade552010-07-26 21:25:24 +00002189}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002190
2191/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002192Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002193 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002194 if (Ctor->isDefaultConstructor())
2195 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002196
2197 if (Ctor->isCopyConstructor())
2198 return Sema::CXXCopyConstructor;
2199
2200 if (Ctor->isMoveConstructor())
2201 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002202 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002203 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002204 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002205 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002206 } else if (MD->isMoveAssignmentOperator()) {
2207 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002208 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002209
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002210 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002211}
2212
Sebastian Redl243d9052010-06-09 21:17:41 +00002213/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002214/// only extern inline functions can be redefined, and even then only in
2215/// GNU89 mode.
2216static bool canRedefineFunction(const FunctionDecl *FD,
2217 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002218 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2219 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002220 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002221 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002222}
2223
Reid Kleckner78af0702013-08-27 23:08:25 +00002224const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2225 const AttributedType *AT = T->getAs<AttributedType>();
2226 while (AT && !AT->isCallingConv())
2227 AT = AT->getModifiedType()->getAs<AttributedType>();
2228 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002229}
2230
Benjamin Kramer3e350262013-02-15 12:30:38 +00002231template <typename T>
2232static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002233 const DeclContext *DC = Old->getDeclContext();
2234 if (DC->isRecord())
2235 return false;
2236
2237 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002238 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002239 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002240 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002241 return true;
2242 return false;
2243}
2244
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002245/// MergeFunctionDecl - We just parsed a function 'New' from
2246/// declarator D which has the same name and scope as a previous
2247/// declaration 'Old'. Figure out how to resolve this situation,
2248/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002249///
2250/// In C++, New and Old must be declarations that are not
2251/// overloaded. Use IsOverload to determine whether New and Old are
2252/// overloaded, and to select the Old declaration that New should be
2253/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002254///
2255/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002256bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2257 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002258 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002259 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002260 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002261 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002262 if (New->getFriendObjectKind()) {
2263 Diag(New->getLocation(), diag::err_using_decl_friend);
2264 Diag(Shadow->getTargetDecl()->getLocation(),
2265 diag::note_using_decl_target);
2266 Diag(Shadow->getUsingDecl()->getLocation(),
2267 diag::note_using_decl) << 0;
2268 return true;
2269 }
2270
Richard Smith18819302014-02-06 01:31:33 +00002271 // C++11 [namespace.udecl]p14:
2272 // If a function declaration in namespace scope or block scope has the
2273 // same name and the same parameter-type-list as a function introduced
2274 // by a using-declaration, and the declarations do not declare the same
2275 // function, the program is ill-formed.
2276
2277 // Check whether the two declarations might declare the same function.
2278 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2279 if (Old &&
2280 !Old->getDeclContext()->getRedeclContext()->Equals(
2281 New->getDeclContext()->getRedeclContext()) &&
2282 !(Old->isExternC() && New->isExternC()))
2283 Old = 0;
2284
2285 if (!Old) {
2286 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2287 Diag(Shadow->getTargetDecl()->getLocation(),
2288 diag::note_using_decl_target);
2289 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2290 return true;
2291 }
2292 OldD = Old;
2293 } else {
2294 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2295 << New->getDeclName();
2296 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002297 return true;
2298 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002300
David Majnemerea5092a2013-07-07 23:49:50 +00002301 // If the old declaration is invalid, just give up here.
2302 if (Old->isInvalidDecl())
2303 return true;
2304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002305 // Determine whether the previous declaration was a definition,
2306 // implicit declaration, or a declaration.
2307 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002308 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002309 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002310 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002311 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002312 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002313 if (OldLocation.isInvalid())
2314 OldLocation = New->getLocation();
2315 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002316 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Charles Davisfea48452010-02-18 02:00:42 +00002318 // Don't complain about this if we're in GNU89 mode and the old function
2319 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002320 // Don't complain about specializations. They are not supposed to have
2321 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002322 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002323 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002324 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002325 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002326 !canRedefineFunction(Old, getLangOpts())) {
2327 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002328 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002329 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002330 } else {
2331 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002332 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002333 return true;
2334 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002335 }
2336
Reid Kleckner78af0702013-08-27 23:08:25 +00002337
2338 // If a function is first declared with a calling convention, but is later
2339 // declared or defined without one, all following decls assume the calling
2340 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002341 //
John McCalla5f46fb2012-08-25 02:00:03 +00002342 // It's OK if a function is first declared without a calling convention,
2343 // but is later declared or defined with the default calling convention.
2344 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002345 // To test if either decl has an explicit calling convention, we look for
2346 // AttributedType sugar nodes on the type as written. If they are missing or
2347 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002348 //
2349 // Note also that we DO NOT return at this point, because we still have
2350 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002351 QualType OldQType = Context.getCanonicalType(Old->getType());
2352 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002353 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002354 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002355 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2356 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2357 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002358
Reid Kleckner78af0702013-08-27 23:08:25 +00002359 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002360 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002361 const FunctionType *FT =
2362 First->getType().getCanonicalType()->castAs<FunctionType>();
2363 FunctionType::ExtInfo FI = FT->getExtInfo();
2364 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2365 if (!NewCCExplicit) {
2366 // Inherit the CC from the previous declaration if it was specified
2367 // there but not here.
2368 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2369 RequiresAdjustment = true;
2370 } else {
2371 // Calling conventions aren't compatible, so complain.
2372 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2373 Diag(New->getLocation(), diag::err_cconv_change)
2374 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2375 << !FirstCCExplicit
2376 << (!FirstCCExplicit ? "" :
2377 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002378
Reid Kleckner78af0702013-08-27 23:08:25 +00002379 // Put the note on the first decl, since it is the one that matters.
2380 Diag(First->getLocation(), diag::note_previous_declaration);
2381 return true;
2382 }
John McCallcddbad02010-02-04 05:44:44 +00002383 }
2384
John McCallab26cfa2010-02-05 21:31:56 +00002385 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002386 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2387 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2388 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002389 }
2390
Douglas Gregor77e274f2010-06-18 21:30:25 +00002391 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002392 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2393 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2394 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002395 Diag(New->getLocation(), diag::err_regparm_mismatch)
2396 << NewType->getRegParmType()
2397 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002398 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002399 return true;
2400 }
John McCall4f5019e2010-12-19 02:44:49 +00002401
2402 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2403 RequiresAdjustment = true;
2404 }
2405
Douglas Gregorf1404d72011-10-14 15:55:40 +00002406 // Merge ns_returns_retained attribute.
2407 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2408 if (NewTypeInfo.getProducesResult()) {
2409 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002410 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002411 return true;
2412 }
2413
2414 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2415 RequiresAdjustment = true;
2416 }
2417
John McCall4f5019e2010-12-19 02:44:49 +00002418 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002419 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2420 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2421 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002422 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002423 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002424 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002425
2426 // If this redeclaration makes the function inline, we may need to add it to
2427 // UndefinedButUsed.
2428 if (!Old->isInlined() && New->isInlined() &&
2429 !New->hasAttr<GNUInlineAttr>() &&
2430 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2431 Old->isUsed(false) &&
2432 !Old->isDefined() && !New->isThisDeclarationADefinition())
2433 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2434 SourceLocation()));
2435
2436 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2437 // about it.
2438 if (New->hasAttr<GNUInlineAttr>() &&
2439 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2440 UndefinedButUsed.erase(Old->getCanonicalDecl());
2441 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002442
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002444 // (C++98 13.1p2):
2445 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002446 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002448
2449 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002450 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002451 // Redeclarations or specializations of a function or function template
2452 // with a declared return type that uses a placeholder type shall also
2453 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002454 QualType OldDeclaredReturnType =
2455 (Old->getTypeSourceInfo()
2456 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2457 : OldType)->getReturnType();
2458 QualType NewDeclaredReturnType =
2459 (New->getTypeSourceInfo()
2460 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2461 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002462 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002463 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2464 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2465 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002466 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2467 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002468 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2469 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002470 if (New->isCXXClassMember() && New->isOutOfLine())
2471 Diag(New->getLocation(),
2472 diag::err_member_def_does_not_match_ret_type) << New;
2473 else
2474 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002475 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002476 return true;
2477 }
2478 else
2479 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002480 }
2481
Alp Toker314cc812014-01-25 16:55:45 +00002482 QualType OldReturnType = OldType->getReturnType();
2483 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002484 if (OldReturnType != NewReturnType) {
2485 // If this function has a deduced return type and has already been
2486 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002487 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002488 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002489 New->setType(
2490 SubstAutoType(New->getType(),
2491 OldAT->isDependentType() ? Context.DependentTy
2492 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002493 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002494 SubstAutoType(NewQType,
2495 OldAT->isDependentType() ? Context.DependentTy
2496 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002497 }
2498 }
2499
2500 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2501 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002502 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002503 // Preserve triviality.
2504 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002505
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002506 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002507 // 2 CXXMethodDecls referring to the same function will be injected.
2508 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002509 bool IsClassScopeExplicitSpecialization =
2510 OldMethod->isFunctionTemplateSpecialization() &&
2511 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002512 bool isFriend = NewMethod->getFriendObjectKind();
2513
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002514 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2515 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002516 // -- Member function declarations with the same name and the
2517 // same parameter types cannot be overloaded if any of them
2518 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002519 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002520 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002521 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002522 return true;
2523 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002524
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002525 // C++ [class.mem]p1:
2526 // [...] A member shall not be declared twice in the
2527 // member-specification, except that a nested class or member
2528 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002529 if (ActiveTemplateInstantiations.empty()) {
2530 unsigned NewDiag;
2531 if (isa<CXXConstructorDecl>(OldMethod))
2532 NewDiag = diag::err_constructor_redeclared;
2533 else if (isa<CXXDestructorDecl>(NewMethod))
2534 NewDiag = diag::err_destructor_redeclared;
2535 else if (isa<CXXConversionDecl>(NewMethod))
2536 NewDiag = diag::err_conv_function_redeclared;
2537 else
2538 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002539
Richard Smith57e7ff92012-07-13 04:12:04 +00002540 Diag(New->getLocation(), NewDiag);
2541 } else {
2542 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2543 << New << New->getType();
2544 }
Richard Smithbdd14642014-02-04 01:14:30 +00002545 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002546
2547 // Complain if this is an explicit declaration of a special
2548 // member that was initially declared implicitly.
2549 //
2550 // As an exception, it's okay to befriend such methods in order
2551 // to permit the implicit constructor/destructor/operator calls.
2552 } else if (OldMethod->isImplicit()) {
2553 if (isFriend) {
2554 NewMethod->setImplicit();
2555 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002556 Diag(NewMethod->getLocation(),
2557 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002558 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002559 return true;
2560 }
Richard Smith337a5a12012-06-08 01:30:54 +00002561 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002562 Diag(NewMethod->getLocation(),
2563 diag::err_definition_of_explicitly_defaulted_member)
2564 << getSpecialMember(OldMethod);
2565 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002566 }
2567 }
2568
Richard Smith10876ef2013-01-17 01:30:42 +00002569 // C++11 [dcl.attr.noreturn]p1:
2570 // The first declaration of a function shall specify the noreturn
2571 // attribute if any declaration of that function specifies the noreturn
2572 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002573 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2574 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2575 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002576 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002577 diag::note_noreturn_missing_first_decl);
2578 }
2579
Richard Smithe233fbf2013-01-28 22:42:45 +00002580 // C++11 [dcl.attr.depend]p2:
2581 // The first declaration of a function shall specify the
2582 // carries_dependency attribute for its declarator-id if any declaration
2583 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002584 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2585 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2586 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002587 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002588 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002589 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2590 }
2591
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002592 // (C++98 8.3.5p3):
2593 // All declarations for a function shall agree exactly in both the
2594 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002595 // We also want to respect all the extended bits except noreturn.
2596
2597 // noreturn should now match unless the old type info didn't have it.
2598 QualType OldQTypeForComparison = OldQType;
2599 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2600 assert(OldQType == QualType(OldType, 0));
2601 const FunctionType *OldTypeForComparison
2602 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2603 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2604 assert(OldQTypeForComparison.isCanonical());
2605 }
2606
Rafael Espindolaf4187652013-02-14 01:18:37 +00002607 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002608 // As a special case, retain the language linkage from previous
2609 // declarations of a friend function as an extension.
2610 //
2611 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2612 // and is useful because there's otherwise no way to specify language
2613 // linkage within class scope.
2614 //
2615 // Check cautiously as the friend object kind isn't yet complete.
2616 if (New->getFriendObjectKind() != Decl::FOK_None) {
2617 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002618 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002619 } else {
2620 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002621 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002622 return true;
2623 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002624 }
2625
John McCall4f5019e2010-12-19 02:44:49 +00002626 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002627 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002628
Richard Smith541b38b2013-09-20 01:15:31 +00002629 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2630 New->isLocalExternDecl()) {
2631 // It's OK if we couldn't merge types for a local function declaraton
2632 // if either the old or new type is dependent. We'll merge the types
2633 // when we instantiate the function.
2634 return false;
2635 }
2636
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002637 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002638 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002639
2640 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002641 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002642 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002643 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002644 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2645 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002646 const FunctionProtoType *OldProto = 0;
Richard Smith1c34fb72013-08-13 18:18:50 +00002647 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002648 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002649 // The old declaration provided a function prototype, but the
2650 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002651 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Alp Toker9cacbab2014-01-20 20:26:09 +00002652 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2653 OldProto->param_type_end());
Alp Toker314cc812014-01-25 16:55:45 +00002654 NewQType =
2655 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2656 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002657 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002658 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002659
2660 // Synthesize a parameter for each argument type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002661 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00002662 for (FunctionProtoType::param_type_iterator
2663 ParamType = OldProto->param_type_begin(),
2664 ParamEnd = OldProto->param_type_end();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002665 ParamType != ParamEnd; ++ParamType) {
2666 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002667 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002668 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002669 *ParamType, /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002670 SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002671 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00002672 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002673 Param->setImplicit();
2674 Params.push_back(Param);
2675 }
2676
David Blaikie9c70e042011-09-21 18:16:56 +00002677 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002678 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002679
Richard Smith1c34fb72013-08-13 18:18:50 +00002680 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002681 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002682
Douglas Gregora74a2972009-03-06 22:43:54 +00002683 // GNU C permits a K&R definition to follow a prototype declaration
2684 // if the declared types of the parameters in the K&R definition
2685 // match the types in the prototype declaration, even when the
2686 // promoted types of the parameters from the K&R definition differ
2687 // from the types in the prototype. GCC then keeps the types from
2688 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002689 //
2690 // If a variadic prototype is followed by a non-variadic K&R definition,
2691 // the K&R definition becomes variadic. This is sort of an edge case, but
2692 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2693 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002694 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002695 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002696 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002697 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002698 SmallVector<QualType, 16> ArgTypes;
2699 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002700 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002701 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002702 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002703 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002704
Douglas Gregora74a2972009-03-06 22:43:54 +00002705 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002706 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2707 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002708 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002709 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002710 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002711 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2712 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002713 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002714 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002715 ArgTypes.push_back(NewParm->getType());
2716 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002717 NewParm->getType(),
2718 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002719 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2720 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002721 Warnings.push_back(Warn);
2722 ArgTypes.push_back(NewParm->getType());
2723 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002724 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002725 }
2726
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002727 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002728 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2729 Diag(Warnings[Warn].NewParm->getLocation(),
2730 diag::ext_param_promoted_not_compatible_with_prototype)
2731 << Warnings[Warn].PromotedType
2732 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002733 if (Warnings[Warn].OldParm->getLocation().isValid())
2734 Diag(Warnings[Warn].OldParm->getLocation(),
2735 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002736 }
2737
Richard Smith1c34fb72013-08-13 18:18:50 +00002738 if (MergeTypeWithOld)
2739 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2740 OldProto->getExtProtoInfo()));
2741 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 }
2743
2744 // Fall through to diagnose conflicting types.
2745 }
2746
John McCallad327cd2013-04-14 08:50:55 +00002747 // A function that has already been declared has been redeclared or
2748 // defined with a different type; show an appropriate diagnostic.
2749
2750 // If the previous declaration was an implicitly-generated builtin
2751 // declaration, then at the very least we should use a specialized note.
2752 unsigned BuiltinID;
2753 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2754 // If it's actually a library-defined builtin function like 'malloc'
2755 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002756 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002757 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002758 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002759 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002760
2761 // If this is a global redeclaration, just forget hereafter
2762 // about the "builtin-ness" of the function.
2763 //
2764 // Doing this for local extern declarations is problematic. If
2765 // the builtin declaration remains visible, a second invalid
2766 // local declaration will produce a hard error; if it doesn't
2767 // remain visible, a single bogus local redeclaration (which is
2768 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002769 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002770 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2771
Douglas Gregor893c2c92009-03-23 17:47:24 +00002772 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002773 }
Steve Naroff17832a42008-01-16 15:01:34 +00002774
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002775 PrevDiag = diag::note_previous_builtin_declaration;
2776 }
2777
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002778 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002779 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002780 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002781}
2782
Douglas Gregore62c0a42009-02-24 01:23:02 +00002783/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002784/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002785///
2786/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002787/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002788/// the new declaration, once we know that New is in fact a
2789/// redeclaration of Old.
2790///
2791/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002792bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002793 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002794 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002795 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002796
Douglas Gregore62c0a42009-02-24 01:23:02 +00002797 // Merge "pure" flag.
2798 if (Old->isPure())
2799 New->setPure();
2800
Rafael Espindolabefe1302012-11-25 14:07:59 +00002801 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002802 if (Old->getMostRecentDecl()->isUsed(false))
2803 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002804
John McCallf79e87d2011-03-02 04:00:57 +00002805 // Merge attributes from the parameters. These can mismatch with K&R
2806 // declarations.
2807 if (New->getNumParams() == Old->getNumParams())
2808 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2809 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002810 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002811
David Blaikiebbafb8a2012-03-11 07:00:24 +00002812 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002813 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002814
Rafael Espindola8778c282012-11-29 16:09:03 +00002815 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002816 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2817 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002818 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002819 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002820 New->setType(Merged);
2821
Douglas Gregore62c0a42009-02-24 01:23:02 +00002822 return false;
2823}
2824
John McCall31168b02011-06-15 23:02:42 +00002825
John McCallf79e87d2011-03-02 04:00:57 +00002826void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002827 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002828
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002829 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002830 AvailabilityMergeKind MergeKind =
2831 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2832 : AMK_Override;
2833 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002834
2835 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002836 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2837 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002838 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002839 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002840 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002841 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002842
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002843 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002844}
2845
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002846/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2847/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002848/// emitting diagnostics as appropriate.
2849///
2850/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002851/// to here in AddInitializerToDecl. We can't check them before the initializer
2852/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002853void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2854 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002855 if (New->isInvalidDecl() || Old->isInvalidDecl())
2856 return;
2857
2858 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002860 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002861 // We don't know what the new type is until the initializer is attached.
2862 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002863 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2864 // These could still be something that needs exception specs checked.
2865 return MergeVarDeclExceptionSpecs(New, Old);
2866 }
Richard Smith30482bc2011-02-20 03:19:35 +00002867 // C++ [basic.link]p10:
2868 // [...] the types specified by all declarations referring to a given
2869 // object or function shall be identical, except that declarations for an
2870 // array object can specify array types that differ by the presence or
2871 // absence of a major array bound (8.3.4).
2872 else if (Old->getType()->isIncompleteArrayType() &&
2873 New->getType()->isArrayType()) {
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 = New->getType();
2879 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002880 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2882 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2883 if (Context.hasSameType(OldArray->getElementType(),
2884 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002885 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002886 } else if (New->getType()->isObjCObjectPointerType() &&
2887 Old->getType()->isObjCObjectPointerType()) {
2888 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2889 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002890 }
2891 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002892 // C 6.2.7p2:
2893 // All declarations that refer to the same object or function shall have
2894 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002895 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2896 }
2897 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002898 // It's OK if we couldn't merge types if either type is dependent, for a
2899 // block-scope variable. In other cases (static data members of class
2900 // templates, variable templates, ...), we require the types to be
2901 // equivalent.
2902 // FIXME: The C++ standard doesn't say anything about this.
2903 if ((New->getType()->isDependentType() ||
2904 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2905 // If the old type was dependent, we can't merge with it, so the new type
2906 // becomes dependent for now. We'll reproduce the original type when we
2907 // instantiate the TypeSourceInfo for the variable.
2908 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2909 New->setType(Context.DependentTy);
2910 return;
2911 }
2912
2913 // FIXME: Even if this merging succeeds, some other non-visible declaration
2914 // of this variable might have an incompatible type. For instance:
2915 //
2916 // extern int arr[];
2917 // void f() { extern int arr[2]; }
2918 // void g() { extern int arr[3]; }
2919 //
2920 // Neither C nor C++ requires a diagnostic for this, but we should still try
2921 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002922 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002923 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002924 Diag(Old->getLocation(), diag::note_previous_definition);
2925 return New->setInvalidDecl();
2926 }
John McCallb65e8fe2013-04-01 18:34:28 +00002927
2928 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002929 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002930 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002931 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002932}
2933
Richard Smith3c785782013-09-03 21:00:58 +00002934static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2935 LookupResult &Previous) {
2936 // C11 6.2.7p4:
2937 // For an identifier with internal or external linkage declared
2938 // in a scope in which a prior declaration of that identifier is
2939 // visible, if the prior declaration specifies internal or
2940 // external linkage, the type of the identifier at the later
2941 // declaration becomes the composite type.
2942 //
2943 // If the variable isn't visible, we do not merge with its type.
2944 if (Previous.isShadowed())
2945 return false;
2946
2947 if (S.getLangOpts().CPlusPlus) {
2948 // C++11 [dcl.array]p3:
2949 // If there is a preceding declaration of the entity in the same
2950 // scope in which the bound was specified, an omitted array bound
2951 // is taken to be the same as in that earlier declaration.
2952 return NewVD->isPreviousDeclInSameBlockScope() ||
2953 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2954 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2955 } else {
2956 // If the old declaration was function-local, don't merge with its
2957 // type unless we're in the same function.
2958 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2959 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2960 }
2961}
2962
Chris Lattner01564d92007-01-27 19:27:06 +00002963/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2964/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2965/// situation, merging decls or emitting diagnostics as appropriate.
2966///
Mike Stump11289f42009-09-09 15:08:12 +00002967/// Tentative definition rules (C99 6.9.2p2) are checked by
2968/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002969/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002970///
Richard Smith3c785782013-09-03 21:00:58 +00002971void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00002972 // If the new decl is already invalid, don't do any other checking.
2973 if (New->isInvalidDecl())
2974 return;
Mike Stump11289f42009-09-09 15:08:12 +00002975
Richard Smithbeef3452014-01-16 23:39:20 +00002976 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2977
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002978 // Verify the old decl was also a variable or variable template.
John McCall1f82f242009-11-18 22:49:29 +00002979 VarDecl *Old = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00002980 VarTemplateDecl *OldTemplate = 0;
2981 if (Previous.isSingleResult()) {
2982 if (NewTemplate) {
2983 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2984 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2985 } else
2986 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00002987 }
2988 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002989 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002990 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002991 Diag(Previous.getRepresentativeDecl()->getLocation(),
2992 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002993 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002994 }
Chris Lattner84966392008-03-03 03:28:21 +00002995
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00002996 if (!shouldLinkPossiblyHiddenDecl(Old, New))
2997 return;
2998
Richard Smithbeef3452014-01-16 23:39:20 +00002999 // Ensure the template parameters are compatible.
3000 if (NewTemplate &&
3001 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3002 OldTemplate->getTemplateParameters(),
3003 /*Complain=*/true, TPL_TemplateMatch))
3004 return;
3005
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003006 // C++ [class.mem]p1:
3007 // A member shall not be declared twice in the member-specification [...]
3008 //
3009 // Here, we need only consider static data members.
3010 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3011 Diag(New->getLocation(), diag::err_duplicate_member)
3012 << New->getIdentifier();
3013 Diag(Old->getLocation(), diag::note_previous_declaration);
3014 New->setInvalidDecl();
3015 }
3016
Douglas Gregor32c17572012-01-01 20:30:41 +00003017 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003018 // Warn if an already-declared variable is made a weak_import in a subsequent
3019 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003020 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003021 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003022 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003023 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3024 Diag(Old->getLocation(), diag::note_previous_definition);
3025 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003026 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003027 }
Chris Lattner84966392008-03-03 03:28:21 +00003028
Richard Smith30482bc2011-02-20 03:19:35 +00003029 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003030 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3031
Richard Smith30482bc2011-02-20 03:19:35 +00003032 if (New->isInvalidDecl())
3033 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003034
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003035 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003036 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003037 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003038 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003039 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003040 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003041 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003044 // For an identifier declared with the storage-class specifier
3045 // extern in a scope in which a prior declaration of that
3046 // identifier is visible,23) if the prior declaration specifies
3047 // internal or external linkage, the linkage of the identifier at
3048 // the later declaration is the same as the linkage specified at
3049 // the prior declaration. If no prior declaration is visible, or
3050 // if the prior declaration specifies no linkage, then the
3051 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003052 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003053 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003054 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003055 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003056 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003057 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003058 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003059 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003060 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003061
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003062 // Check if extern is followed by non-extern and vice-versa.
3063 if (New->hasExternalStorage() &&
3064 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3065 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3066 Diag(Old->getLocation(), diag::note_previous_definition);
3067 return New->setInvalidDecl();
3068 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003069 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3070 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003071 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3072 Diag(Old->getLocation(), diag::note_previous_definition);
3073 return New->setInvalidDecl();
3074 }
3075
Steve Naroffa5629372008-09-17 14:05:40 +00003076 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003077
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003078 // FIXME: The test for external storage here seems wrong? We still
3079 // need to check for mismatches.
3080 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003081 // Don't complain about out-of-line definitions of static members.
3082 !(Old->getLexicalDeclContext()->isRecord() &&
3083 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003084 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003085 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003086 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003087 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003088
Richard Smithfd3834f2013-04-13 02:43:54 +00003089 if (New->getTLSKind() != Old->getTLSKind()) {
3090 if (!Old->getTLSKind()) {
3091 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3092 Diag(Old->getLocation(), diag::note_previous_declaration);
3093 } else if (!New->getTLSKind()) {
3094 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3095 Diag(Old->getLocation(), diag::note_previous_declaration);
3096 } else {
3097 // Do not allow redeclaration to change the variable between requiring
3098 // static and dynamic initialization.
3099 // FIXME: GCC allows this, but uses the TLS keyword on the first
3100 // declaration to determine the kind. Do we need to be compatible here?
3101 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3102 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3103 Diag(Old->getLocation(), diag::note_previous_declaration);
3104 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003105 }
3106
Sebastian Redlf1842912010-02-02 18:35:11 +00003107 // C++ doesn't have tentative definitions, so go right ahead and check here.
3108 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003109 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003110 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003111 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003112 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003113 Diag(Def->getLocation(), diag::note_previous_definition);
3114 New->setInvalidDecl();
3115 return;
3116 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003117
Rafael Espindolaf4187652013-02-14 01:18:37 +00003118 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003119 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3120 Diag(Old->getLocation(), diag::note_previous_definition);
3121 New->setInvalidDecl();
3122 return;
3123 }
3124
Rafael Espindolabefe1302012-11-25 14:07:59 +00003125 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003126 if (Old->getMostRecentDecl()->isUsed(false))
3127 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003128
Douglas Gregor0760fa12009-03-10 23:43:53 +00003129 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003130 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003131 if (NewTemplate)
3132 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003133
3134 // Inherit access appropriately.
3135 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003136 if (NewTemplate)
3137 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003138}
3139
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003140/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3141/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003142Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003143 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003144 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003145}
3146
David Majnemer2206bf52014-03-05 08:57:59 +00003147static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003148 if (!S.Context.getLangOpts().CPlusPlus)
3149 return;
3150
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003151 if (isa<CXXRecordDecl>(Tag->getParent())) {
3152 // If this tag is the direct child of a class, number it if
3153 // it is anonymous.
3154 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3155 return;
3156 MangleNumberingContext &MCtx =
3157 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003158 S.Context.setManglingNumber(
3159 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003160 return;
3161 }
3162
3163 // If this tag isn't a direct child of a class, number it if it is local.
3164 Decl *ManglingContextDecl;
3165 if (MangleNumberingContext *MCtx =
3166 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3167 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003168 S.Context.setManglingNumber(
3169 Tag,
3170 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003171 }
3172}
3173
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003174/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003175/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003176/// parameters to cope with template friend declarations.
3177Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3178 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003179 MultiTemplateParamsArg TemplateParams,
3180 bool IsExplicitInstantiation) {
John McCallc3987482009-10-07 23:34:25 +00003181 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003182 TagDecl *Tag = 0;
3183 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3184 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003185 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003186 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003187 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003188 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003189
3190 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00003191 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003192
John McCall07e91c02009-08-06 02:15:43 +00003193 // Note that the above type specs guarantee that the
3194 // type rep is a Decl, whereas in many of the others
3195 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003196 if (isa<TagDecl>(TagD))
3197 Tag = cast<TagDecl>(TagD);
3198 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3199 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003200 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003201
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003202 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003203 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003204 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003205 if (Tag->isInvalidDecl())
3206 return Tag;
3207 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003208
Nuno Lopese9823fa2009-12-17 11:35:26 +00003209 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3210 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3211 // or incomplete types shall not be restrict-qualified."
3212 if (TypeQuals & DeclSpec::TQ_restrict)
3213 Diag(DS.getRestrictSpecLoc(),
3214 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3215 << DS.getSourceRange();
3216 }
3217
Richard Smitha77a0a62011-08-15 21:04:07 +00003218 if (DS.isConstexprSpecified()) {
3219 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3220 // and definitions of functions and variables.
3221 if (Tag)
3222 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3223 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3224 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003225 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3226 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003227 else
3228 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3229 // Don't emit warnings after this error.
3230 return TagD;
3231 }
3232
Richard Smithb1402ae2013-03-18 22:52:47 +00003233 DiagnoseFunctionSpecifiers(DS);
3234
Douglas Gregor3dad8422009-09-26 06:47:28 +00003235 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003236 // If we're dealing with a decl but not a TagDecl, assume that
3237 // whatever routines created it handled the friendship aspect.
3238 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00003239 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003240 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003241 }
John McCallaa017372011-03-22 23:00:04 +00003242
Richard Smithb1402ae2013-03-18 22:52:47 +00003243 CXXScopeSpec &SS = DS.getTypeSpecScope();
3244 bool IsExplicitSpecialization =
3245 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3246 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3247 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3248 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3249 // nested-name-specifier unless it is an explicit instantiation
3250 // or an explicit specialization.
3251 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3252 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3253 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3254 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3255 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3256 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3257 << SS.getRange();
3258 return 0;
3259 }
3260
3261 // Track whether this decl-specifier declares anything.
3262 bool DeclaresAnything = true;
3263
3264 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003265 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003266 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003267 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003268 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003269 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003270 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003271
Richard Smithb1402ae2013-03-18 22:52:47 +00003272 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003273 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003274 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003275
Richard Smithb1402ae2013-03-18 22:52:47 +00003276 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003277 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003278 CurContext->isRecord() &&
3279 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3280 // Handle 2 kinds of anonymous struct:
3281 // struct STRUCT;
3282 // and
3283 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3284 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003285 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003286 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3287 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003288 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003289 << DS.getSourceRange();
3290 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3291 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003292 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003293
3294 // Skip all the checks below if we have a type error.
3295 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3296 (TagD && TagD->isInvalidDecl()))
3297 return TagD;
3298
3299 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003300 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3301 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3302 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003303 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3304 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003305
John McCallaa017372011-03-22 23:00:04 +00003306 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003307 // Customize diagnostic for a typedef missing a name.
3308 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003309 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003310 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003311 else
3312 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003313 }
Mike Stump11289f42009-09-09 15:08:12 +00003314
Richard Smithb1402ae2013-03-18 22:52:47 +00003315 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003316 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3317 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3318 << Tag->getTagKind()
3319 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3320
Richard Smithb1402ae2013-03-18 22:52:47 +00003321 ActOnDocumentableDecl(TagD);
3322
3323 // C 6.7/2:
3324 // A declaration [...] shall declare at least a declarator [...], a tag,
3325 // or the members of an enumeration.
3326 // C++ [dcl.dcl]p3:
3327 // [If there are no declarators], and except for the declaration of an
3328 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3329 // names into the program, or shall redeclare a name introduced by a
3330 // previous declaration.
3331 if (!DeclaresAnything) {
3332 // In C, we allow this as a (popular) extension / bug. Don't bother
3333 // producing further diagnostics for redundant qualifiers after this.
3334 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3335 return TagD;
3336 }
3337
3338 // C++ [dcl.stc]p1:
3339 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3340 // init-declarator-list of the declaration shall not be empty.
3341 // C++ [dcl.fct.spec]p1:
3342 // If a cv-qualifier appears in a decl-specifier-seq, the
3343 // init-declarator-list of the declaration shall not be empty.
3344 //
3345 // Spurious qualifiers here appear to be valid in C.
3346 unsigned DiagID = diag::warn_standalone_specifier;
3347 if (getLangOpts().CPlusPlus)
3348 DiagID = diag::ext_standalone_specifier;
3349
3350 // Note that a linkage-specification sets a storage class, but
3351 // 'extern "C" struct foo;' is actually valid and not theoretically
3352 // useless.
3353 if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3354 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3355 Diag(DS.getStorageClassSpecLoc(), DiagID)
3356 << DeclSpec::getSpecifierName(SCS);
3357
Richard Smithb4a9e862013-04-12 22:46:28 +00003358 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3359 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3360 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003361 if (DS.getTypeQualifiers()) {
3362 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3363 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3364 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3365 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3366 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003367 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3368 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003369 }
3370
Eli Friedmane3217952011-12-17 00:36:09 +00003371 // Warn about ignored type attributes, for example:
3372 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003373 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003374 if (!DS.getAttributes().empty()) {
3375 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3376 if (TypeSpecType == DeclSpec::TST_class ||
3377 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003378 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003379 TypeSpecType == DeclSpec::TST_union ||
3380 TypeSpecType == DeclSpec::TST_enum) {
3381 AttributeList* attrs = DS.getAttributes().getList();
3382 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003383 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003384 << attrs->getName()
3385 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3386 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003387 TypeSpecType == DeclSpec::TST_union ? 2 :
3388 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003389 attrs = attrs->getNext();
3390 }
3391 }
3392 }
John McCallaa017372011-03-22 23:00:04 +00003393
John McCall48871652010-08-21 09:40:31 +00003394 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003395}
3396
John McCallea305ed2009-12-18 10:40:03 +00003397/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003398/// check if there's an existing declaration that can't be overloaded.
3399///
3400/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003401static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3402 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003403 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003404 DeclarationName Name,
3405 SourceLocation NameLoc,
3406 unsigned diagnostic) {
3407 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3408 Sema::ForRedeclaration);
3409 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003410
John McCallea305ed2009-12-18 10:40:03 +00003411 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003412 return false;
3413
3414 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003415 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003416 assert(PrevDecl && "Expected a non-null Decl");
3417
3418 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3419 return false;
John McCall1f82f242009-11-18 22:49:29 +00003420
John McCallea305ed2009-12-18 10:40:03 +00003421 SemaRef.Diag(NameLoc, diagnostic) << Name;
3422 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003423
3424 return true;
3425}
3426
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003427/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3428/// anonymous struct or union AnonRecord into the owning context Owner
3429/// and scope S. This routine will be invoked just after we realize
3430/// that an unnamed union or struct is actually an anonymous union or
3431/// struct, e.g.,
3432///
3433/// @code
3434/// union {
3435/// int i;
3436/// float f;
3437/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3438/// // f into the surrounding scope.x
3439/// @endcode
3440///
3441/// This routine is recursive, injecting the names of nested anonymous
3442/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003443static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003444 DeclContext *Owner,
3445 RecordDecl *AnonRecord,
3446 AccessSpecifier AS,
3447 SmallVectorImpl<NamedDecl *> &Chaining,
3448 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003449 unsigned diagKind
3450 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3451 : diag::err_anonymous_struct_member_redecl;
3452
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003453 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003454
3455 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003456 for (auto *D : AnonRecord->decls()) {
3457 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3458 cast<NamedDecl>(D)->getDeclName()) {
3459 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003460 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3461 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003462 // C++ [class.union]p2:
3463 // The names of the members of an anonymous union shall be
3464 // distinct from the names of any other entity in the
3465 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003466 Invalid = true;
3467 } else {
3468 // C++ [class.union]p2:
3469 // For the purpose of name lookup, after the anonymous union
3470 // definition, the members of the anonymous union are
3471 // considered to have been defined in the scope in which the
3472 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003473 unsigned OldChainingSize = Chaining.size();
3474 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003475 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003476 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003477 else
3478 Chaining.push_back(VD);
3479
Francois Pichet783dd6e2010-11-21 06:08:52 +00003480 assert(Chaining.size() >= 2);
3481 NamedDecl **NamedChain =
3482 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3483 for (unsigned i = 0; i < Chaining.size(); i++)
3484 NamedChain[i] = Chaining[i];
3485
3486 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003487 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3488 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003489 NamedChain, Chaining.size());
3490
3491 IndirectField->setAccess(AS);
3492 IndirectField->setImplicit();
3493 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003494
3495 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003496 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003497
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003498 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003499 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003500 }
3501 }
3502
3503 return Invalid;
3504}
3505
Douglas Gregorc4df4072010-04-19 22:54:31 +00003506/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3507/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003508/// illegal input values are mapped to SC_None.
3509static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003510StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3511 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3512 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3513 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003514 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003515 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003516 case DeclSpec::SCS_extern:
3517 if (DS.isExternInLinkageSpec())
3518 return SC_None;
3519 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003520 case DeclSpec::SCS_static: return SC_Static;
3521 case DeclSpec::SCS_auto: return SC_Auto;
3522 case DeclSpec::SCS_register: return SC_Register;
3523 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003524 // Illegal SCSs map to None: error reporting is up to the caller.
3525 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003526 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003527 }
3528 llvm_unreachable("unknown storage class specifier");
3529}
3530
Richard Smithab44d5b2013-12-10 08:25:00 +00003531static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3532 assert(Record->hasInClassInitializer());
3533
Aaron Ballman629afae2014-03-07 19:56:05 +00003534 for (const auto *I : Record->decls()) {
3535 const auto *FD = dyn_cast<FieldDecl>(I);
3536 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003537 FD = IFD->getAnonField();
3538 if (FD && FD->hasInClassInitializer())
3539 return FD->getLocation();
3540 }
3541
3542 llvm_unreachable("couldn't find in-class initializer");
3543}
3544
3545static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3546 SourceLocation DefaultInitLoc) {
3547 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3548 return;
3549
3550 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3551 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3552}
3553
3554static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3555 CXXRecordDecl *AnonUnion) {
3556 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3557 return;
3558
3559 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3560}
3561
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003562/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003563/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003564/// (C++ [class.union]) and a C11 feature; anonymous structures
3565/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003566Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003567 AccessSpecifier AS,
3568 RecordDecl *Record,
3569 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003570 DeclContext *Owner = Record->getDeclContext();
3571
3572 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003574 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003575 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003576 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003577 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003578 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003580 // C and C++ require different kinds of checks for anonymous
3581 // structs/unions.
3582 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003583 if (getLangOpts().CPlusPlus) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003584 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00003585 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003586 if (Record->isUnion()) {
3587 // C++ [class.union]p6:
3588 // Anonymous unions declared in a named namespace or in the
3589 // global namespace shall be declared static.
3590 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3591 (isa<TranslationUnitDecl>(Owner) ||
3592 (isa<NamespaceDecl>(Owner) &&
3593 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003594 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3595 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003596
3597 // Recover by adding 'static'.
3598 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003599 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003600 }
3601 // C++ [class.union]p6:
3602 // A storage class is not allowed in a declaration of an
3603 // anonymous union in a class scope.
3604 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3605 isa<RecordDecl>(Owner)) {
3606 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003607 diag::err_anonymous_union_with_storage_spec)
3608 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003609
3610 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003611 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3612 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003613 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003614 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003615 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003616
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003617 // Ignore const/volatile/restrict qualifiers.
3618 if (DS.getTypeQualifiers()) {
3619 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3620 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003621 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003622 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3623 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003624 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003625 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003626 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003627 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3628 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003629 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003630 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003631 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003632 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003633 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3634 Diag(DS.getAtomicSpecLoc(),
3635 diag::ext_anonymous_struct_union_qualified)
3636 << Record->isUnion() << "_Atomic"
3637 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003638
3639 DS.ClearTypeQualifiers();
3640 }
3641
Mike Stump11289f42009-09-09 15:08:12 +00003642 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003643 // The member-specification of an anonymous union shall only
3644 // define non-static data members. [Note: nested types and
3645 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003646 for (auto *Mem : Record->decls()) {
3647 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003648 // C++ [class.union]p3:
3649 // An anonymous union shall not have private or protected
3650 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003651 assert(FD->getAccess() != AS_none);
3652 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003653 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3654 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3655 Invalid = true;
3656 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003657
Alexis Hunt97ab5542011-05-16 22:41:40 +00003658 // C++ [class.union]p1
3659 // An object of a class with a non-trivial constructor, a non-trivial
3660 // copy constructor, a non-trivial destructor, or a non-trivial copy
3661 // assignment operator cannot be a member of a union, nor can an
3662 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003663 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003664 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003665 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003666 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003667 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003668 // This is a type that showed up in an
3669 // elaborated-type-specifier inside the anonymous struct or
3670 // union, but which actually declares a type outside of the
3671 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003672 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003673 if (!MemRecord->isAnonymousStructOrUnion() &&
3674 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003675 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003676 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003677 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3678 << (int)Record->isUnion();
3679 else {
3680 // This is a nested type declaration.
3681 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3682 << (int)Record->isUnion();
3683 Invalid = true;
3684 }
Richard Smith254d2662013-01-28 00:54:05 +00003685 } else {
3686 // This is an anonymous type definition within another anonymous type.
3687 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3688 // not part of standard C++.
3689 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003690 diag::ext_anonymous_record_with_anonymous_type)
3691 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003692 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003693 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003694 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003695 } else {
3696 // We have something that isn't a non-static data
3697 // member. Complain about it.
3698 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003699 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003700 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003701 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003702 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003703 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003704 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003705
3706 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003707 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003708 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003709 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003710 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003711 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003712 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003713 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003714 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003715 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003716 }
3717 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003718
3719 // C++11 [class.union]p8 (DR1460):
3720 // At most one variant member of a union may have a
3721 // brace-or-equal-initializer.
3722 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3723 Owner->isRecord())
3724 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3725 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003726 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003727
3728 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003729 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003730 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003731 Invalid = true;
3732 }
3733
John McCallfa2d6922009-10-22 23:31:08 +00003734 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003735 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003736 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003737 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003738
Mike Stump11289f42009-09-09 15:08:12 +00003739 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003740 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003741 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003742 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003743 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003744 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003745 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003746 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003747 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003748 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003749 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003750 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003751 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003752 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003753 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003754 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003755 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003756 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003757 // mutable can only appear on non-static class members, so it's always
3758 // an error here
3759 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3760 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003761 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003762 }
3763
Abramo Bagnaradff19302011-03-08 08:55:46 +00003764 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003765 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003766 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003767 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003768 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003769
3770 // Default-initialize the implicit variable. This initialization will be
3771 // trivial in almost all cases, except if a union member has an in-class
3772 // initializer:
3773 // union { int n = 0; };
3774 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003775 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003776 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003777
Richard Smithab44d5b2013-12-10 08:25:00 +00003778 // Mark this as an anonymous struct/union type.
3779 Record->setAnonymousStructOrUnion(true);
3780
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003781 // Add the anonymous struct/union object to the current
3782 // context. We'll be referencing this object when we refer to one of
3783 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003784 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003785
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003786 // Inject the members of the anonymous struct/union into the owning
3787 // context and into the identifier resolver chain for name lookup
3788 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003789 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003790 Chain.push_back(Anon);
3791
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003792 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3793 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003794 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003795
David Majnemer2206bf52014-03-05 08:57:59 +00003796 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3797 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3798 Decl *ManglingContextDecl;
3799 if (MangleNumberingContext *MCtx =
3800 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3801 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003802 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003803 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3804 }
3805 }
3806 }
3807
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003808 if (Invalid)
3809 Anon->setInvalidDecl();
3810
John McCall48871652010-08-21 09:40:31 +00003811 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003812}
3813
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003814/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3815/// Microsoft C anonymous structure.
3816/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3817/// Example:
3818///
3819/// struct A { int a; };
3820/// struct B { struct A; int b; };
3821///
3822/// void foo() {
3823/// B var;
3824/// var.a = 3;
3825/// }
3826///
3827Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3828 RecordDecl *Record) {
3829
3830 // If there is no Record, get the record via the typedef.
3831 if (!Record)
3832 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3833
3834 // Mock up a declarator.
3835 Declarator Dc(DS, Declarator::TypeNameContext);
3836 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3837 assert(TInfo && "couldn't build declarator info for anonymous struct");
3838
3839 // Create a declaration for this anonymous struct.
3840 NamedDecl* Anon = FieldDecl::Create(Context,
3841 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003842 DS.getLocStart(),
3843 DS.getLocStart(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003844 /*IdentifierInfo=*/0,
3845 Context.getTypeDeclType(Record),
3846 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00003847 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003848 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003849 Anon->setImplicit();
3850
3851 // Add the anonymous struct object to the current context.
3852 CurContext->addDecl(Anon);
3853
3854 // Inject the members of the anonymous struct into the current
3855 // context and into the identifier resolver chain for name lookup
3856 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003857 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003858 Chain.push_back(Anon);
3859
Nico Weberf8bb3de2012-02-01 00:41:00 +00003860 RecordDecl *RecordDef = Record->getDefinition();
3861 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3862 RecordDef, AS_none,
3863 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003864 Anon->setInvalidDecl();
3865
3866 return Anon;
3867}
Steve Naroff2fea1392007-09-02 02:04:30 +00003868
Douglas Gregor92751d42008-11-17 22:58:34 +00003869/// GetNameForDeclarator - Determine the full declaration name for the
3870/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003871DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003872 return GetNameFromUnqualifiedId(D.getName());
3873}
3874
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003875/// \brief Retrieves the declaration name from a parsed unqualified-id.
3876DeclarationNameInfo
3877Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3878 DeclarationNameInfo NameInfo;
3879 NameInfo.setLoc(Name.StartLocation);
3880
Douglas Gregor7861a802009-11-03 01:35:08 +00003881 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003882
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003883 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003884 case UnqualifiedId::IK_Identifier:
3885 NameInfo.setName(Name.Identifier);
3886 NameInfo.setLoc(Name.StartLocation);
3887 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003888
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003889 case UnqualifiedId::IK_OperatorFunctionId:
3890 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3891 Name.OperatorFunctionId.Operator));
3892 NameInfo.setLoc(Name.StartLocation);
3893 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3894 = Name.OperatorFunctionId.SymbolLocations[0];
3895 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3896 = Name.EndLocation.getRawEncoding();
3897 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003898
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003899 case UnqualifiedId::IK_LiteralOperatorId:
3900 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3901 Name.Identifier));
3902 NameInfo.setLoc(Name.StartLocation);
3903 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3904 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003905
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003906 case UnqualifiedId::IK_ConversionFunctionId: {
3907 TypeSourceInfo *TInfo;
3908 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3909 if (Ty.isNull())
3910 return DeclarationNameInfo();
3911 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3912 Context.getCanonicalType(Ty)));
3913 NameInfo.setLoc(Name.StartLocation);
3914 NameInfo.setNamedTypeInfo(TInfo);
3915 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003916 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003917
3918 case UnqualifiedId::IK_ConstructorName: {
3919 TypeSourceInfo *TInfo;
3920 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3921 if (Ty.isNull())
3922 return DeclarationNameInfo();
3923 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3924 Context.getCanonicalType(Ty)));
3925 NameInfo.setLoc(Name.StartLocation);
3926 NameInfo.setNamedTypeInfo(TInfo);
3927 return NameInfo;
3928 }
3929
3930 case UnqualifiedId::IK_ConstructorTemplateId: {
3931 // In well-formed code, we can only have a constructor
3932 // template-id that refers to the current context, so go there
3933 // to find the actual type being constructed.
3934 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3935 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3936 return DeclarationNameInfo();
3937
3938 // Determine the type of the class being constructed.
3939 QualType CurClassType = Context.getTypeDeclType(CurClass);
3940
3941 // FIXME: Check two things: that the template-id names the same type as
3942 // CurClassType, and that the template-id does not occur when the name
3943 // was qualified.
3944
3945 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3946 Context.getCanonicalType(CurClassType)));
3947 NameInfo.setLoc(Name.StartLocation);
3948 // FIXME: should we retrieve TypeSourceInfo?
3949 NameInfo.setNamedTypeInfo(0);
3950 return NameInfo;
3951 }
3952
3953 case UnqualifiedId::IK_DestructorName: {
3954 TypeSourceInfo *TInfo;
3955 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3956 if (Ty.isNull())
3957 return DeclarationNameInfo();
3958 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3959 Context.getCanonicalType(Ty)));
3960 NameInfo.setLoc(Name.StartLocation);
3961 NameInfo.setNamedTypeInfo(TInfo);
3962 return NameInfo;
3963 }
3964
3965 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00003966 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003967 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3968 return Context.getNameForTemplate(TName, TNameLoc);
3969 }
3970
3971 } // switch (Name.getKind())
3972
David Blaikie83d382b2011-09-23 05:06:16 +00003973 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00003974}
3975
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003976static QualType getCoreType(QualType Ty) {
3977 do {
3978 if (Ty->isPointerType() || Ty->isReferenceType())
3979 Ty = Ty->getPointeeType();
3980 else if (Ty->isArrayType())
3981 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3982 else
3983 return Ty.withoutLocalFastQualifiers();
3984 } while (true);
3985}
3986
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00003987/// hasSimilarParameters - Determine whether the C++ functions Declaration
3988/// and Definition have "nearly" matching parameters. This heuristic is
3989/// used to improve diagnostics in the case where an out-of-line function
3990/// definition doesn't match any declaration within the class or namespace.
3991/// Also sets Params to the list of indices to the parameters that differ
3992/// between the declaration and the definition. If hasSimilarParameters
3993/// returns true and Params is empty, then all of the parameters match.
3994static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00003995 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003996 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003997 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00003998 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00003999 if (Declaration->param_size() != Definition->param_size())
4000 return false;
4001 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4002 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4003 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4004
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004005 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004006 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004007 continue;
4008
4009 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4010 QualType DefParamBaseTy = getCoreType(DefParamTy);
4011 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4012 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4013
4014 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4015 (DeclTyName && DeclTyName == DefTyName))
4016 Params.push_back(Idx);
4017 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004018 return false;
4019 }
4020
4021 return true;
4022}
4023
John McCall99b2fe52010-04-29 23:50:39 +00004024/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4025/// declarator needs to be rebuilt in the current instantiation.
4026/// Any bits of declarator which appear before the name are valid for
4027/// consideration here. That's specifically the type in the decl spec
4028/// and the base type in any member-pointer chunks.
4029static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4030 DeclarationName Name) {
4031 // The types we specifically need to rebuild are:
4032 // - typenames, typeofs, and decltypes
4033 // - types which will become injected class names
4034 // Of course, we also need to rebuild any type referencing such a
4035 // type. It's safest to just say "dependent", but we call out a
4036 // few cases here.
4037
4038 DeclSpec &DS = D.getMutableDeclSpec();
4039 switch (DS.getTypeSpecType()) {
4040 case DeclSpec::TST_typename:
4041 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004042 case DeclSpec::TST_underlyingType:
4043 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004044 // Grab the type from the parser.
4045 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00004046 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004047 if (T.isNull() || !T->isDependentType()) break;
4048
4049 // Make sure there's a type source info. This isn't really much
4050 // of a waste; most dependent types should have type source info
4051 // attached already.
4052 if (!TSI)
4053 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4054
4055 // Rebuild the type in the current instantiation.
4056 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4057 if (!TSI) return true;
4058
4059 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004060 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4061 DS.UpdateTypeRep(LocType);
4062 break;
4063 }
4064
Richard Smith1620ebd2012-10-01 20:35:07 +00004065 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004066 case DeclSpec::TST_typeofExpr: {
4067 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004068 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004069 if (Result.isInvalid()) return true;
4070 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004071 break;
4072 }
4073
4074 default:
4075 // Nothing to do for these decl specs.
4076 break;
4077 }
4078
4079 // It doesn't matter what order we do this in.
4080 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4081 DeclaratorChunk &Chunk = D.getTypeObject(I);
4082
4083 // The only type information in the declarator which can come
4084 // before the declaration name is the base type of a member
4085 // pointer.
4086 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4087 continue;
4088
4089 // Rebuild the scope specifier in-place.
4090 CXXScopeSpec &SS = Chunk.Mem.Scope();
4091 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4092 return true;
4093 }
4094
4095 return false;
4096}
4097
Anders Carlsson1052fd72011-07-04 16:28:17 +00004098Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004099 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004100 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004101
4102 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004103 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004104 Dcl->setTopLevelDeclInObjCContainer();
4105
4106 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004107}
4108
Richard Smithdda56e42011-04-15 14:24:37 +00004109/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4110/// If T is the name of a class, then each of the following shall have a
4111/// name different from T:
4112/// - every static data member of class T;
4113/// - every member function of class T
4114/// - every member of class T that is itself a type;
4115/// \returns true if the declaration name violates these rules.
4116bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4117 DeclarationNameInfo NameInfo) {
4118 DeclarationName Name = NameInfo.getName();
4119
4120 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4121 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4122 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4123 return true;
4124 }
4125
4126 return false;
4127}
Douglas Gregor31feb332012-03-17 23:06:31 +00004128
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004129/// \brief Diagnose a declaration whose declarator-id has the given
4130/// nested-name-specifier.
4131///
4132/// \param SS The nested-name-specifier of the declarator-id.
4133///
4134/// \param DC The declaration context to which the nested-name-specifier
4135/// resolves.
4136///
4137/// \param Name The name of the entity being declared.
4138///
4139/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004140///
4141/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004142bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004143 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004144 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004145 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004146 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004147 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004148
4149 // If the user provided a superfluous scope specifier that refers back to the
4150 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004151 //
4152 // class X {
4153 // void X::f();
4154 // };
Richard Smitha2302242013-12-05 07:51:02 +00004155 //
4156 // Note, it was once ill-formed to give redundant qualification in all
4157 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004158 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004159 if (Cur->isRecord()) {
4160 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4161 : diag::err_member_extra_qualification)
4162 << Name << FixItHint::CreateRemoval(SS.getRange());
4163 SS.clear();
4164 } else {
4165 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4166 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004167 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004168 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004169
4170 // Check whether the qualifying scope encloses the scope of the original
4171 // declaration.
4172 if (!Cur->Encloses(DC)) {
4173 if (Cur->isRecord())
4174 Diag(Loc, diag::err_member_qualification)
4175 << Name << SS.getRange();
4176 else if (isa<TranslationUnitDecl>(DC))
4177 Diag(Loc, diag::err_invalid_declarator_global_scope)
4178 << Name << SS.getRange();
4179 else if (isa<FunctionDecl>(Cur))
4180 Diag(Loc, diag::err_invalid_declarator_in_function)
4181 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004182 else if (isa<BlockDecl>(Cur))
4183 Diag(Loc, diag::err_invalid_declarator_in_block)
4184 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004185 else
4186 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004187 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004188
Douglas Gregor31feb332012-03-17 23:06:31 +00004189 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004190 }
4191
4192 if (Cur->isRecord()) {
4193 // Cannot qualify members within a class.
4194 Diag(Loc, diag::err_member_qualification)
4195 << Name << SS.getRange();
4196 SS.clear();
4197
4198 // C++ constructors and destructors with incorrect scopes can break
4199 // our AST invariants by having the wrong underlying types. If
4200 // that's the case, then drop this declaration entirely.
4201 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4202 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4203 !Context.hasSameType(Name.getCXXNameType(),
4204 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4205 return true;
4206
4207 return false;
4208 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004209
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004210 // C++11 [dcl.meaning]p1:
4211 // [...] "The nested-name-specifier of the qualified declarator-id shall
4212 // not begin with a decltype-specifer"
4213 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4214 while (SpecLoc.getPrefix())
4215 SpecLoc = SpecLoc.getPrefix();
4216 if (dyn_cast_or_null<DecltypeType>(
4217 SpecLoc.getNestedNameSpecifier()->getAsType()))
4218 Diag(Loc, diag::err_decltype_in_declarator)
4219 << SpecLoc.getTypeLoc().getSourceRange();
4220
Douglas Gregor31feb332012-03-17 23:06:31 +00004221 return false;
4222}
4223
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004224NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4225 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004226 // TODO: consider using NameInfo for diagnostic.
4227 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4228 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004229
Chris Lattner02c04392007-07-25 00:24:17 +00004230 // All of these full declarators require an identifier. If it doesn't have
4231 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004232 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004233 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004234 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004235 diag::err_declarator_need_ident)
4236 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00004237 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00004238 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4239 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004240
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004241 // The scope passed in may not be a decl scope. Zip up the scope tree until
4242 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004243 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004244 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004245 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004246
John McCall99b2fe52010-04-29 23:50:39 +00004247 DeclContext *DC = CurContext;
4248 if (D.getCXXScopeSpec().isInvalid())
4249 D.setInvalidType();
4250 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004251 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4252 UPPC_DeclarationQualifier))
4253 return 0;
4254
John McCall99b2fe52010-04-29 23:50:39 +00004255 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4256 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004257 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004258 // If we could not compute the declaration context, it's because the
4259 // declaration context is dependent but does not refer to a class,
4260 // class template, or class template partial specialization. Complain
4261 // and return early, to avoid the coming semantic disaster.
4262 Diag(D.getIdentifierLoc(),
4263 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004264 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004265 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00004266 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004267 }
John McCall99b2fe52010-04-29 23:50:39 +00004268 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004269
John McCall99b2fe52010-04-29 23:50:39 +00004270 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004271 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00004272 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00004273
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004274 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4275 Diag(D.getIdentifierLoc(),
4276 diag::err_member_def_undefined_record)
4277 << Name << DC << D.getCXXScopeSpec().getRange();
4278 D.setInvalidType();
4279 } else if (!D.getDeclSpec().isFriendSpecified()) {
4280 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4281 Name, D.getIdentifierLoc())) {
4282 if (DC->isRecord())
Douglas Gregor31feb332012-03-17 23:06:31 +00004283 return 0;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004284
4285 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004286 }
John McCall99b2fe52010-04-29 23:50:39 +00004287 }
4288
4289 // Check whether we need to rebuild the type of the given
4290 // declaration in the current instantiation.
4291 if (EnteringContext && IsDependentContext &&
4292 TemplateParamLists.size() != 0) {
4293 ContextRAII SavedContext(*this, DC);
4294 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4295 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004296 }
4297 }
Richard Smithdda56e42011-04-15 14:24:37 +00004298
4299 if (DiagnoseClassNameShadow(DC, NameInfo))
4300 // If this is a typedef, we'll end up spewing multiple diagnostics.
4301 // Just return early; it's safer.
4302 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4303 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00004304
John McCall8cb7bdf2010-06-04 23:28:52 +00004305 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4306 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004307
Douglas Gregor506bd562010-12-13 22:49:22 +00004308 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4309 UPPC_DeclarationType))
4310 D.setInvalidType();
4311
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004312 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004313 ForRedeclaration);
4314
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004315 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004316 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004317 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004318 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004319
4320 // If the declaration we're planning to build will be a function
4321 // or object with linkage, then look for another declaration with
4322 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004323 //
4324 // If the declaration we're planning to build will be declared with
4325 // external linkage in the translation unit, create any builtin with
4326 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004327 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4328 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004329 else if (CurContext->isFunctionOrMethod() &&
4330 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4331 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004332 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004333 CreateBuiltins =
4334 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4335 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4336 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4337 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004338
4339 if (IsLinkageLookup)
4340 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004341
Richard Smith1c34fb72013-08-13 18:18:50 +00004342 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004343 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004344 LookupQualifiedName(Previous, DC);
4345
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004346 // C++ [dcl.meaning]p1:
4347 // When the declarator-id is qualified, the declaration shall refer to a
4348 // previously declared member of the class or namespace to which the
4349 // qualifier refers (or, in the case of a namespace, of an element of the
4350 // inline namespace set of that namespace (7.3.1)) or to a specialization
4351 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004352 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004353 // Note that we already checked the context above, and that we do not have
4354 // enough information to make sure that Previous contains the declaration
4355 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004356 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004357 // class X {
4358 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004359 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004360 // };
4361 //
Douglas Gregorad590502008-12-15 23:53:10 +00004362 // void X::f(int) { } // ill-formed
4363 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004364 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004365 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004366 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004367
4368 // C++ [dcl.meaning]p1:
4369 // [...] the member shall not merely have been introduced by a
4370 // using-declaration in the scope of the class or namespace nominated by
4371 // the nested-name-specifier of the declarator-id.
4372 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004373 }
4374
John McCall1f82f242009-11-18 22:49:29 +00004375 if (Previous.isSingleResult() &&
4376 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004377 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004378 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004379 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4380 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004381
Douglas Gregor5101c242008-12-05 18:15:24 +00004382 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004383 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004384 }
4385
Douglas Gregor83a586e2008-04-13 21:07:44 +00004386 // In C++, the previous declaration we find might be a tag type
4387 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004388 // tag type. Note that this does does not apply if we're declaring a
4389 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004390 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004391 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004392 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004393
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004394 // Check that there are no default arguments other than in the parameters
4395 // of a function declaration (C++ only).
4396 if (getLangOpts().CPlusPlus)
4397 CheckExtraCXXDefaultArguments(D);
4398
Nico Webercb4c7f42012-12-23 00:40:46 +00004399 NamedDecl *New;
4400
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004401 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004402 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004403 if (TemplateParamLists.size()) {
4404 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00004405 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004408 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004409 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004410 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004411 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004412 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004413 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004414 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4415 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004416 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004417
4418 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00004419 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004420
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004421 // If this has an identifier and is not an invalid redeclaration or
4422 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004423 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004424 !(D.isRedeclaration() && New->isInvalidDecl())) {
4425 // Only make a locally-scoped extern declaration visible if it is the first
4426 // declaration of this entity. Qualified lookup for such an entity should
4427 // only find this declaration if there is no visible declaration of it.
4428 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4429 PushOnScopeChains(New, S, AddToContext);
4430 if (!AddToContext)
4431 CurContext->addHiddenDecl(New);
4432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433
John McCall48871652010-08-21 09:40:31 +00004434 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004435}
4436
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004437/// Helper method to turn variable array types into constant array
4438/// types in certain situations which would otherwise be errors (for
4439/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004440static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4441 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004442 bool &SizeIsNegative,
4443 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004444 // This method tries to turn a variable array into a constant
4445 // array even when the size isn't an ICE. This is necessary
4446 // for compatibility with code that depends on gcc's buggy
4447 // constant expression folding, like struct {char x[(int)(char*)2];}
4448 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004449 Oversized = 0;
4450
4451 if (T->isDependentType())
4452 return QualType();
4453
John McCall8ccfcb52009-09-24 19:53:00 +00004454 QualifierCollector Qs;
4455 const Type *Ty = Qs.strip(T);
4456
4457 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004458 QualType Pointee = PTy->getPointeeType();
4459 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004460 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4461 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004462 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004463 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004464 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004465 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004466 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4467 QualType Inner = PTy->getInnerType();
4468 QualType FixedType =
4469 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4470 Oversized);
4471 if (FixedType.isNull()) return FixedType;
4472 FixedType = Context.getParenType(FixedType);
4473 return Qs.apply(Context, FixedType);
4474 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004475
4476 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004477 if (!VLATy)
4478 return QualType();
4479 // FIXME: We should probably handle this case
4480 if (VLATy->getElementType()->isVariablyModifiedType())
4481 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004482
Richard Smith42d3af92011-12-07 00:43:50 +00004483 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004484 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004485 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004486 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004487
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004488 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004489 if (Res.isSigned() && Res.isNegative()) {
4490 SizeIsNegative = true;
4491 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004492 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004493
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004494 // Check whether the array is too large to be addressed.
4495 unsigned ActiveSizeBits
4496 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4497 Res);
4498 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4499 Oversized = Res;
4500 return QualType();
4501 }
4502
4503 return Context.getConstantArrayType(VLATy->getElementType(),
4504 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004505}
4506
Abramo Bagnara341ab732012-11-08 14:44:42 +00004507static void
4508FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004509 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4510 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4511 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4512 DstPTL.getPointeeLoc());
4513 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004514 return;
4515 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004516 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4517 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4518 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4519 DstPTL.getInnerLoc());
4520 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4521 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004522 return;
4523 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004524 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4525 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4526 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4527 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004528 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004529 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4530 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4531 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004532}
4533
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004534/// Helper method to turn variable array types into constant array
4535/// types in certain situations which would otherwise be errors (for
4536/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004537static TypeSourceInfo*
4538TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4539 ASTContext &Context,
4540 bool &SizeIsNegative,
4541 llvm::APSInt &Oversized) {
4542 QualType FixedTy
4543 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4544 SizeIsNegative, Oversized);
4545 if (FixedTy.isNull())
4546 return 0;
4547 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4548 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4549 FixedTInfo->getTypeLoc());
4550 return FixedTInfo;
4551}
4552
Richard Smith78165b52013-01-10 23:43:47 +00004553/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004554/// that it can be found later for redeclarations. We include any extern "C"
4555/// declaration that is not visible in the translation unit here, not just
4556/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004557void
Richard Smith39b79682013-06-18 20:15:12 +00004558Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004559 if (!getLangOpts().CPlusPlus &&
4560 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4561 // Don't need to track declarations in the TU in C.
4562 return;
4563
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004564 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004565 // FIXME: There can be multiple such declarations if they are functions marked
4566 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004567 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004568}
4569
Richard Smith39b79682013-06-18 20:15:12 +00004570NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004571 if (ExternalSource) {
4572 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004573 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004574 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004575 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004576 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4577 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004578 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4579 if (Pos == LocallyScopedExternCDecls.end())
4580 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004581 }
4582 }
Richard Smith39b79682013-06-18 20:15:12 +00004583
4584 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00004585 return D ? D->getMostRecentDecl() : 0;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004586}
4587
Eli Friedman574c7452009-04-07 19:37:57 +00004588/// \brief Diagnose function specifiers on a declaration of an identifier that
4589/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004590void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004591 // FIXME: We should probably indicate the identifier in question to avoid
4592 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004593 if (DS.isInlineSpecified())
4594 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004595 diag::err_inline_non_function);
4596
Richard Smithb1402ae2013-03-18 22:52:47 +00004597 if (DS.isVirtualSpecified())
4598 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004599 diag::err_virtual_non_function);
4600
Richard Smithb1402ae2013-03-18 22:52:47 +00004601 if (DS.isExplicitSpecified())
4602 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004603 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004604
Richard Smithb1402ae2013-03-18 22:52:47 +00004605 if (DS.isNoreturnSpecified())
4606 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004607 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004608}
4609
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004610NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004611Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004612 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004613 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4614 if (D.getCXXScopeSpec().isSet()) {
4615 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4616 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004617 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004618 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004619 DC = CurContext;
4620 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004621 }
4622
Richard Smithb1402ae2013-03-18 22:52:47 +00004623 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004624
Richard Smitha77a0a62011-08-15 21:04:07 +00004625 if (D.getDeclSpec().isConstexprSpecified())
4626 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4627 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004628
Douglas Gregord8f446f2010-07-13 06:37:01 +00004629 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4630 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4631 << D.getName().getSourceRange();
4632 return 0;
4633 }
4634
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004635 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004636 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004637
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004638 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004639 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004640
Richard Smith3f1b5d02011-05-05 21:57:07 +00004641 CheckTypedefForVariablyModifiedType(S, NewTD);
4642
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004643 bool Redeclaration = D.isRedeclaration();
4644 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4645 D.setRedeclaration(Redeclaration);
4646 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004647}
4648
Richard Smith3f1b5d02011-05-05 21:57:07 +00004649void
4650Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004651 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4652 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004653 // Note that variably modified types must be fixed before merging the decl so
4654 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004655 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4656 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004657 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004658 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004659
Chris Lattner9fecd742009-04-19 05:21:20 +00004660 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004661 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004662 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004663 TypeSourceInfo *FixedTInfo =
4664 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4665 SizeIsNegative,
4666 Oversized);
4667 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004668 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004669 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004670 } else {
4671 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004672 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004673 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004674 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004675 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004676 Diag(NewTD->getLocation(), diag::err_array_too_large)
4677 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004678 else
Richard Smithdda56e42011-04-15 14:24:37 +00004679 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004680 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004681 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004682 }
4683 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004684}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004685
Richard Smith3f1b5d02011-05-05 21:57:07 +00004686
4687/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4688/// declares a typedef-name, either using the 'typedef' type specifier or via
4689/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4690NamedDecl*
4691Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4692 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004693 // Merge the decl with the existing one if appropriate. If the decl is
4694 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004695 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4696 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004697 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004698 if (!Previous.empty()) {
4699 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004700 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004701 }
4702
Douglas Gregor27821ce2009-07-07 16:35:42 +00004703 // If this is the C FILE type, notify the AST context.
4704 if (IdentifierInfo *II = NewTD->getIdentifier())
4705 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004706 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004707 if (II->isStr("FILE"))
4708 Context.setFILEDecl(NewTD);
4709 else if (II->isStr("jmp_buf"))
4710 Context.setjmp_bufDecl(NewTD);
4711 else if (II->isStr("sigjmp_buf"))
4712 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004713 else if (II->isStr("ucontext_t"))
4714 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004715 }
4716
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004717 return NewTD;
4718}
4719
Douglas Gregor5d68a202009-02-24 19:23:27 +00004720/// \brief Determines whether the given declaration is an out-of-scope
4721/// previous declaration.
4722///
4723/// This routine should be invoked when name lookup has found a
4724/// previous declaration (PrevDecl) that is not in the scope where a
4725/// new declaration by the same name is being introduced. If the new
4726/// declaration occurs in a local scope, previous declarations with
4727/// linkage may still be considered previous declarations (C99
4728/// 6.2.2p4-5, C++ [basic.link]p6).
4729///
4730/// \param PrevDecl the previous declaration found by name
4731/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004732///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004733/// \param DC the context in which the new declaration is being
4734/// declared.
4735///
4736/// \returns true if PrevDecl is an out-of-scope previous declaration
4737/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004738static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004739isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4740 ASTContext &Context) {
4741 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004742 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004743
Douglas Gregoreddf4332009-02-24 20:03:32 +00004744 if (!PrevDecl->hasLinkage())
4745 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004746
David Blaikiebbafb8a2012-03-11 07:00:24 +00004747 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004748 // C++ [basic.link]p6:
4749 // If there is a visible declaration of an entity with linkage
4750 // having the same name and type, ignoring entities declared
4751 // outside the innermost enclosing namespace scope, the block
4752 // scope declaration declares that same entity and receives the
4753 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004754 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004755 if (!OuterContext->isFunctionOrMethod())
4756 // This rule only applies to block-scope declarations.
4757 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004758
4759 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4760 if (PrevOuterContext->isRecord())
4761 // We found a member function: ignore it.
4762 return false;
4763
4764 // Find the innermost enclosing namespace for the new and
4765 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004766 OuterContext = OuterContext->getEnclosingNamespaceContext();
4767 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004768
Douglas Gregorfcee9462010-08-27 22:55:10 +00004769 // The previous declaration is in a different namespace, so it
4770 // isn't the same function.
4771 if (!OuterContext->Equals(PrevOuterContext))
4772 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004773 }
4774
Douglas Gregor5d68a202009-02-24 19:23:27 +00004775 return true;
4776}
4777
John McCall3e11ebe2010-03-15 10:12:16 +00004778static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4779 CXXScopeSpec &SS = D.getCXXScopeSpec();
4780 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004781 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004782}
4783
John McCall31168b02011-06-15 23:02:42 +00004784bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4785 QualType type = decl->getType();
4786 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4787 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4788 // Various kinds of declaration aren't allowed to be __autoreleasing.
4789 unsigned kind = -1U;
4790 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4791 if (var->hasAttr<BlocksAttr>())
4792 kind = 0; // __block
4793 else if (!var->hasLocalStorage())
4794 kind = 1; // global
4795 } else if (isa<ObjCIvarDecl>(decl)) {
4796 kind = 3; // ivar
4797 } else if (isa<FieldDecl>(decl)) {
4798 kind = 2; // field
4799 }
4800
4801 if (kind != -1U) {
4802 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4803 << kind;
4804 }
4805 } else if (lifetime == Qualifiers::OCL_None) {
4806 // Try to infer lifetime.
4807 if (!type->isObjCLifetimeType())
4808 return false;
4809
4810 lifetime = type->getObjCARCImplicitLifetime();
4811 type = Context.getLifetimeQualifiedType(type, lifetime);
4812 decl->setType(type);
4813 }
4814
4815 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4816 // Thread-local variables cannot have lifetime.
4817 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004818 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004819 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004820 << var->getType();
4821 return true;
4822 }
4823 }
4824
4825 return false;
4826}
4827
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004828static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004829 // Ensure that an auto decl is deduced otherwise the checks below might cache
4830 // the wrong linkage.
4831 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4832
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004833 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004834 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004835 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004836 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4837 ND.dropAttr<WeakAttr>();
4838 }
4839 }
4840 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004841 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004842 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4843 ND.dropAttr<WeakRefAttr>();
4844 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004845 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004846
4847 // 'selectany' only applies to externally visible varable declarations.
4848 // It does not apply to functions.
4849 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4850 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4851 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4852 ND.dropAttr<SelectAnyAttr>();
4853 }
4854 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004855}
4856
John McCallc87d9722013-04-02 02:48:58 +00004857/// Given that we are within the definition of the given function,
4858/// will that definition behave like C99's 'inline', where the
4859/// definition is discarded except for optimization purposes?
4860static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4861 // Try to avoid calling GetGVALinkageForFunction.
4862
4863 // All cases of this require the 'inline' keyword.
4864 if (!FD->isInlined()) return false;
4865
4866 // This is only possible in C++ with the gnu_inline attribute.
4867 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4868 return false;
4869
4870 // Okay, go ahead and call the relatively-more-expensive function.
4871
4872#ifndef NDEBUG
4873 // AST quite reasonably asserts that it's working on a function
4874 // definition. We don't really have a way to tell it that we're
4875 // currently defining the function, so just lie to it in +Asserts
4876 // builds. This is an awful hack.
4877 FD->setLazyBody(1);
4878#endif
4879
4880 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4881
4882#ifndef NDEBUG
4883 FD->setLazyBody(0);
4884#endif
4885
4886 return isC99Inline;
4887}
4888
Richard Smithac974a32013-06-30 09:48:50 +00004889/// Determine whether a variable is extern "C" prior to attaching
4890/// an initializer. We can't just call isExternC() here, because that
4891/// will also compute and cache whether the declaration is externally
4892/// visible, which might change when we attach the initializer.
4893///
4894/// This can only be used if the declaration is known to not be a
4895/// redeclaration of an internal linkage declaration.
4896///
4897/// For instance:
4898///
4899/// auto x = []{};
4900///
4901/// Attaching the initializer here makes this declaration not externally
4902/// visible, because its type has internal linkage.
4903///
4904/// FIXME: This is a hack.
4905template<typename T>
4906static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4907 if (S.getLangOpts().CPlusPlus) {
4908 // In C++, the overloadable attribute negates the effects of extern "C".
4909 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4910 return false;
4911 }
4912 return D->isExternC();
4913}
4914
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004915static bool shouldConsiderLinkage(const VarDecl *VD) {
4916 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4917 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004918 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004919 if (DC->isFileContext())
4920 return true;
4921 if (DC->isRecord())
4922 return false;
4923 llvm_unreachable("Unexpected context");
4924}
4925
4926static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4927 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4928 if (DC->isFileContext() || DC->isFunctionOrMethod())
4929 return true;
4930 if (DC->isRecord())
4931 return false;
4932 llvm_unreachable("Unexpected context");
4933}
4934
Richard Smith541b38b2013-09-20 01:15:31 +00004935/// Adjust the \c DeclContext for a function or variable that might be a
4936/// function-local external declaration.
4937bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4938 if (!DC->isFunctionOrMethod())
4939 return false;
4940
4941 // If this is a local extern function or variable declared within a function
4942 // template, don't add it into the enclosing namespace scope until it is
4943 // instantiated; it might have a dependent type right now.
4944 if (DC->isDependentContext())
4945 return true;
4946
4947 // C++11 [basic.link]p7:
4948 // When a block scope declaration of an entity with linkage is not found to
4949 // refer to some other declaration, then that entity is a member of the
4950 // innermost enclosing namespace.
4951 //
4952 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4953 // semantically-enclosing namespace, not a lexically-enclosing one.
4954 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4955 DC = DC->getParent();
4956 return true;
4957}
4958
Larisse Voufo39a1e502013-08-06 01:03:05 +00004959NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00004960Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004961 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004962 MultiTemplateParamsArg TemplateParamLists,
4963 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004964 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004965 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004966
Douglas Gregorc4df4072010-04-19 22:54:31 +00004967 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00004968 VarDecl::StorageClass SC =
4969 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00004970
Richard Smith541b38b2013-09-20 01:15:31 +00004971 DeclContext *OriginalDC = DC;
4972 bool IsLocalExternDecl = SC == SC_Extern &&
4973 adjustContextForLocalExternDecl(DC);
4974
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00004975 if (getLangOpts().OpenCL) {
4976 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
4977 QualType NR = R;
4978 while (NR->isPointerType()) {
4979 if (NR->isFunctionPointerType()) {
4980 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
4981 D.setInvalidType();
4982 break;
4983 }
4984 NR = NR->getPointeeType();
4985 }
4986
4987 if (!getOpenCLOptions().cl_khr_fp16) {
4988 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4989 // half array type (unless the cl_khr_fp16 extension is enabled).
4990 if (Context.getBaseElementType(R)->isHalfType()) {
4991 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4992 D.setInvalidType();
4993 }
Joey Goulydd7f4562013-01-23 11:56:20 +00004994 }
4995 }
4996
Douglas Gregorc4df4072010-04-19 22:54:31 +00004997 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004998 // mutable can only appear on non-static class members, so it's always
4999 // an error here
5000 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005001 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005002 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005003 }
John McCallc87d9722013-04-02 02:48:58 +00005004
Richard Smithf2c9afc2013-06-17 01:34:01 +00005005 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5006 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5007 D.getDeclSpec().getStorageClassSpecLoc())) {
5008 // In C++11, the 'register' storage class specifier is deprecated.
5009 // Suppress the warning in system macros, it's used in macros in some
5010 // popular C system headers, such as in glibc's htonl() macro.
5011 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5012 diag::warn_deprecated_register)
5013 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5014 }
5015
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005016 IdentifierInfo *II = Name.getAsIdentifierInfo();
5017 if (!II) {
5018 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005019 << Name;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005020 return 0;
5021 }
5022
Richard Smithb1402ae2013-03-18 22:52:47 +00005023 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005024
Douglas Gregor212cab32009-03-11 20:22:50 +00005025 if (!DC->isRecord() && S->getFnParent() == 0) {
5026 // C99 6.9p2: The storage-class specifiers auto and register shall not
5027 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00005028 if (SC == SC_Auto || SC == SC_Register) {
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005029 // If this is a register variable with an asm label specified, then this
5030 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00005031 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00005032 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5033 else
5034 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005035 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005036 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005037 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005038
David Blaikiebbafb8a2012-03-11 07:00:24 +00005039 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005040 // Set up the special work-group-local storage class for variables in the
5041 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005042 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005043 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005044 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005045
Guy Benyei61054192013-02-07 10:55:47 +00005046 // OpenCL v1.2 s6.9.b p4:
5047 // The sampler type cannot be used with the __local and __global address
5048 // space qualifiers.
5049 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5050 R.getAddressSpace() == LangAS::opencl_global)) {
5051 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5052 }
5053
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005054 // OpenCL 1.2 spec, p6.9 r:
5055 // The event type cannot be used to declare a program scope variable.
5056 // The event type cannot be used with the __local, __constant and __global
5057 // address space qualifiers.
5058 if (R->isEventT()) {
5059 if (S->getParent() == 0) {
5060 Diag(D.getLocStart(), diag::err_event_t_global_var);
5061 D.setInvalidType();
5062 }
5063
5064 if (R.getAddressSpace()) {
5065 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5066 D.setInvalidType();
5067 }
5068 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005069 }
5070
Larisse Voufo39a1e502013-08-06 01:03:05 +00005071 bool IsExplicitSpecialization = false;
5072 bool IsVariableTemplateSpecialization = false;
5073 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005074 bool IsVariableTemplate = false;
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005075 VarDecl *NewVD = 0;
5076 VarTemplateDecl *NewTemplate = 0;
Richard Smithbeef3452014-01-16 23:39:20 +00005077 TemplateParameterList *TemplateParams = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005078 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005079 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005080 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005081 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005082
5083 if (D.isInvalidType())
5084 NewVD->setInvalidDecl();
5085 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005086 bool Invalid = false;
5087
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005088 if (DC->isRecord() && !CurContext->isRecord()) {
5089 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005090 switch (SC) {
5091 case SC_None:
5092 break;
5093 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005094 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5095 diag::err_static_out_of_line)
5096 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005097 break;
5098 case SC_Auto:
5099 case SC_Register:
5100 case SC_Extern:
5101 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5102 // to names of variables declared in a block or to function parameters.
5103 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5104 // of class members
5105
5106 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5107 diag::err_storage_class_for_static_member)
5108 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5109 break;
5110 case SC_PrivateExtern:
5111 llvm_unreachable("C storage class in c++!");
5112 case SC_OpenCLWorkGroupLocal:
5113 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005114 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005115 }
5116
Richard Smith42973752012-02-16 20:41:22 +00005117 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005118 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5119 if (RD->isLocalClass())
5120 Diag(D.getIdentifierLoc(),
5121 diag::err_static_data_member_not_allowed_in_local_class)
5122 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005123
Richard Smith42973752012-02-16 20:41:22 +00005124 // C++98 [class.union]p1: If a union contains a static data member,
5125 // the program is ill-formed. C++11 drops this restriction.
5126 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005127 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005128 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005129 ? diag::warn_cxx98_compat_static_data_member_in_union
5130 : diag::ext_static_data_member_in_union) << Name;
5131 // We conservatively disallow static data members in anonymous structs.
5132 else if (!RD->getDeclName())
5133 Diag(D.getIdentifierLoc(),
5134 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005135 << Name << RD->isUnion();
5136 }
5137 }
5138
5139 // Match up the template parameter lists with the scope specifier, then
5140 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005141 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5142 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5143 D.getCXXScopeSpec(), TemplateParamLists,
5144 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005145
Richard Smithbeef3452014-01-16 23:39:20 +00005146 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5147 !TemplateParams) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005148 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5149
5150 // We have encountered something that the user meant to be a
5151 // specialization (because it has explicitly-specified template
5152 // arguments) but that was not introduced with a "template<>" (or had
5153 // too few of them).
5154 // FIXME: Differentiate between attempts for explicit instantiations
5155 // (starting with "template") and the rest.
5156 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5157 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5158 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5159 "template<> ");
Richard Smith72db5632014-01-25 21:32:06 +00005160 IsExplicitSpecialization = true;
Richard Smithbeef3452014-01-16 23:39:20 +00005161 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5162 SourceLocation(), 0, 0,
5163 SourceLocation());
5164 }
5165
5166 if (TemplateParams) {
5167 if (!TemplateParams->size() &&
5168 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5169 // There is an extraneous 'template<>' for this variable. Complain
5170 // about it, but allow the declaration of the variable.
5171 Diag(TemplateParams->getTemplateLoc(),
5172 diag::err_template_variable_noparams)
5173 << II
5174 << SourceRange(TemplateParams->getTemplateLoc(),
5175 TemplateParams->getRAngleLoc());
5176 TemplateParams = 0;
5177 } else {
5178 // Only C++1y supports variable templates (N3651).
5179 Diag(D.getIdentifierLoc(),
5180 getLangOpts().CPlusPlus1y
5181 ? diag::warn_cxx11_compat_variable_template
5182 : diag::ext_variable_template);
5183
5184 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5185 // This is an explicit specialization or a partial specialization.
5186 // FIXME: Check that we can declare a specialization here.
5187 IsVariableTemplateSpecialization = true;
5188 IsPartialSpecialization = TemplateParams->size() > 0;
5189 } else { // if (TemplateParams->size() > 0)
5190 // This is a template declaration.
5191 IsVariableTemplate = true;
5192
5193 // Check that we can declare a template here.
5194 if (CheckTemplateDeclScope(S, TemplateParams))
5195 return 0;
5196 }
5197 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005198 }
Mike Stump11289f42009-09-09 15:08:12 +00005199
Larisse Voufo39a1e502013-08-06 01:03:05 +00005200 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005201 SourceLocation TemplateKWLoc =
5202 TemplateParamLists.size() > 0
5203 ? TemplateParamLists[0]->getTemplateLoc()
5204 : SourceLocation();
5205 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005206 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005207 IsPartialSpecialization);
5208 if (Res.isInvalid())
5209 return 0;
5210 NewVD = cast<VarDecl>(Res.get());
5211 AddToScope = false;
5212 } else
5213 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5214 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005215
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005216 // If this is supposed to be a variable template, create it as such.
5217 if (IsVariableTemplate) {
5218 NewTemplate =
5219 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005220 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005221 NewVD->setDescribedVarTemplate(NewTemplate);
5222 }
5223
Richard Smithb2bc2e62011-02-21 20:05:19 +00005224 // If this decl has an auto type in need of deduction, make a note of the
5225 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005226 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005227 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005228
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005229 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005230 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005231 if (NewTemplate)
5232 NewTemplate->setInvalidDecl();
5233 }
Mike Stump11289f42009-09-09 15:08:12 +00005234
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005235 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005236
Richard Smith72db5632014-01-25 21:32:06 +00005237 // If we have any template parameter lists that don't directly belong to
5238 // the variable (matching the scope specifier), store them.
5239 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5240 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005241 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005242 Context, TemplateParamLists.size() - VDTemplateParamLists,
5243 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005244
Richard Smith6331c402012-02-13 22:16:19 +00005245 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005246 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005247 }
5248
Douglas Gregor41866812011-09-12 18:37:38 +00005249 // Set the lexical context. If the declarator has a C++ scope specifier, the
5250 // lexical context will be different from the semantic context.
5251 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005252 if (NewTemplate)
5253 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005254
Richard Smith541b38b2013-09-20 01:15:31 +00005255 if (IsLocalExternDecl)
5256 NewVD->setLocalExternDecl();
5257
Richard Smithb4a9e862013-04-12 22:46:28 +00005258 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005259 if (NewVD->hasLocalStorage()) {
5260 // C++11 [dcl.stc]p4:
5261 // When thread_local is applied to a variable of block scope the
5262 // storage-class-specifier static is implied if it does not appear
5263 // explicitly.
5264 // Core issue: 'static' is not implied if the variable is declared
5265 // 'extern'.
5266 if (SCSpec == DeclSpec::SCS_unspecified &&
5267 TSCS == DeclSpec::TSCS_thread_local &&
5268 DC->isFunctionOrMethod())
5269 NewVD->setTSCSpec(TSCS);
5270 else
5271 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5272 diag::err_thread_non_global)
5273 << DeclSpec::getSpecifierName(TSCS);
5274 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005275 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5276 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005277 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005278 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005279 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005280
John McCallc87d9722013-04-02 02:48:58 +00005281 // C99 6.7.4p3
5282 // An inline definition of a function with external linkage shall
5283 // not contain a definition of a modifiable object with static or
5284 // thread storage duration...
5285 // We only apply this when the function is required to be defined
5286 // elsewhere, i.e. when the function is not 'extern inline'. Note
5287 // that a local variable with thread storage duration still has to
5288 // be marked 'static'. Also note that it's possible to get these
5289 // semantics in C++ using __attribute__((gnu_inline)).
5290 if (SC == SC_Static && S->getFnParent() != 0 &&
5291 !NewVD->getType().isConstQualified()) {
5292 FunctionDecl *CurFD = getCurFunctionDecl();
5293 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5294 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5295 diag::warn_static_local_in_extern_inline);
5296 MaybeSuggestAddingStaticToDecl(CurFD);
5297 }
5298 }
5299
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005300 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005301 if (IsVariableTemplateSpecialization)
5302 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5303 << (IsPartialSpecialization ? 1 : 0)
5304 << FixItHint::CreateRemoval(
5305 D.getDeclSpec().getModulePrivateSpecLoc());
5306 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005307 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5308 << 2
5309 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005310 else if (NewVD->hasLocalStorage())
5311 Diag(NewVD->getLocation(), diag::err_module_private_local)
5312 << 0 << NewVD->getDeclName()
5313 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5314 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005315 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005316 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005317 if (NewTemplate)
5318 NewTemplate->setModulePrivate();
5319 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005320 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005321
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005322 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005323 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005324
Richard Smith848e1f12013-02-01 08:12:08 +00005325 if (NewVD->hasAttrs())
5326 CheckAlignasUnderalignment(NewVD);
5327
Peter Collingbournec6b08572012-08-28 20:37:50 +00005328 if (getLangOpts().CUDA) {
5329 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5330 // storage [duration]."
5331 if (SC == SC_None && S->getFnParent() != 0 &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005332 (NewVD->hasAttr<CUDASharedAttr>() ||
5333 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005334 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005335 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005336 }
5337
John McCall31168b02011-06-15 23:02:42 +00005338 // In auto-retain/release, infer strong retension for variables of
5339 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005340 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005341 NewVD->setInvalidDecl();
5342
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005343 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005344 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005345 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005346 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005347 StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00005348 if (S->getFnParent() != 0) {
5349 switch (SC) {
5350 case SC_None:
5351 case SC_Auto:
5352 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5353 break;
5354 case SC_Register:
Douglas Gregore8bbc122011-09-02 00:18:52 +00005355 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005356 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5357 break;
5358 case SC_Static:
5359 case SC_Extern:
5360 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005361 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005362 break;
5363 }
5364 }
5365
5366 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005367 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005368 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5369 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5370 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5371 if (I != ExtnameUndeclaredIdentifiers.end()) {
5372 NewVD->addAttr(I->second);
5373 ExtnameUndeclaredIdentifiers.erase(I);
5374 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005375 }
5376
John McCalla2a3f7d2010-03-16 21:48:18 +00005377 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005378 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005379 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005380
John McCall1f82f242009-11-18 22:49:29 +00005381 // Don't consider existing declarations that are in a different
5382 // scope and are out-of-semantic-context declarations (if the new
5383 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005384 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5385 D.getCXXScopeSpec().isNotEmpty() ||
5386 IsExplicitSpecialization ||
5387 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005388
Richard Smith1c34fb72013-08-13 18:18:50 +00005389 // Check whether the previous declaration is in the same block scope. This
5390 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5391 if (getLangOpts().CPlusPlus &&
5392 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5393 NewVD->setPreviousDeclInSameBlockScope(
5394 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005395 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005396
David Blaikiebbafb8a2012-03-11 07:00:24 +00005397 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005398 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5399 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005400 // If this is an explicit specialization of a static data member, check it.
5401 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5402 CheckMemberSpecialization(NewVD, Previous))
5403 NewVD->setInvalidDecl();
5404
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005405 // Merge the decl with the existing one if appropriate.
5406 if (!Previous.empty()) {
5407 if (Previous.isSingleResult() &&
5408 isa<FieldDecl>(Previous.getFoundDecl()) &&
5409 D.getCXXScopeSpec().isSet()) {
5410 // The user tried to define a non-static data member
5411 // out-of-line (C++ [dcl.meaning]p1).
5412 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5413 << D.getCXXScopeSpec().getRange();
5414 Previous.clear();
5415 NewVD->setInvalidDecl();
5416 }
5417 } else if (D.getCXXScopeSpec().isSet()) {
5418 // No previous declaration in the qualifying scope.
5419 Diag(D.getIdentifierLoc(), diag::err_no_member)
5420 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005421 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005422 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005423 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005424
Richard Smithbeef3452014-01-16 23:39:20 +00005425 if (!IsVariableTemplateSpecialization)
5426 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005427
Richard Smithbeef3452014-01-16 23:39:20 +00005428 if (NewTemplate) {
5429 VarTemplateDecl *PrevVarTemplate =
5430 NewVD->getPreviousDecl()
5431 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5432 : 0;
5433
5434 // Check the template parameter list of this declaration, possibly
5435 // merging in the template parameter list from the previous variable
5436 // template declaration.
5437 if (CheckTemplateParameterList(
5438 TemplateParams,
5439 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5440 : 0,
5441 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5442 DC->isDependentContext())
5443 ? TPC_ClassTemplateMember
5444 : TPC_VarTemplate))
5445 NewVD->setInvalidDecl();
5446
5447 // If we are providing an explicit specialization of a static variable
5448 // template, make a note of that.
5449 if (PrevVarTemplate &&
5450 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5451 PrevVarTemplate->setMemberSpecialization();
5452 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005453 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005454
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005455 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005456
Richard Smithac974a32013-06-30 09:48:50 +00005457 // If this is the first declaration of an extern C variable, update
5458 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005459 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005460 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005461 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005462
Reid Klecknerd8110b62013-09-10 20:14:30 +00005463 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005464 Decl *ManglingContextDecl;
5465 if (MangleNumberingContext *MCtx =
5466 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5467 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005468 Context.setManglingNumber(
5469 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005470 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005471 }
5472 }
5473
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005474 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005475 if (NewVD->isInvalidDecl())
5476 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005477 ActOnDocumentableDecl(NewTemplate);
5478 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005479 }
5480
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005481 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005482}
5483
John McCalldf8b37c2010-03-22 09:20:08 +00005484/// \brief Diagnose variable or built-in function shadowing. Implements
5485/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005486///
John McCalldf8b37c2010-03-22 09:20:08 +00005487/// This method is called whenever a VarDecl is added to a "useful"
5488/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005489///
John McCall2d8c7602010-03-20 04:12:52 +00005490/// \param S the scope in which the shadowing name is being declared
5491/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005492///
John McCalldf8b37c2010-03-22 09:20:08 +00005493void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005494 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005495 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005496 DiagnosticsEngine::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00005497 return;
5498
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005499 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005500 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005501 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005502
5503 DeclContext *NewDC = D->getDeclContext();
5504
John McCall2d8c7602010-03-20 04:12:52 +00005505 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005506 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005507 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005508
John McCalla2a3f7d2010-03-16 21:48:18 +00005509 NamedDecl* ShadowedDecl = R.getFoundDecl();
5510 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5511 return;
5512
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005513 // Fields are not shadowed by variables in C++ static methods.
5514 if (isa<FieldDecl>(ShadowedDecl))
5515 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5516 if (MD->isStatic())
5517 return;
5518
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005519 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5520 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005521 // For shadowing external vars, make sure that we point to the global
5522 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005523 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005524 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005525 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005526 break;
5527 }
5528 }
5529
5530 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5531
John McCall2d8c7602010-03-20 04:12:52 +00005532 // Only warn about certain kinds of shadowing for class members.
5533 if (NewDC && NewDC->isRecord()) {
5534 // In particular, don't warn about shadowing non-class members.
5535 if (!OldDC->isRecord())
5536 return;
5537
5538 // TODO: should we warn about static data members shadowing
5539 // static data members from base classes?
5540
5541 // TODO: don't diagnose for inaccessible shadowed members.
5542 // This is hard to do perfectly because we might friend the
5543 // shadowing context, but that's just a false negative.
5544 }
5545
5546 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005547 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005548 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005549 if (isa<FieldDecl>(ShadowedDecl))
5550 Kind = 3; // field
5551 else
5552 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005553 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005554 Kind = 1; // global
5555 else
5556 Kind = 0; // local
5557
John McCall2d8c7602010-03-20 04:12:52 +00005558 DeclarationName Name = R.getLookupName();
5559
John McCalla2a3f7d2010-03-16 21:48:18 +00005560 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005561 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5562 return;
John McCall2d8c7602010-03-20 04:12:52 +00005563 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005564 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5565}
5566
John McCalldf8b37c2010-03-22 09:20:08 +00005567/// \brief Check -Wshadow without the advantage of a previous lookup.
5568void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005569 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00005570 DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005571 return;
5572
John McCalldf8b37c2010-03-22 09:20:08 +00005573 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5574 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5575 LookupName(R, S);
5576 CheckShadow(S, D, R);
5577}
5578
Richard Smithac974a32013-06-30 09:48:50 +00005579/// Check for conflict between this global or extern "C" declaration and
5580/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005581template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005582static bool checkGlobalOrExternCConflict(
5583 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5584 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5585 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005586
Richard Smithac974a32013-06-30 09:48:50 +00005587 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5588 // The common case: this global doesn't conflict with any extern "C"
5589 // declaration.
5590 return false;
5591 }
5592
5593 if (Prev) {
5594 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5595 // Both the old and new declarations have C language linkage. This is a
5596 // redeclaration.
5597 Previous.clear();
5598 Previous.addDecl(Prev);
5599 return true;
5600 }
5601
5602 // This is a global, non-extern "C" declaration, and there is a previous
5603 // non-global extern "C" declaration. Diagnose if this is a variable
5604 // declaration.
5605 if (!isa<VarDecl>(ND))
5606 return false;
5607 } else {
5608 // The declaration is extern "C". Check for any declaration in the
5609 // translation unit which might conflict.
5610 if (IsGlobal) {
5611 // We have already performed the lookup into the translation unit.
5612 IsGlobal = false;
5613 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5614 I != E; ++I) {
5615 if (isa<VarDecl>(*I)) {
5616 Prev = *I;
5617 break;
5618 }
5619 }
5620 } else {
5621 DeclContext::lookup_result R =
5622 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5623 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5624 I != E; ++I) {
5625 if (isa<VarDecl>(*I)) {
5626 Prev = *I;
5627 break;
5628 }
5629 // FIXME: If we have any other entity with this name in global scope,
5630 // the declaration is ill-formed, but that is a defect: it breaks the
5631 // 'stat' hack, for instance. Only variables can have mangled name
5632 // clashes with extern "C" declarations, so only they deserve a
5633 // diagnostic.
5634 }
5635 }
5636
5637 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005638 return false;
5639 }
5640
Richard Smithac974a32013-06-30 09:48:50 +00005641 // Use the first declaration's location to ensure we point at something which
5642 // is lexically inside an extern "C" linkage-spec.
5643 assert(Prev && "should have found a previous declaration to diagnose");
5644 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005645 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005646 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005647 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005648
5649 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5650 << IsGlobal << ND;
5651 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5652 << IsGlobal;
5653 return false;
5654}
5655
5656/// Apply special rules for handling extern "C" declarations. Returns \c true
5657/// if we have found that this is a redeclaration of some prior entity.
5658///
5659/// Per C++ [dcl.link]p6:
5660/// Two declarations [for a function or variable] with C language linkage
5661/// with the same name that appear in different scopes refer to the same
5662/// [entity]. An entity with C language linkage shall not be declared with
5663/// the same name as an entity in global scope.
5664template<typename T>
5665static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5666 LookupResult &Previous) {
5667 if (!S.getLangOpts().CPlusPlus) {
5668 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005669 // variable declared in function scope. We don't need this in C++, because
5670 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005671 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5672 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5673 Previous.clear();
5674 Previous.addDecl(Prev);
5675 return true;
5676 }
5677 }
5678 return false;
5679 }
5680
5681 // A declaration in the translation unit can conflict with an extern "C"
5682 // declaration.
5683 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5684 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5685
5686 // An extern "C" declaration can conflict with a declaration in the
5687 // translation unit or can be a redeclaration of an extern "C" declaration
5688 // in another scope.
5689 if (isIncompleteDeclExternC(S,ND))
5690 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5691
5692 // Neither global nor extern "C": nothing to do.
5693 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005694}
5695
Richard Smith27d807c2013-04-30 13:56:41 +00005696void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005697 // If the decl is already known invalid, don't check it.
5698 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005699 return;
Mike Stump11289f42009-09-09 15:08:12 +00005700
Abramo Bagnara341ab732012-11-08 14:44:42 +00005701 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5702 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005703
Richard Smith27d807c2013-04-30 13:56:41 +00005704 // Defer checking an 'auto' type until its initializer is attached.
5705 if (T->isUndeducedType())
5706 return;
5707
John McCall8b07ec22010-05-15 11:32:37 +00005708 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005709 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5710 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005711 T = Context.getObjCObjectPointerType(T);
5712 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005713 }
Mike Stump11289f42009-09-09 15:08:12 +00005714
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005715 // Emit an error if an address space was applied to decl with local storage.
5716 // This includes arrays of objects with address space qualifiers, but not
5717 // automatic variables that point to other address spaces.
5718 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005719 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005720 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005721 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005722 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005723 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005724
Tanya Lattner713eef42013-04-05 20:14:50 +00005725 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5726 // __constant address space.
5727 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5728 && T.getAddressSpace() != LangAS::opencl_constant
5729 && !T->isSamplerT()){
5730 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5731 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005732 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005733 }
5734
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005735 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5736 // scope.
5737 if ((getLangOpts().OpenCLVersion >= 120)
5738 && NewVD->isStaticLocal()) {
5739 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5740 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005741 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005742 }
5743
Mike Stumpca5ae662009-04-14 00:57:29 +00005744 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005745 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005746 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005747 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005748 else {
5749 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005750 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005751 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005752 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005753
Chris Lattner9fecd742009-04-19 05:21:20 +00005754 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005755 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005756 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005757 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005758
Chris Lattner9fecd742009-04-19 05:21:20 +00005759 if ((isVM && NewVD->hasLinkage()) ||
5760 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005761 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005762 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005763 TypeSourceInfo *FixedTInfo =
5764 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5765 SizeIsNegative, Oversized);
5766 if (FixedTInfo == 0 && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005767 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005768 // FIXME: This won't give the correct result for
5769 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005770 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005771
Anders Carlsson6c885802009-02-28 21:56:50 +00005772 if (NewVD->isFileVarDecl())
5773 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005774 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005775 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005776 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005777 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005778 else
5779 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005780 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005781 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005782 return;
Mike Stump11289f42009-09-09 15:08:12 +00005783 }
5784
Abramo Bagnara341ab732012-11-08 14:44:42 +00005785 if (FixedTInfo == 0) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005786 if (NewVD->isFileVarDecl())
5787 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5788 else
5789 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005790 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005791 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005794 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005795 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005796 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005797 }
5798
David Majnemer0ffa3312013-05-29 00:56:45 +00005799 if (T->isVoidType()) {
5800 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5801 // of objects and functions.
5802 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5803 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5804 << T;
5805 NewVD->setInvalidDecl();
5806 return;
5807 }
Richard Smith27d807c2013-04-30 13:56:41 +00005808 }
5809
5810 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5811 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5812 NewVD->setInvalidDecl();
5813 return;
5814 }
5815
5816 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5817 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5818 NewVD->setInvalidDecl();
5819 return;
5820 }
5821
5822 if (NewVD->isConstexpr() && !T->isDependentType() &&
5823 RequireLiteralType(NewVD->getLocation(), T,
5824 diag::err_constexpr_var_non_literal)) {
5825 // Can't perform this check until the type is deduced.
5826 NewVD->setInvalidDecl();
5827 return;
5828 }
5829}
5830
5831/// \brief Perform semantic checking on a newly-created variable
5832/// declaration.
5833///
5834/// This routine performs all of the type-checking required for a
5835/// variable declaration once it has been built. It is used both to
5836/// check variables after they have been parsed and their declarators
5837/// have been translated into a declaration, and to check variables
5838/// that have been instantiated from a template.
5839///
5840/// Sets NewVD->isInvalidDecl() if an error was encountered.
5841///
5842/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005843bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005844 CheckVariableDeclarationType(NewVD);
5845
5846 // If the decl is already known invalid, don't check it.
5847 if (NewVD->isInvalidDecl())
5848 return false;
5849
John McCallb65e8fe2013-04-01 18:34:28 +00005850 // If we did not find anything by this name, look for a non-visible
5851 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00005852 if (Previous.empty() &&
5853 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00005854 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005855
Douglas Gregor3552dab2013-01-09 00:47:56 +00005856 // Filter out any non-conflicting previous declarations.
5857 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5858
John McCall1f82f242009-11-18 22:49:29 +00005859 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00005860 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005861 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005862 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005863 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005864}
5865
Douglas Gregor36d1b142009-10-06 17:59:45 +00005866/// \brief Data used with FindOverriddenMethod
5867struct FindOverriddenMethodData {
5868 Sema *S;
5869 CXXMethodDecl *Method;
5870};
5871
5872/// \brief Member lookup function that determines whether a given C++
5873/// method overrides a method in a base class, to be used with
5874/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00005875static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00005876 CXXBasePath &Path,
5877 void *UserData) {
5878 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00005879
Douglas Gregor36d1b142009-10-06 17:59:45 +00005880 FindOverriddenMethodData *Data
5881 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00005882
5883 DeclarationName Name = Data->Method->getDeclName();
5884
5885 // FIXME: Do we care about other names here too?
5886 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00005887 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00005888 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5889 CanQualType CT = Data->S->Context.getCanonicalType(T);
5890
Anders Carlsson5a4f7722009-11-27 01:26:58 +00005891 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00005892 }
5893
5894 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005895 !Path.Decls.empty();
5896 Path.Decls = Path.Decls.slice(1)) {
5897 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00005898 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5899 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00005900 return true;
5901 }
5902 }
5903
5904 return false;
5905}
5906
David Blaikie7e414262012-10-17 00:47:58 +00005907namespace {
5908 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5909}
5910/// \brief Report an error regarding overriding, along with any relevant
5911/// overriden methods.
5912///
5913/// \param DiagID the primary error to report.
5914/// \param MD the overriding method.
5915/// \param OEK which overrides to include as notes.
5916static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5917 OverrideErrorKind OEK = OEK_All) {
5918 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5919 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5920 E = MD->end_overridden_methods();
5921 I != E; ++I) {
5922 // This check (& the OEK parameter) could be replaced by a predicate, but
5923 // without lambdas that would be overkill. This is still nicer than writing
5924 // out the diag loop 3 times.
5925 if ((OEK == OEK_All) ||
5926 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5927 (OEK == OEK_Deleted && (*I)->isDeleted()))
5928 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5929 }
5930}
5931
Sebastian Redld5b24532009-11-18 21:51:29 +00005932/// AddOverriddenMethods - See if a method overrides any in the base classes,
5933/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005934bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00005935 // Look for virtual methods in base classes that this method might override.
5936 CXXBasePaths Paths;
5937 FindOverriddenMethodData Data;
5938 Data.Method = MD;
5939 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00005940 bool hasDeletedOverridenMethods = false;
5941 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005942 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00005943 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5944 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5945 E = Paths.found_decls_end(); I != E; ++I) {
5946 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00005947 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00005948 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00005949 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00005950 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00005951 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00005952 hasDeletedOverridenMethods |= OldMD->isDeleted();
5953 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005954 AddedAny = true;
5955 }
Sebastian Redld5b24532009-11-18 21:51:29 +00005956 }
5957 }
5958 }
David Blaikie7e414262012-10-17 00:47:58 +00005959
5960 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5961 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5962 }
5963 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5964 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5965 }
5966
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005967 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00005968}
5969
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005970namespace {
5971 // Struct for holding all of the extra arguments needed by
5972 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5973 struct ActOnFDArgs {
5974 Scope *S;
5975 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005976 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00005977 bool AddToScope;
5978 };
5979}
5980
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005981namespace {
5982
5983// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005984// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00005985class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5986 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005987 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5988 CXXRecordDecl *Parent)
5989 : Context(Context), OriginalFD(TypoFD),
5990 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005991
Craig Toppere14c0f82014-03-12 04:55:44 +00005992 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00005993 if (candidate.getEditDistance() == 0)
5994 return false;
5995
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005996 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00005997 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5998 CDeclEnd = candidate.end();
5999 CDecl != CDeclEnd; ++CDecl) {
6000 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6001
6002 if (FD && !FD->hasBody() &&
6003 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6005 CXXRecordDecl *Parent = MD->getParent();
6006 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6007 return true;
6008 } else if (!ExpectedParent) {
6009 return true;
6010 }
6011 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006012 }
6013
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006014 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006015 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006016
6017 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006018 ASTContext &Context;
6019 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006020 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006021};
6022
6023}
6024
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006025/// \brief Generate diagnostics for an invalid function redeclaration.
6026///
6027/// This routine handles generating the diagnostic messages for an invalid
6028/// function redeclaration, including finding possible similar declarations
6029/// or performing typo correction if there are no previous declarations with
6030/// the same name.
6031///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006032/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006033/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006034static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006035 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006036 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006037 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006038 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006039 SmallVector<unsigned, 1> MismatchedParams;
6040 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006041 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006042 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006043 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6044 : diag::err_member_decl_does_not_match;
6045 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6046 IsLocalFriend ? Sema::LookupLocalFriendName
6047 : Sema::LookupOrdinaryName,
6048 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006049
6050 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006051 if (IsLocalFriend)
6052 SemaRef.LookupName(Prev, S);
6053 else
6054 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006055 assert(!Prev.isAmbiguous() &&
6056 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006057 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006058 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6059 MD ? MD->getParent() : 0);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006060 if (!Prev.empty()) {
6061 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6062 Func != FuncEnd; ++Func) {
6063 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006064 if (FD &&
6065 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006066 // Add 1 to the index so that 0 can mean the mismatch didn't
6067 // involve a parameter
6068 unsigned ParamNum =
6069 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6070 NearMatches.push_back(std::make_pair(FD, ParamNum));
6071 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006072 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006073 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006074 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006075 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6076 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6077 IsLocalFriend ? 0 : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006078 // Set up everything for the call to ActOnFunctionDeclarator
6079 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6080 ExtraArgs.D.getIdentifierLoc());
6081 Previous.clear();
6082 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006083 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6084 CDeclEnd = Correction.end();
6085 CDecl != CDeclEnd; ++CDecl) {
6086 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006087 if (FD && !FD->hasBody() &&
6088 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006089 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006090 }
6091 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006092 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006093
6094 NamedDecl *Result;
6095 // Retry building the function declaration with the new previous
6096 // declarations, and with errors suppressed.
6097 {
6098 // Trap errors.
6099 Sema::SFINAETrap Trap(SemaRef);
6100
6101 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6102 // pieces need to verify the typo-corrected C++ declaration and hopefully
6103 // eliminate the need for the parameter pack ExtraArgs.
6104 Result = SemaRef.ActOnFunctionDeclarator(
6105 ExtraArgs.S, ExtraArgs.D,
6106 Correction.getCorrectionDecl()->getDeclContext(),
6107 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6108 ExtraArgs.AddToScope);
6109
6110 if (Trap.hasErrorOccurred())
6111 Result = 0;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006112 }
Richard Smithf9b15102013-08-17 00:46:16 +00006113
6114 if (Result) {
6115 // Determine which correction we picked.
6116 Decl *Canonical = Result->getCanonicalDecl();
6117 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6118 I != E; ++I)
6119 if ((*I)->getCanonicalDecl() == Canonical)
6120 Correction.setCorrectionDecl(*I);
6121
6122 SemaRef.diagnoseTypo(
6123 Correction,
6124 SemaRef.PDiag(IsLocalFriend
6125 ? diag::err_no_matching_local_friend_suggest
6126 : diag::err_member_decl_does_not_match_suggest)
6127 << Name << NewDC << IsDefinition);
6128 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006129 }
Richard Smithf9b15102013-08-17 00:46:16 +00006130
6131 // Pretend the typo correction never occurred
6132 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6133 ExtraArgs.D.getIdentifierLoc());
6134 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6135 Previous.clear();
6136 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006137 }
6138
Richard Smithf9b15102013-08-17 00:46:16 +00006139 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6140 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006141
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006142 bool NewFDisConst = false;
6143 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006144 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006145
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006146 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006147 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6148 NearMatch != NearMatchEnd; ++NearMatch) {
6149 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006150 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6151 bool FDisConst = MD && MD->isConst();
6152 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006153
Richard Smith541b38b2013-09-20 01:15:31 +00006154 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006155 if (unsigned Idx = NearMatch->second) {
6156 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006157 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6158 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006159 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6160 : diag::note_local_decl_close_param_match)
6161 << Idx << FDParam->getType()
6162 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006163 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006164 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006165 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006166 } else
Richard Smith114394f2013-08-09 04:35:01 +00006167 SemaRef.Diag(FD->getLocation(),
6168 IsMember ? diag::note_member_def_close_match
6169 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006170 }
Richard Smithf9b15102013-08-17 00:46:16 +00006171 return 0;
John McCallf7cfb222010-10-13 05:45:15 +00006172}
6173
David Blaikie30d15442011-10-19 22:56:21 +00006174static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6175 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006176 switch (D.getDeclSpec().getStorageClassSpec()) {
6177 default: llvm_unreachable("Unknown storage class!");
6178 case DeclSpec::SCS_auto:
6179 case DeclSpec::SCS_register:
6180 case DeclSpec::SCS_mutable:
6181 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6182 diag::err_typecheck_sclass_func);
6183 D.setInvalidType();
6184 break;
6185 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006186 case DeclSpec::SCS_extern:
6187 if (D.getDeclSpec().isExternInLinkageSpec())
6188 return SC_None;
6189 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006190 case DeclSpec::SCS_static: {
6191 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6192 // C99 6.7.1p5:
6193 // The declaration of an identifier for a function that has
6194 // block scope shall have no explicit storage-class specifier
6195 // other than extern
6196 // See also (C++ [dcl.stc]p4).
6197 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6198 diag::err_static_block_func);
6199 break;
6200 } else
6201 return SC_Static;
6202 }
6203 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6204 }
6205
6206 // No explicit storage class has already been returned
6207 return SC_None;
6208}
6209
6210static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6211 DeclContext *DC, QualType &R,
6212 TypeSourceInfo *TInfo,
6213 FunctionDecl::StorageClass SC,
6214 bool &IsVirtualOkay) {
6215 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6216 DeclarationName Name = NameInfo.getName();
6217
6218 FunctionDecl *NewFD = 0;
6219 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006220
David Blaikiebbafb8a2012-03-11 07:00:24 +00006221 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006222 // Determine whether the function was written with a
6223 // prototype. This true when:
6224 // - there is a prototype in the declarator, or
6225 // - the type R of the function is some kind of typedef or other reference
6226 // to a type name (which eventually refers to a function type).
6227 bool HasPrototype =
6228 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6229 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6230
David Blaikie30d15442011-10-19 22:56:21 +00006231 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006232 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006233 TInfo, SC, isInline,
6234 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006235 if (D.isInvalidType())
6236 NewFD->setInvalidDecl();
6237
6238 // Set the lexical context.
6239 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6240
6241 return NewFD;
6242 }
6243
6244 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6245 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6246
6247 // Check that the return type is not an abstract class type.
6248 // For record types, this is done by the AbstractClassUsageDiagnoser once
6249 // the class has been completely parsed.
6250 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006251 SemaRef.RequireNonAbstractType(
6252 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6253 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006254 D.setInvalidType();
6255
6256 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6257 // This is a C++ constructor declaration.
6258 assert(DC->isRecord() &&
6259 "Constructors can only be declared in a member context");
6260
6261 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6262 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006263 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006264 R, TInfo, isExplicit, isInline,
6265 /*isImplicitlyDeclared=*/false,
6266 isConstexpr);
6267
6268 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6269 // This is a C++ destructor declaration.
6270 if (DC->isRecord()) {
6271 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6272 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6273 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6274 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006275 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006276 NameInfo, R, TInfo, isInline,
6277 /*isImplicitlyDeclared=*/false);
6278
6279 // If the class is complete, then we now create the implicit exception
6280 // specification. If the class is incomplete or dependent, we can't do
6281 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006282 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006283 Record->getDefinition() && !Record->isBeingDefined() &&
6284 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6285 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6286 }
6287
6288 IsVirtualOkay = true;
6289 return NewDD;
6290
6291 } else {
6292 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6293 D.setInvalidType();
6294
6295 // Create a FunctionDecl to satisfy the function definition parsing
6296 // code path.
6297 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006298 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006299 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006300 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006301 /*hasPrototype=*/true, isConstexpr);
6302 }
6303
6304 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6305 if (!DC->isRecord()) {
6306 SemaRef.Diag(D.getIdentifierLoc(),
6307 diag::err_conv_function_not_member);
6308 return 0;
6309 }
6310
6311 SemaRef.CheckConversionDeclarator(D, R, SC);
6312 IsVirtualOkay = true;
6313 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006314 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006315 R, TInfo, isInline, isExplicit,
6316 isConstexpr, SourceLocation());
6317
6318 } else if (DC->isRecord()) {
6319 // If the name of the function is the same as the name of the record,
6320 // then this must be an invalid constructor that has a return type.
6321 // (The parser checks for a return type and makes the declarator a
6322 // constructor if it has no return type).
6323 if (Name.getAsIdentifierInfo() &&
6324 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6325 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6326 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6327 << SourceRange(D.getIdentifierLoc());
6328 return 0;
6329 }
6330
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006331 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006332 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6333 cast<CXXRecordDecl>(DC),
6334 D.getLocStart(), NameInfo, R,
6335 TInfo, SC, isInline,
6336 isConstexpr, SourceLocation());
6337 IsVirtualOkay = !Ret->isStatic();
6338 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006339 } else {
6340 // Determine whether the function was written with a
6341 // prototype. This true when:
6342 // - we're in C++ (where every function has a prototype),
6343 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006344 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006345 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006346 true/*HasPrototype*/, isConstexpr);
6347 }
6348}
6349
Matt Arsenaultefb38192013-07-23 01:23:36 +00006350enum OpenCLParamType {
6351 ValidKernelParam,
6352 PtrPtrKernelParam,
6353 PtrKernelParam,
6354 InvalidKernelParam,
6355 RecordKernelParam
6356};
6357
6358static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6359 if (PT->isPointerType()) {
6360 QualType PointeeType = PT->getPointeeType();
6361 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6362 }
6363
6364 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6365 // be used as builtin types.
6366
6367 if (PT->isImageType())
6368 return PtrKernelParam;
6369
6370 if (PT->isBooleanType())
6371 return InvalidKernelParam;
6372
6373 if (PT->isEventT())
6374 return InvalidKernelParam;
6375
6376 if (PT->isHalfType())
6377 return InvalidKernelParam;
6378
6379 if (PT->isRecordType())
6380 return RecordKernelParam;
6381
6382 return ValidKernelParam;
6383}
6384
6385static void checkIsValidOpenCLKernelParameter(
6386 Sema &S,
6387 Declarator &D,
6388 ParmVarDecl *Param,
6389 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6390 QualType PT = Param->getType();
6391
6392 // Cache the valid types we encounter to avoid rechecking structs that are
6393 // used again
6394 if (ValidTypes.count(PT.getTypePtr()))
6395 return;
6396
6397 switch (getOpenCLKernelParameterType(PT)) {
6398 case PtrPtrKernelParam:
6399 // OpenCL v1.2 s6.9.a:
6400 // A kernel function argument cannot be declared as a
6401 // pointer to a pointer type.
6402 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6403 D.setInvalidType();
6404 return;
6405
6406 // OpenCL v1.2 s6.9.k:
6407 // Arguments to kernel functions in a program cannot be declared with the
6408 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6409 // uintptr_t or a struct and/or union that contain fields declared to be
6410 // one of these built-in scalar types.
6411
6412 case InvalidKernelParam:
6413 // OpenCL v1.2 s6.8 n:
6414 // A kernel function argument cannot be declared
6415 // of event_t type.
6416 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6417 D.setInvalidType();
6418 return;
6419
6420 case PtrKernelParam:
6421 case ValidKernelParam:
6422 ValidTypes.insert(PT.getTypePtr());
6423 return;
6424
6425 case RecordKernelParam:
6426 break;
6427 }
6428
6429 // Track nested structs we will inspect
6430 SmallVector<const Decl *, 4> VisitStack;
6431
6432 // Track where we are in the nested structs. Items will migrate from
6433 // VisitStack to HistoryStack as we do the DFS for bad field.
6434 SmallVector<const FieldDecl *, 4> HistoryStack;
6435 HistoryStack.push_back((const FieldDecl *) 0);
6436
6437 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6438 VisitStack.push_back(PD);
6439
6440 assert(VisitStack.back() && "First decl null?");
6441
6442 do {
6443 const Decl *Next = VisitStack.pop_back_val();
6444 if (!Next) {
6445 assert(!HistoryStack.empty());
6446 // Found a marker, we have gone up a level
6447 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6448 ValidTypes.insert(Hist->getType().getTypePtr());
6449
6450 continue;
6451 }
6452
6453 // Adds everything except the original parameter declaration (which is not a
6454 // field itself) to the history stack.
6455 const RecordDecl *RD;
6456 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6457 HistoryStack.push_back(Field);
6458 RD = Field->getType()->castAs<RecordType>()->getDecl();
6459 } else {
6460 RD = cast<RecordDecl>(Next);
6461 }
6462
6463 // Add a null marker so we know when we've gone back up a level
6464 VisitStack.push_back((const Decl *) 0);
6465
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006466 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006467 QualType QT = FD->getType();
6468
6469 if (ValidTypes.count(QT.getTypePtr()))
6470 continue;
6471
6472 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6473 if (ParamType == ValidKernelParam)
6474 continue;
6475
6476 if (ParamType == RecordKernelParam) {
6477 VisitStack.push_back(FD);
6478 continue;
6479 }
6480
6481 // OpenCL v1.2 s6.9.p:
6482 // Arguments to kernel functions that are declared to be a struct or union
6483 // do not allow OpenCL objects to be passed as elements of the struct or
6484 // union.
6485 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6486 S.Diag(Param->getLocation(),
6487 diag::err_record_with_pointers_kernel_param)
6488 << PT->isUnionType()
6489 << PT;
6490 } else {
6491 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6492 }
6493
6494 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6495 << PD->getDeclName();
6496
6497 // We have an error, now let's go back up through history and show where
6498 // the offending field came from
6499 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6500 E = HistoryStack.end(); I != E; ++I) {
6501 const FieldDecl *OuterField = *I;
6502 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6503 << OuterField->getType();
6504 }
6505
6506 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6507 << QT->isPointerType()
6508 << QT;
6509 D.setInvalidType();
6510 return;
6511 }
6512 } while (!VisitStack.empty());
6513}
6514
Mike Stump11289f42009-09-09 15:08:12 +00006515NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006516Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006517 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006518 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006519 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006520 QualType R = TInfo->getType();
6521
Zhongxing Xubece5d62009-01-16 01:13:29 +00006522 assert(R.getTypePtr()->isFunctionType());
6523
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006524 // TODO: consider using NameInfo for diagnostic.
6525 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6526 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006527 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006528
Richard Smithb4a9e862013-04-12 22:46:28 +00006529 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6530 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6531 diag::err_invalid_thread)
6532 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006533
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006534 if (D.isFirstDeclarationOfMember())
6535 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006536
Douglas Gregor513e63c2010-12-10 19:28:19 +00006537 bool isFriend = false;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006538 FunctionTemplateDecl *FunctionTemplate = 0;
6539 bool isExplicitSpecialization = false;
6540 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006541
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006542 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006543 bool HasExplicitTemplateArgs = false;
6544 TemplateArgumentListInfo TemplateArgs;
6545
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006546 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006547
Richard Smith541b38b2013-09-20 01:15:31 +00006548 DeclContext *OriginalDC = DC;
6549 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6550
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006551 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6552 isVirtualOkay);
6553 if (!NewFD) return 0;
6554
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006555 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6556 NewFD->setTopLevelDeclInObjCContainer();
6557
Richard Smith541b38b2013-09-20 01:15:31 +00006558 // Set the lexical context. If this is a function-scope declaration, or has a
6559 // C++ scope specifier, or is the object of a friend declaration, the lexical
6560 // context will be different from the semantic context.
6561 NewFD->setLexicalDeclContext(CurContext);
6562
6563 if (IsLocalExternDecl)
6564 NewFD->setLocalExternDecl();
6565
David Blaikiebbafb8a2012-03-11 07:00:24 +00006566 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006567 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006568 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6569 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006570 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006571 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006572 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006573 // C++ [class.friend]p5
6574 // A function can be defined in a friend declaration of a
6575 // class . . . . Such a function is implicitly inline.
6576 NewFD->setImplicitlyInline();
6577 }
6578
John McCalldb632ac2012-09-25 07:32:39 +00006579 // If this is a method defined in an __interface, and is not a constructor
6580 // or an overloaded operator, then set the pure flag (isVirtual will already
6581 // return true).
6582 if (const CXXRecordDecl *Parent =
6583 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6584 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006585 NewFD->setPure(true);
6586 }
6587
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006588 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006589 isExplicitSpecialization = false;
6590 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006591 if (D.isInvalidType())
6592 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006593
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006594 // Match up the template parameter lists with the scope specifier, then
6595 // determine whether we have a template or a template specialization.
6596 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006597 if (TemplateParameterList *TemplateParams =
6598 MatchTemplateParametersToScopeSpecifier(
6599 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6600 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6601 isExplicitSpecialization, Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006602 if (TemplateParams->size() > 0) {
6603 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006604
Abramo Bagnara60804e12011-03-18 15:16:37 +00006605 // Check that we can declare a template here.
6606 if (CheckTemplateDeclScope(S, TemplateParams))
6607 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006608
Abramo Bagnara60804e12011-03-18 15:16:37 +00006609 // A destructor cannot be a template.
6610 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6611 Diag(NewFD->getLocation(), diag::err_destructor_template);
6612 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00006613 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006614
6615 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006616 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006617 // now that we know what the current instantiation is.
6618 if (DC->isDependentContext()) {
6619 ContextRAII SavedContext(*this, DC);
6620 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6621 Invalid = true;
6622 }
6623
John McCall1f0479e2010-03-24 08:27:58 +00006624
Abramo Bagnara60804e12011-03-18 15:16:37 +00006625 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6626 NewFD->getLocation(),
6627 Name, TemplateParams,
6628 NewFD);
6629 FunctionTemplate->setLexicalDeclContext(CurContext);
6630 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6631
6632 // For source fidelity, store the other template param lists.
6633 if (TemplateParamLists.size() > 1) {
6634 NewFD->setTemplateParameterListsInfo(Context,
6635 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006636 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006637 }
6638 } else {
6639 // This is a function template specialization.
6640 isFunctionTemplateSpecialization = true;
6641 // For source fidelity, store all the template param lists.
6642 NewFD->setTemplateParameterListsInfo(Context,
6643 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006644 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006645
6646 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6647 if (isFriend) {
6648 // We want to remove the "template<>", found here.
6649 SourceRange RemoveRange = TemplateParams->getSourceRange();
6650
6651 // If we remove the template<> and the name is not a
6652 // template-id, we're actually silently creating a problem:
6653 // the friend declaration will refer to an untemplated decl,
6654 // and clearly the user wants a template specialization. So
6655 // we need to insert '<>' after the name.
6656 SourceLocation InsertLoc;
6657 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6658 InsertLoc = D.getName().getSourceRange().getEnd();
6659 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6660 }
6661
6662 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6663 << Name << RemoveRange
6664 << FixItHint::CreateRemoval(RemoveRange)
6665 << FixItHint::CreateInsertion(InsertLoc, "<>");
6666 }
6667 }
6668 }
6669 else {
6670 // All template param lists were matched against the scope specifier:
6671 // this is NOT (an explicit specialization of) a template.
6672 if (TemplateParamLists.size() > 0)
6673 // For source fidelity, store all the template param lists.
6674 NewFD->setTemplateParameterListsInfo(Context,
6675 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006676 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006677 }
6678
6679 if (Invalid) {
6680 NewFD->setInvalidDecl();
6681 if (FunctionTemplate)
6682 FunctionTemplate->setInvalidDecl();
6683 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006684
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006685 // C++ [dcl.fct.spec]p5:
6686 // The virtual specifier shall only be used in declarations of
6687 // nonstatic class member functions that appear within a
6688 // member-specification of a class declaration; see 10.3.
6689 //
6690 if (isVirtual && !NewFD->isInvalidDecl()) {
6691 if (!isVirtualOkay) {
6692 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6693 diag::err_virtual_non_function);
6694 } else if (!CurContext->isRecord()) {
6695 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006696 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6697 diag::err_virtual_out_of_class)
6698 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6699 } else if (NewFD->getDescribedFunctionTemplate()) {
6700 // C++ [temp.mem]p3:
6701 // A member function template shall not be virtual.
6702 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6703 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006704 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6705 } else {
6706 // Okay: Add virtual to the method.
6707 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006708 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006709
6710 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006711 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006712 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006713 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006714
Richard Smithc1564702013-11-15 02:58:23 +00006715 if (getLangOpts().CPlusPlus1y &&
6716 (NewFD->isDependentContext() ||
6717 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006718 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006719 // If the function template is referenced directly (for instance, as a
6720 // member of the current instantiation), pretend it has a dependent type.
6721 // This is not really justified by the standard, but is the only sane
6722 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006723 // FIXME: For a friend function, we have not marked the function as being
6724 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006725 const FunctionProtoType *FPT =
6726 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006727 QualType Result =
6728 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006729 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006730 FPT->getExtProtoInfo()));
6731 }
6732
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006733 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006734 // The inline specifier shall not appear on a block scope function
6735 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006736 if (isInline && !NewFD->isInvalidDecl()) {
6737 if (CurContext->isFunctionOrMethod()) {
6738 // 'inline' is not allowed on block scope function declaration.
6739 Diag(D.getDeclSpec().getInlineSpecLoc(),
6740 diag::err_inline_declaration_block_scope) << Name
6741 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6742 }
6743 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006744
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006745 // C++ [dcl.fct.spec]p6:
6746 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006747 // constructor or conversion function within its class definition;
6748 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006749 if (isExplicit && !NewFD->isInvalidDecl()) {
6750 if (!CurContext->isRecord()) {
6751 // 'explicit' was specified outside of the class.
6752 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6753 diag::err_explicit_out_of_class)
6754 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6755 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6756 !isa<CXXConversionDecl>(NewFD)) {
6757 // 'explicit' was specified on a function that wasn't a constructor
6758 // or conversion function.
6759 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6760 diag::err_explicit_non_ctor_or_conv_function)
6761 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6762 }
6763 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006764
Richard Smitha77a0a62011-08-15 21:04:07 +00006765 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006766 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006767 // are implicitly inline.
6768 NewFD->setImplicitlyInline();
6769
Richard Smith574f4f62013-01-14 05:37:29 +00006770 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006771 // be either constructors or to return a literal type. Therefore,
6772 // destructors cannot be declared constexpr.
6773 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006774 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006775 }
6776
Douglas Gregor26701a42011-09-09 02:06:17 +00006777 // If __module_private__ was specified, mark the function accordingly.
6778 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006779 if (isFunctionTemplateSpecialization) {
6780 SourceLocation ModulePrivateLoc
6781 = D.getDeclSpec().getModulePrivateSpecLoc();
6782 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6783 << 0
6784 << FixItHint::CreateRemoval(ModulePrivateLoc);
6785 } else {
6786 NewFD->setModulePrivate();
6787 if (FunctionTemplate)
6788 FunctionTemplate->setModulePrivate();
6789 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006790 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006791
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006792 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006793 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006794 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006795 FunctionTemplate->setAccess(AS_public);
6796 }
Richard Smith64017682013-07-17 23:53:16 +00006797 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006798 NewFD->setAccess(AS_public);
6799 }
6800
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006801 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006802 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6803 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006804 switch (D.getFunctionDefinitionKind()) {
6805 case FDK_Declaration:
6806 case FDK_Definition:
6807 break;
6808
6809 case FDK_Defaulted:
6810 NewFD->setDefaulted();
6811 break;
6812
6813 case FDK_Deleted:
6814 NewFD->setDeletedAsWritten();
6815 break;
6816 }
6817
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006818 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6819 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006820 // C++ [class.mfct]p2:
6821 // A member function may be defined (8.4) in its class definition, in
6822 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006823 NewFD->setImplicitlyInline();
6824 }
6825
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006826 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6827 !CurContext->isRecord()) {
6828 // C++ [class.static]p1:
6829 // A data or function member of a class may be declared static
6830 // in a class definition, in which case it is a static member of
6831 // the class.
6832
6833 // Complain about the 'static' specifier if it's on an out-of-line
6834 // member function definition.
6835 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6836 diag::err_static_out_of_line)
6837 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6838 }
Richard Smith66f3ac92012-10-20 08:26:51 +00006839
6840 // C++11 [except.spec]p15:
6841 // A deallocation function with no exception-specification is treated
6842 // as if it were specified with noexcept(true).
6843 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6844 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6845 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006846 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00006847 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6848 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00006849 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006850 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00006851 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006852 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006853
6854 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00006855 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00006856 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006857 isExplicitSpecialization ||
6858 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00006859
Zhongxing Xubece5d62009-01-16 01:13:29 +00006860 // Handle GNU asm-label extension (encoded as an attribute).
6861 if (Expr *E = (Expr*) D.getAsmLabel()) {
6862 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00006863 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006864 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00006865 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00006866 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6867 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6868 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6869 if (I != ExtnameUndeclaredIdentifiers.end()) {
6870 NewFD->addAttr(I->second);
6871 ExtnameUndeclaredIdentifiers.erase(I);
6872 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00006873 }
6874
Chris Lattner9af40c12009-04-25 06:12:16 +00006875 // Copy the parameter declarations from the declarator D to the function
6876 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006877 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00006878 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006879 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00006880
Zhongxing Xubece5d62009-01-16 01:13:29 +00006881 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6882 // function that takes no arguments, not a function that takes a
6883 // single void argument.
6884 // We let through "const void" here because Sema::GetTypeForDeclarator
6885 // already checks for that case.
Alp Tokerc5350722014-02-26 22:27:52 +00006886 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6887 FTI.Params[0].Param &&
6888 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00006889 // Empty arg list, don't push any params.
Alp Tokerc5350722014-02-26 22:27:52 +00006890 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
6891 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6892 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[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);
David Blaikie080a61c2014-02-09 07:24:41 +00006960 // Attach WarnUnusedResult to functions returning types with that attribute.
6961 // Don't apply the attribute to that type's own non-static member functions
6962 // (to avoid warning on things like assignment operators)
6963 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00006964 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
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;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007307 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007308 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007309 }
7310
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007311 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007312
David Blaikiebbafb8a2012-03-11 07:00:24 +00007313 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007314 if (IdentifierInfo *II = NewFD->getIdentifier())
7315 if (!NewFD->isInvalidDecl() &&
7316 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7317 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007318 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007319 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7320
7321 Context.setcudaConfigureCallDecl(NewFD);
7322 }
7323 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007324
7325 // Here we have an function template explicit specialization at class scope.
7326 // The actually specialization will be postponed to template instatiation
7327 // time via the ClassScopeFunctionSpecializationDecl node.
7328 if (isDependentClassScopeExplicitSpecialization) {
7329 ClassScopeFunctionSpecializationDecl *NewSpec =
7330 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007331 Context, CurContext, SourceLocation(),
7332 cast<CXXMethodDecl>(NewFD),
7333 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007334 CurContext->addDecl(NewSpec);
7335 AddToScope = false;
7336 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007337
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007338 return NewFD;
7339}
7340
7341/// \brief Perform semantic checking of a new function declaration.
7342///
7343/// Performs semantic analysis of the new function declaration
7344/// NewFD. This routine performs all semantic checking that does not
7345/// require the actual declarator involved in the declaration, and is
7346/// used both for the declaration of functions as they are parsed
7347/// (called via ActOnDeclarator) and for the declaration of functions
7348/// that have been instantiated via C++ template instantiation (called
7349/// via InstantiateDecl).
7350///
James Dennettffad8b72012-06-22 08:10:18 +00007351/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007352/// an explicit specialization of the previous declaration.
7353///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007354/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007355///
James Dennettffad8b72012-06-22 08:10:18 +00007356/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007357bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007358 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007359 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007360 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7361 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007362
Richard Smith1c34fb72013-08-13 18:18:50 +00007363 // Determine whether the type of this function should be merged with
7364 // a previous visible declaration. This never happens for functions in C++,
7365 // and always happens in C if the previous declaration was visible.
7366 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7367 !Previous.isShadowed();
7368
Douglas Gregor3552dab2013-01-09 00:47:56 +00007369 // Filter out any non-conflicting previous declarations.
7370 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7371
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007372 bool Redeclaration = false;
Richard Smith574f4f62013-01-14 05:37:29 +00007373 NamedDecl *OldDecl = 0;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007374
Douglas Gregore62c0a42009-02-24 01:23:02 +00007375 // Merge or overload the declaration with an existing declaration of
7376 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007377 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007378 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007379 // a declaration that requires merging. If it's an overload,
7380 // there's no more work to do here; we'll just add the new
7381 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007382 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007383 NamedDecl *Candidate = Previous.getFoundDecl();
7384 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7385 Redeclaration = true;
7386 OldDecl = Candidate;
7387 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007388 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007389 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7390 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007391 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007392 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007393 break;
7394
7395 case Ovl_NonFunction:
7396 Redeclaration = true;
7397 break;
7398
7399 case Ovl_Overload:
7400 Redeclaration = false;
7401 break;
John McCall1f82f242009-11-18 22:49:29 +00007402 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007403
David Blaikiebbafb8a2012-03-11 07:00:24 +00007404 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007405 // If a function name is overloadable in C, then every function
7406 // with that name must be marked "overloadable".
7407 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7408 << Redeclaration << NewFD;
7409 NamedDecl *OverloadedDecl = 0;
7410 if (Redeclaration)
7411 OverloadedDecl = OldDecl;
7412 else if (!Previous.empty())
7413 OverloadedDecl = Previous.getRepresentativeDecl();
7414 if (OverloadedDecl)
7415 Diag(OverloadedDecl->getLocation(),
7416 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007417 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007418 }
John McCall1f82f242009-11-18 22:49:29 +00007419 }
Richard Smith574f4f62013-01-14 05:37:29 +00007420 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007421
Richard Smithac974a32013-06-30 09:48:50 +00007422 // Check for a previous extern "C" declaration with this name.
7423 if (!Redeclaration &&
7424 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7425 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7426 if (!Previous.empty()) {
7427 // This is an extern "C" declaration with the same name as a previous
7428 // declaration, and thus redeclares that entity...
7429 Redeclaration = true;
7430 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007431 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007432
7433 // ... except in the presence of __attribute__((overloadable)).
7434 if (OldDecl->hasAttr<OverloadableAttr>()) {
7435 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7436 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7437 << Redeclaration << NewFD;
7438 Diag(Previous.getFoundDecl()->getLocation(),
7439 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007440 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007441 }
7442 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7443 Redeclaration = false;
7444 OldDecl = 0;
7445 }
7446 }
7447 }
7448 }
7449
Richard Smith574f4f62013-01-14 05:37:29 +00007450 // C++11 [dcl.constexpr]p8:
7451 // A constexpr specifier for a non-static member function that is not
7452 // a constructor declares that member function to be const.
7453 //
7454 // This needs to be delayed until we know whether this is an out-of-line
7455 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007456 //
7457 // This rule is not present in C++1y, so we produce a backwards
7458 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007459 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007460 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7461 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007462 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Alp Tokera2794f92014-01-22 07:29:52 +00007463 CXXMethodDecl *OldMD = 0;
7464 if (OldDecl)
7465 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007466 if (!OldMD || !OldMD->isStatic()) {
7467 const FunctionProtoType *FPT =
7468 MD->getType()->castAs<FunctionProtoType>();
7469 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7470 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007471 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007472 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007473
7474 // Warn that we did this, if we're not performing template instantiation.
7475 // In that case, we'll have warned already when the template was defined.
7476 if (ActiveTemplateInstantiations.empty()) {
7477 SourceLocation AddConstLoc;
7478 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7479 .IgnoreParens().getAs<FunctionTypeLoc>())
7480 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7481
7482 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7483 << FixItHint::CreateInsertion(AddConstLoc, " const");
7484 }
Richard Smith574f4f62013-01-14 05:37:29 +00007485 }
7486 }
7487
7488 if (Redeclaration) {
7489 // NewFD and OldDecl represent declarations that need to be
7490 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007491 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007492 NewFD->setInvalidDecl();
7493 return Redeclaration;
7494 }
7495
7496 Previous.clear();
7497 Previous.addDecl(OldDecl);
7498
7499 if (FunctionTemplateDecl *OldTemplateDecl
7500 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7501 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7502 FunctionTemplateDecl *NewTemplateDecl
7503 = NewFD->getDescribedFunctionTemplate();
7504 assert(NewTemplateDecl && "Template/non-template mismatch");
7505 if (CXXMethodDecl *Method
7506 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7507 Method->setAccess(OldTemplateDecl->getAccess());
7508 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007509 }
Richard Smith574f4f62013-01-14 05:37:29 +00007510
7511 // If this is an explicit specialization of a member that is a function
7512 // template, mark it as a member specialization.
7513 if (IsExplicitSpecialization &&
7514 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7515 NewTemplateDecl->setMemberSpecialization();
7516 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007517 }
Richard Smith574f4f62013-01-14 05:37:29 +00007518
7519 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007520 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007521 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007522
7523 if (isa<CXXMethodDecl>(NewFD)) {
7524 // A valid redeclaration of a C++ method must be out-of-line,
7525 // but (unfortunately) it's not necessarily a definition
7526 // because of templates, which means that the previous
7527 // declaration is not necessarily from the class definition.
7528
7529 // For just setting the access, that doesn't matter.
7530 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7531 NewFD->setAccess(oldMethod->getAccess());
7532
7533 // Update the key-function state if necessary for this ABI.
7534 if (NewFD->isInlined() &&
7535 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7536 // setNonKeyFunction needs to work with the original
7537 // declaration from the class definition, and isVirtual() is
7538 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007539 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007540 if (oldMethod->isVirtual()) {
7541 Context.setNonKeyFunction(oldMethod);
7542 }
7543 }
7544 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007545 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007546 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007547
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007548 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007549 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007550 // C++-specific checks.
7551 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7552 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007553 } else if (CXXDestructorDecl *Destructor =
7554 dyn_cast<CXXDestructorDecl>(NewFD)) {
7555 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007556 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007557
Douglas Gregor7454c562010-07-02 20:37:36 +00007558 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007559 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007560 if (!ClassType->isDependentType()) {
7561 DeclarationName Name
7562 = Context.DeclarationNames.getCXXDestructorName(
7563 Context.getCanonicalType(ClassType));
7564 if (NewFD->getDeclName() != Name) {
7565 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007566 NewFD->setInvalidDecl();
7567 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007568 }
7569 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007570 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007571 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007572 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007573 }
7574
7575 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007576 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7577 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007578 !Method->getDescribedFunctionTemplate() &&
7579 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007580 if (AddOverriddenMethods(Method->getParent(), Method)) {
7581 // If the function was marked as "static", we have a problem.
7582 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007583 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007584 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007585 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007586 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007587
7588 if (Method->isStatic())
7589 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007590 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007591
7592 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7593 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007594 CheckOverloadedOperatorDeclaration(NewFD)) {
7595 NewFD->setInvalidDecl();
7596 return Redeclaration;
7597 }
Alexis Huntc88db062010-01-13 09:01:02 +00007598
7599 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7600 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007601 CheckLiteralOperatorDeclaration(NewFD)) {
7602 NewFD->setInvalidDecl();
7603 return Redeclaration;
7604 }
Alexis Huntc88db062010-01-13 09:01:02 +00007605
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007606 // In C++, check default arguments now that we have merged decls. Unless
7607 // the lexical context is the class, because in this case this is done
7608 // during delayed parsing anyway.
7609 if (!CurContext->isRecord())
7610 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007611
Douglas Gregor9246b682010-12-21 19:47:46 +00007612 // If this function declares a builtin function, check the type of this
7613 // declaration against the expected type for the builtin.
7614 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7615 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007616 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007617 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7618 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7619 // The type of this function differs from the type of the builtin,
7620 // so forget about the builtin entirely.
7621 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7622 }
7623 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007624
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007625 // If this function is declared as being extern "C", then check to see if
7626 // the function returns a UDT (class, struct, or union type) that is not C
7627 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007628 // But, issue any diagnostic on the first declaration only.
7629 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007630 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007631 if (R->isIncompleteType() && !R->isVoidType())
7632 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7633 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007634 else if (!R.isPODType(Context) && !R->isVoidType() &&
7635 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007636 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007637 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007638 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007639 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007640}
7641
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007642static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7643 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7644 if (!TSI)
7645 return SourceRange();
7646
7647 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007648 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007649 if (!FunctionTL)
7650 return SourceRange();
7651
Alp Toker42a16a62014-01-25 23:51:36 +00007652 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007653 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007654 return ResultTL.getSourceRange();
7655
7656 return SourceRange();
7657}
7658
David Blaikied937bf12011-09-08 06:33:04 +00007659void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007660 // C++11 [basic.start.main]p3:
7661 // A program that [...] declares main to be inline, static or
7662 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007663 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7664 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007665 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007666 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007667 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007668 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007669 ? diag::err_static_main : diag::warn_static_main)
7670 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7671 if (FD->isInlineSpecified())
7672 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7673 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007674 if (DS.isNoreturnSpecified()) {
7675 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7676 SourceRange NoreturnRange(NoreturnLoc,
7677 PP.getLocForEndOfToken(NoreturnLoc));
7678 Diag(NoreturnLoc, diag::ext_noreturn_main);
7679 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7680 << FixItHint::CreateRemoval(NoreturnRange);
7681 }
Richard Smith3f333f22012-02-04 06:10:17 +00007682 if (FD->isConstexpr()) {
7683 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7684 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7685 FD->setConstexpr(false);
7686 }
John McCall02dee0a2009-07-25 04:36:53 +00007687
Joey Goulya7310a82013-11-05 12:30:39 +00007688 if (getLangOpts().OpenCL) {
7689 Diag(FD->getLocation(), diag::err_opencl_no_main)
7690 << FD->hasAttr<OpenCLKernelAttr>();
7691 FD->setInvalidDecl();
7692 return;
7693 }
7694
John McCall02dee0a2009-07-25 04:36:53 +00007695 QualType T = FD->getType();
7696 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007697 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007698
John McCall5ed3caf2012-02-14 19:50:52 +00007699 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007700 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007701 // In C and C++, main magically returns 0 if you fall off the end;
7702 // set the flag which tells us that.
7703 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7704 FD->setHasImplicitReturnZero(true);
7705
7706 // In C with GNU extensions we allow main() to have non-integer return
7707 // type, but we should warn about the extension, and we disable the
7708 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007709 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007710 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7711
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007712 SourceRange ResultRange = getResultSourceRange(FD);
7713 if (ResultRange.isValid())
7714 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7715 << FixItHint::CreateReplacement(ResultRange, "int");
7716
John McCall5ed3caf2012-02-14 19:50:52 +00007717 // Otherwise, this is just a flat-out error.
7718 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007719 SourceRange ResultRange = getResultSourceRange(FD);
7720 if (ResultRange.isValid())
7721 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7722 << FixItHint::CreateReplacement(ResultRange, "int");
7723 else
7724 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7725
John McCall02dee0a2009-07-25 04:36:53 +00007726 FD->setInvalidDecl(true);
7727 }
7728
7729 // Treat protoless main() as nullary.
7730 if (isa<FunctionNoProtoType>(FT)) return;
7731
7732 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007733 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007734 assert(FD->getNumParams() == nparams);
7735
John McCall0e21fcc2009-12-24 09:58:38 +00007736 bool HasExtraParameters = (nparams > 3);
7737
7738 // Darwin passes an undocumented fourth argument of type char**. If
7739 // other platforms start sprouting these, the logic below will start
7740 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007741 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007742 HasExtraParameters = false;
7743
7744 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007745 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7746 FD->setInvalidDecl(true);
7747 nparams = 3;
7748 }
7749
7750 // FIXME: a lot of the following diagnostics would be improved
7751 // if we had some location information about types.
7752
7753 QualType CharPP =
7754 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007755 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007756
7757 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007758 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007759
7760 bool mismatch = true;
7761
7762 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7763 mismatch = false;
7764 else if (Expected[i] == CharPP) {
7765 // As an extension, the following forms are okay:
7766 // char const **
7767 // char const * const *
7768 // char * const *
7769
John McCall8ccfcb52009-09-24 19:53:00 +00007770 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007771 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007772 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7773 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007774 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7775 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007776 qs.removeConst();
7777 mismatch = !qs.empty();
7778 }
7779 }
7780
7781 if (mismatch) {
7782 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7783 // TODO: suggest replacing given type with expected type
7784 FD->setInvalidDecl(true);
7785 }
7786 }
7787
7788 if (nparams == 1 && !FD->isInvalidDecl()) {
7789 Diag(FD->getLocation(), diag::warn_main_one_arg);
7790 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007791
7792 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007793 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007794 FD->setInvalidDecl();
7795 }
7796}
7797
7798void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7799 QualType T = FD->getType();
7800 assert(T->isFunctionType() && "function decl is not of function type");
7801 const FunctionType *FT = T->castAs<FunctionType>();
7802
7803 // Set an implicit return of 'zero' if the function can return some integral,
7804 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007805 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7806 FT->getReturnType()->isAnyPointerType() ||
7807 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007808 // DllMain is exempt because a return value of zero means it failed.
7809 if (FD->getName() != "DllMain")
7810 FD->setHasImplicitReturnZero(true);
7811
7812 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007813 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007814 FD->setInvalidDecl();
7815 }
John McCalld9baf6a2009-07-24 03:03:21 +00007816}
7817
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007818bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007819 // FIXME: Need strict checking. In C89, we need to check for
7820 // any assignment, increment, decrement, function-calls, or
7821 // commas outside of a sizeof. In C99, it's the same list,
7822 // except that the aforementioned are allowed in unevaluated
7823 // expressions. Everything else falls under the
7824 // "may accept other forms of constant expressions" exception.
7825 // (We never end up here for C++, so the constant expression
7826 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00007827 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00007828 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00007829 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7830 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007831 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00007832}
7833
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007834namespace {
7835 // Visits an initialization expression to see if OrigDecl is evaluated in
7836 // its own initialization and throws a warning if it does.
7837 class SelfReferenceChecker
7838 : public EvaluatedExprVisitor<SelfReferenceChecker> {
7839 Sema &S;
7840 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007841 bool isRecordType;
7842 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007843 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007844
7845 public:
7846 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7847
7848 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00007849 S(S), OrigDecl(OrigDecl) {
7850 isPODType = false;
7851 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00007852 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00007853 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7854 isPODType = VD->getType().isPODType(S.Context);
7855 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00007856 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00007857 }
7858 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007859
Richard Trieu64c51ab2012-05-09 00:21:34 +00007860 // For most expressions, the cast is directly above the DeclRefExpr.
7861 // For conditional operators, the cast can be outside the conditional
7862 // operator if both expressions are DeclRefExpr's.
7863 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00007864 if (isReferenceType)
7865 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007866 E = E->IgnoreParenImpCasts();
7867 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7868 HandleDeclRefExpr(DRE);
7869 return;
7870 }
7871
7872 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7873 HandleValue(CO->getTrueExpr());
7874 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00007875 return;
7876 }
7877
7878 if (isa<MemberExpr>(E)) {
7879 Expr *Base = E->IgnoreParenImpCasts();
7880 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7881 // Check for static member variables and don't warn on them.
7882 if (!isa<FieldDecl>(ME->getMemberDecl()))
7883 return;
7884 Base = ME->getBase()->IgnoreParenImpCasts();
7885 }
7886 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7887 HandleDeclRefExpr(DRE);
7888 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007889 }
7890 }
7891
Richard Trieu32673472012-10-01 17:39:51 +00007892 // Reference types are handled here since all uses of references are
7893 // bad, not just r-value uses.
7894 void VisitDeclRefExpr(DeclRefExpr *E) {
7895 if (isReferenceType)
7896 HandleDeclRefExpr(E);
7897 }
7898
Richard Trieu64c51ab2012-05-09 00:21:34 +00007899 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00007900 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00007901 (isRecordType && E->getCastKind() == CK_NoOp))
7902 HandleValue(E->getSubExpr());
7903
7904 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007905 }
7906
Richard Trieua04ad1a2011-09-01 21:44:13 +00007907 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00007908 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00007909 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00007910
Richard Trieu742c6ed2012-10-03 00:41:36 +00007911 // Warn when a non-static method call is followed by non-static member
7912 // field accesses, which is followed by a DeclRefExpr.
7913 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7914 bool Warn = (MD && !MD->isStatic());
7915 Expr *Base = E->getBase()->IgnoreParenImpCasts();
7916 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7917 if (!isa<FieldDecl>(ME->getMemberDecl()))
7918 Warn = false;
7919 Base = ME->getBase()->IgnoreParenImpCasts();
7920 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007921
Richard Trieu742c6ed2012-10-03 00:41:36 +00007922 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7923 if (Warn)
7924 HandleDeclRefExpr(DRE);
7925 return;
7926 }
7927
7928 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7929 // Visit that expression.
7930 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007931 }
7932
Richard Trieu8fbd91d2013-03-26 03:41:40 +00007933 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7934 if (E->getNumArgs() > 0)
7935 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7936 HandleDeclRefExpr(DRE);
7937
7938 Inherited::VisitCXXOperatorCallExpr(E);
7939 }
7940
Richard Trieua04ad1a2011-09-01 21:44:13 +00007941 void VisitUnaryOperator(UnaryOperator *E) {
7942 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00007943 if (E->getOpcode() == UO_AddrOf && isRecordType &&
7944 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7945 if (!isPODType)
7946 HandleValue(E->getSubExpr());
7947 return;
7948 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007949 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00007950 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00007951
7952 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7953
Richard Trieua04ad1a2011-09-01 21:44:13 +00007954 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00007955 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007956 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00007957 unsigned diag;
7958 if (isReferenceType) {
7959 diag = diag::warn_uninit_self_reference_in_reference_init;
7960 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7961 diag = diag::warn_static_self_reference_in_init;
7962 } else {
7963 diag = diag::warn_uninit_self_reference_in_init;
7964 }
7965
Richard Trieua04ad1a2011-09-01 21:44:13 +00007966 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00007967 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00007968 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007969 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00007970 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007971 }
7972 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00007973
Richard Trieu32673472012-10-01 17:39:51 +00007974 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7975 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7976 bool DirectInit) {
7977 // Parameters arguments are occassionially constructed with itself,
7978 // for instance, in recursive functions. Skip them.
7979 if (isa<ParmVarDecl>(OrigDecl))
7980 return;
7981
7982 E = E->IgnoreParens();
7983
7984 // Skip checking T a = a where T is not a record or reference type.
7985 // Doing so is a way to silence uninitialized warnings.
7986 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7987 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7988 if (ICE->getCastKind() == CK_LValueToRValue)
7989 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7990 if (DRE->getDecl() == OrigDecl)
7991 return;
7992
7993 SelfReferenceChecker(S, OrigDecl).Visit(E);
7994 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00007995}
7996
Douglas Gregor5fb53972009-01-14 15:45:31 +00007997/// AddInitializerToDecl - Adds the initializer Init to the
7998/// declaration dcl. If DirectInit is true, this is C++ direct
7999/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008000void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8001 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008002 // If there is no declaration, there was an error parsing it. Just ignore
8003 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00008004 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008005 return;
Mike Stump11289f42009-09-09 15:08:12 +00008006
Douglas Gregor0c880302009-03-11 23:00:04 +00008007 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8008 // With declarators parsed the way they are, the parser cannot
8009 // distinguish between a normal initializer and a pure-specifier.
8010 // Thus this grotesque test.
8011 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008012 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008013 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8014 CheckPureMethod(Method, Init->getSourceRange());
8015 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008016 Diag(Method->getLocation(), diag::err_member_function_initialization)
8017 << Method->getDeclName() << Init->getSourceRange();
8018 Method->setInvalidDecl();
8019 }
8020 return;
8021 }
8022
Steve Naroff437b4d82007-09-12 20:13:48 +00008023 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8024 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008025 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8026 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008027 RealDecl->setInvalidDecl();
8028 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008029 }
Sebastian Redla9351792012-02-11 23:51:47 +00008030 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8031
Richard Smith0cc85782011-12-15 19:20:59 +00008032 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008033 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008034 Expr *DeduceInit = Init;
8035 // Initializer could be a C++ direct-initializer. Deduction only works if it
8036 // contains exactly one expression.
8037 if (CXXDirectInit) {
8038 if (CXXDirectInit->getNumExprs() == 0) {
8039 // It isn't possible to write this directly, but it is possible to
8040 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008041 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008042 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8043 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008044 << VDecl->getDeclName() << VDecl->getType()
8045 << VDecl->getSourceRange();
8046 RealDecl->setInvalidDecl();
8047 return;
8048 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008049 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008050 VDecl->isInitCapture()
8051 ? diag::err_init_capture_multiple_expressions
8052 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008053 << VDecl->getDeclName() << VDecl->getType()
8054 << VDecl->getSourceRange();
8055 RealDecl->setInvalidDecl();
8056 return;
8057 } else {
8058 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008059 if (isa<InitListExpr>(DeduceInit))
8060 Diag(CXXDirectInit->getLocStart(),
8061 diag::err_auto_var_init_paren_braces)
8062 << VDecl->getDeclName() << VDecl->getType()
8063 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008064 }
8065 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008066
8067 // Expressions default to 'id' when we're in a debugger.
8068 bool DefaultedToAuto = false;
8069 if (getLangOpts().DebuggerCastResultToId &&
8070 Init->getType() == Context.UnknownAnyTy) {
8071 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8072 if (Result.isInvalid()) {
8073 VDecl->setInvalidDecl();
8074 return;
8075 }
8076 Init = Result.take();
8077 DefaultedToAuto = true;
8078 }
Richard Smith061f1e22013-04-30 21:23:01 +00008079
8080 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008081 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008082 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008083 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008084 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008085 RealDecl->setInvalidDecl();
8086 return;
8087 }
Richard Smith061f1e22013-04-30 21:23:01 +00008088 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008089 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008090
John McCall31168b02011-06-15 23:02:42 +00008091 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008092 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008093 VDecl->setInvalidDecl();
8094
Jordan Rosed8d56692012-06-08 22:46:07 +00008095 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8096 // 'id' instead of a specific object type prevents most of our usual checks.
8097 // We only want to warn outside of template instantiations, though:
8098 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008099 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008100 DeducedType->isObjCIdType()) {
8101 SourceLocation Loc =
8102 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008103 Diag(Loc, diag::warn_auto_var_is_id)
8104 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8105 }
8106
Richard Smith30482bc2011-02-20 03:19:35 +00008107 // If this is a redeclaration, check that the type we just deduced matches
8108 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008109 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8110 // We never need to merge the type, because we cannot form an incomplete
8111 // array of auto, nor deduce such a type.
8112 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8113 }
Richard Smith27d807c2013-04-30 13:56:41 +00008114
8115 // Check the deduced type is valid for a variable declaration.
8116 CheckVariableDeclarationType(VDecl);
8117 if (VDecl->isInvalidDecl())
8118 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008119 }
Richard Smith0cc85782011-12-15 19:20:59 +00008120
Nico Rieck8e9791f2014-02-26 21:27:13 +00008121 // dllimport cannot be used on variable definitions.
8122 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8123 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8124 VDecl->setInvalidDecl();
8125 return;
8126 }
8127
Richard Smith0cc85782011-12-15 19:20:59 +00008128 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8129 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8130 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8131 VDecl->setInvalidDecl();
8132 return;
8133 }
8134
Sebastian Redla9351792012-02-11 23:51:47 +00008135 if (!VDecl->getType()->isDependentType()) {
8136 // A definition must end up with a complete type, which means it must be
8137 // complete with the restriction that an array type might be completed by
8138 // the initializer; note that later code assumes this restriction.
8139 QualType BaseDeclType = VDecl->getType();
8140 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8141 BaseDeclType = Array->getElementType();
8142 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8143 diag::err_typecheck_decl_incomplete_type)) {
8144 RealDecl->setInvalidDecl();
8145 return;
8146 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008147
Sebastian Redla9351792012-02-11 23:51:47 +00008148 // The variable can not have an abstract class type.
8149 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8150 diag::err_abstract_type_in_decl,
8151 AbstractVariableType))
8152 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008153 }
8154
Sebastian Redl5ca79842010-02-01 20:16:42 +00008155 const VarDecl *Def;
8156 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008157 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008158 << VDecl->getDeclName();
8159 Diag(Def->getLocation(), diag::note_previous_definition);
8160 VDecl->setInvalidDecl();
8161 return;
8162 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008163
Douglas Gregorf0f83692010-08-24 05:27:49 +00008164 const VarDecl* PrevInit = 0;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008165 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008166 // C++ [class.static.data]p4
8167 // If a static data member is of const integral or const
8168 // enumeration type, its declaration in the class definition can
8169 // specify a constant-initializer which shall be an integral
8170 // constant expression (5.19). In that case, the member can appear
8171 // in integral constant expressions. The member shall still be
8172 // defined in a namespace scope if it is used in the program and the
8173 // namespace scope definition shall not contain an initializer.
8174 //
8175 // We already performed a redefinition check above, but for static
8176 // data members we also need to check whether there was an in-class
8177 // declaration with an initializer.
8178 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008179 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8180 << VDecl->getDeclName();
8181 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008182 return;
8183 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008184
Douglas Gregor71f39c92010-12-16 01:31:22 +00008185 if (VDecl->hasLocalStorage())
8186 getCurFunction()->setHasBranchProtectedScope();
8187
8188 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8189 VDecl->setInvalidDecl();
8190 return;
8191 }
8192 }
John McCalld4e1b762010-08-01 01:24:59 +00008193
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008194 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8195 // a kernel function cannot be initialized."
8196 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8197 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8198 VDecl->setInvalidDecl();
8199 return;
8200 }
8201
Steve Naroff61091402007-09-12 14:07:44 +00008202 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008203 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008204 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008205
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008206 // Expressions default to 'id' when we're in a debugger
8207 // and we are assigning it to a variable of Objective-C pointer type.
8208 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8209 Init->getType() == Context.UnknownAnyTy) {
8210 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8211 if (Result.isInvalid()) {
8212 VDecl->setInvalidDecl();
8213 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008214 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008215 Init = Result.take();
8216 }
Richard Smith0cc85782011-12-15 19:20:59 +00008217
8218 // Perform the initialization.
8219 if (!VDecl->isInvalidDecl()) {
8220 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8221 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008222 = DirectInit ?
8223 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8224 Init->getLocStart(),
8225 Init->getLocEnd())
8226 : InitializationKind::CreateDirectList(
8227 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008228 : InitializationKind::CreateCopy(VDecl->getLocation(),
8229 Init->getLocStart());
8230
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008231 MultiExprArg Args = Init;
8232 if (CXXDirectInit)
8233 Args = MultiExprArg(CXXDirectInit->getExprs(),
8234 CXXDirectInit->getNumExprs());
8235
8236 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8237 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008238 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008239 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008240 return;
Steve Naroff61091402007-09-12 14:07:44 +00008241 }
Richard Smith0cc85782011-12-15 19:20:59 +00008242
8243 Init = Result.takeAs<Expr>();
8244 }
8245
Richard Trieu32673472012-10-01 17:39:51 +00008246 // Check for self-references within variable initializers.
8247 // Variables declared within a function/method body (except for references)
8248 // are handled by a dataflow analysis.
8249 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8250 VDecl->getType()->isReferenceType()) {
8251 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8252 }
8253
Richard Smith0cc85782011-12-15 19:20:59 +00008254 // If the type changed, it means we had an incomplete type that was
8255 // completed by the initializer. For example:
8256 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008257 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008258 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008259 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008260
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008261 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008262 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8263
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008264 if (VDecl->hasAttr<BlocksAttr>())
8265 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008266
8267 // It is safe to assign a weak reference into a strong variable.
8268 // Although this code can still have problems:
8269 // id x = self.weakProp;
8270 // id y = self.weakProp;
8271 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8272 // paths through the function. This should be revisited if
8273 // -Wrepeated-use-of-weak is made flow-sensitive.
Ted Kremenek94537212012-12-20 22:31:27 +00008274 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
Jordan Rosed3934582012-09-28 22:21:30 +00008275 DiagnosticsEngine::Level Level =
8276 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8277 Init->getLocStart());
8278 if (Level != DiagnosticsEngine::Ignored)
8279 getCurFunction()->markSafeWeakUse(Init);
8280 }
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008281 }
8282
Richard Smith945f8d32013-01-14 22:39:08 +00008283 // The initialization is usually a full-expression.
8284 //
8285 // FIXME: If this is a braced initialization of an aggregate, it is not
8286 // an expression, and each individual field initializer is a separate
8287 // full-expression. For instance, in:
8288 //
8289 // struct Temp { ~Temp(); };
8290 // struct S { S(Temp); };
8291 // struct T { S a, b; } t = { Temp(), Temp() }
8292 //
8293 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008294 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8295 false,
8296 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008297 if (Result.isInvalid()) {
8298 VDecl->setInvalidDecl();
8299 return;
8300 }
8301 Init = Result.take();
8302
Richard Smith0cc85782011-12-15 19:20:59 +00008303 // Attach the initializer to the decl.
8304 VDecl->setInit(Init);
8305
8306 if (VDecl->isLocalVarDecl()) {
8307 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8308 // static storage duration shall be constant expressions or string literals.
8309 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008310 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8311 if (VDecl->getStorageClass() == SC_Static)
8312 CheckForConstantInitializer(Init, DclT);
8313 // C89 is stricter than C99 for non-static aggregate types.
8314 // C89 6.5.7p3: All the expressions [...] in an initializer list
8315 // for an object that has aggregate or union type shall be
8316 // constant expressions.
8317 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008318 isa<InitListExpr>(Init) &&
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008319 !Init->isConstantInitializer(Context, false))
8320 Diag(Init->getExprLoc(),
8321 diag::ext_aggregate_init_not_constant)
8322 << Init->getSourceRange();
8323 }
Mike Stump11289f42009-09-09 15:08:12 +00008324 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008325 VDecl->getLexicalDeclContext()->isRecord()) {
8326 // This is an in-class initialization for a static data member, e.g.,
8327 //
8328 // struct S {
8329 // static const int value = 17;
8330 // };
8331
Douglas Gregor0c880302009-03-11 23:00:04 +00008332 // C++ [class.mem]p4:
8333 // A member-declarator can contain a constant-initializer only
8334 // if it declares a static member (9.4) of const integral or
8335 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008336 //
Richard Smith0cc85782011-12-15 19:20:59 +00008337 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008338 // If a non-volatile const static data member is of integral or
8339 // enumeration type, its declaration in the class definition can
8340 // specify a brace-or-equal-initializer in which every initalizer-clause
8341 // that is an assignment-expression is a constant expression. A static
8342 // data member of literal type can be declared in the class definition
8343 // with the constexpr specifier; if so, its declaration shall specify a
8344 // brace-or-equal-initializer in which every initializer-clause that is
8345 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008346
8347 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008348 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008349
Richard Smith2316cd82011-09-29 19:11:37 +00008350 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008351 // type. We separately check that every constexpr variable is of literal
8352 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008353 } else if (VDecl->isConstexpr()) {
8354
John McCalldb768922010-09-10 23:21:22 +00008355 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008356 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008357 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8358 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008359 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008360
8361 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008362 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008363 // Check whether the expression is a constant expression.
8364 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008365 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008366 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008367 // in-class initializer cannot be volatile.
8368 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8369 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008370 ; // Nothing to check.
8371 else if (Init->isIntegerConstantExpr(Context, &Loc))
8372 ; // Ok, it's an ICE!
8373 else if (Init->isEvaluatable(Context)) {
8374 // If we can constant fold the initializer through heroics, accept it,
8375 // but report this as a use of an extension for -pedantic.
8376 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8377 << Init->getSourceRange();
8378 } else {
8379 // Otherwise, this is some crazy unknown case. Report the issue at the
8380 // location provided by the isIntegerConstantExpr failed check.
8381 Diag(Loc, diag::err_in_class_initializer_non_constant)
8382 << Init->getSourceRange();
8383 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008384 }
8385
Richard Smith0cc85782011-12-15 19:20:59 +00008386 // We allow foldable floating-point constants as an extension.
8387 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008388 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8389 // it anyway and provide a fixit to add the 'constexpr'.
8390 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008391 Diag(VDecl->getLocation(),
8392 diag::ext_in_class_initializer_float_type_cxx11)
8393 << DclT << Init->getSourceRange();
8394 Diag(VDecl->getLocStart(),
8395 diag::note_in_class_initializer_float_type_cxx11)
8396 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008397 } else {
8398 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8399 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008400
Richard Smithcf656382013-01-25 04:22:16 +00008401 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8402 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8403 << Init->getSourceRange();
8404 VDecl->setInvalidDecl();
8405 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008406 }
Richard Smith256336d2011-09-29 23:18:34 +00008407
Richard Smith0cc85782011-12-15 19:20:59 +00008408 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008409 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008410 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008411 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008412 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8413 VDecl->setConstexpr(true);
8414
Richard Smith2316cd82011-09-29 19:11:37 +00008415 } else {
8416 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008417 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008418 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008419 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008420 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008421 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008422 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008423 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008424 VDecl->isExternC())) &&
8425 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008426 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008427
Richard Smith0cc85782011-12-15 19:20:59 +00008428 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008429 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008430 CheckForConstantInitializer(Init, DclT);
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008431 else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8432 !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8433 !Init->isValueDependent() && !VDecl->isConstexpr() &&
Richard Smith774672e2013-04-15 08:07:34 +00008434 !Init->isConstantInitializer(
8435 Context, VDecl->getType()->isReferenceType())) {
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008436 // GNU C++98 edits for __thread, [basic.start.init]p4:
8437 // An object of thread storage duration shall not require dynamic
8438 // initialization.
8439 // FIXME: Need strict checking here.
8440 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8441 if (getLangOpts().CPlusPlus11)
8442 Diag(VDecl->getLocation(), diag::note_use_thread_local);
8443 }
Steve Naroff61091402007-09-12 14:07:44 +00008444 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008445
Sebastian Redla9351792012-02-11 23:51:47 +00008446 // We will represent direct-initialization similarly to copy-initialization:
8447 // int x(1); -as-> int x = 1;
8448 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8449 //
8450 // Clients that want to distinguish between the two forms, can check for
8451 // direct initializer using VarDecl::getInitStyle().
8452 // A major benefit is that clients that don't particularly care about which
8453 // exactly form was it (like the CodeGen) can handle both cases without
8454 // special case code.
8455
8456 // C++ 8.5p11:
8457 // The form of initialization (using parentheses or '=') is generally
8458 // insignificant, but does matter when the entity being initialized has a
8459 // class type.
8460 if (CXXDirectInit) {
8461 assert(DirectInit && "Call-style initializer must be direct init.");
8462 VDecl->setInitStyle(VarDecl::CallInit);
8463 } else if (DirectInit) {
8464 // This must be list-initialization. No other way is direct-initialization.
8465 VDecl->setInitStyle(VarDecl::ListInit);
8466 }
8467
John McCall8b7fd8f12011-01-19 11:48:09 +00008468 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008469}
8470
John McCalleae5acb2010-03-31 02:13:20 +00008471/// ActOnInitializerError - Given that there was an error parsing an
8472/// initializer for the given declaration, try to return to some form
8473/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008474void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008475 // Our main concern here is re-establishing invariants like "a
8476 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008477 if (!D || D->isInvalidDecl()) return;
8478
8479 VarDecl *VD = dyn_cast<VarDecl>(D);
8480 if (!VD) return;
8481
Richard Smith30482bc2011-02-20 03:19:35 +00008482 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008483 if (ParsingInitForAutoVars.count(D)) {
8484 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008485 return;
8486 }
8487
John McCalleae5acb2010-03-31 02:13:20 +00008488 QualType Ty = VD->getType();
8489 if (Ty->isDependentType()) return;
8490
8491 // Require a complete type.
8492 if (RequireCompleteType(VD->getLocation(),
8493 Context.getBaseElementType(Ty),
8494 diag::err_typecheck_decl_incomplete_type)) {
8495 VD->setInvalidDecl();
8496 return;
8497 }
8498
8499 // Require an abstract type.
8500 if (RequireNonAbstractType(VD->getLocation(), Ty,
8501 diag::err_abstract_type_in_decl,
8502 AbstractVariableType)) {
8503 VD->setInvalidDecl();
8504 return;
8505 }
8506
8507 // Don't bother complaining about constructors or destructors,
8508 // though.
8509}
8510
John McCall48871652010-08-21 09:40:31 +00008511void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008512 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008513 // If there is no declaration, there was an error parsing it. Just ignore it.
8514 if (RealDecl == 0)
8515 return;
8516
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008517 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8518 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008519
Richard Smithf0215fe2011-12-25 21:17:58 +00008520 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008521 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008522 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8523 << Var->getDeclName() << Type;
8524 Var->setInvalidDecl();
8525 return;
8526 }
Mike Stump11289f42009-09-09 15:08:12 +00008527
Richard Smithf0215fe2011-12-25 21:17:58 +00008528 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008529 // the constexpr specifier; if so, its declaration shall specify
8530 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008531 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8532 // the definition of a variable [...] or the declaration of a static data
8533 // member.
8534 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8535 if (Var->isStaticDataMember())
8536 Diag(Var->getLocation(),
8537 diag::err_constexpr_static_mem_var_requires_init)
8538 << Var->getDeclName();
8539 else
8540 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008541 Var->setInvalidDecl();
8542 return;
8543 }
8544
Joey Gouly96b94e62014-01-03 14:16:55 +00008545 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8546 // be initialized.
8547 if (!Var->isInvalidDecl() &&
8548 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008549 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008550 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8551 Var->setInvalidDecl();
8552 return;
8553 }
8554
Douglas Gregore6565622010-02-09 07:26:29 +00008555 switch (Var->isThisDeclarationADefinition()) {
8556 case VarDecl::Definition:
8557 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8558 break;
8559
8560 // We have an out-of-line definition of a static data member
8561 // that has an in-class initializer, so we type-check this like
8562 // a declaration.
8563 //
8564 // Fall through
8565
8566 case VarDecl::DeclarationOnly:
8567 // It's only a declaration.
8568
8569 // Block scope. C99 6.7p7: If an identifier for an object is
8570 // declared with no linkage (C99 6.2.2p6), the type for the
8571 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008572 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008573 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008574 RequireCompleteType(Var->getLocation(), Type,
8575 diag::err_typecheck_decl_incomplete_type))
8576 Var->setInvalidDecl();
8577
8578 // Make sure that the type is not abstract.
8579 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8580 RequireNonAbstractType(Var->getLocation(), Type,
8581 diag::err_abstract_type_in_decl,
8582 AbstractVariableType))
8583 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008584 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008585 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008586 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008587 Diag(Var->getLocation(), diag::note_private_extern);
8588 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008589
Douglas Gregore6565622010-02-09 07:26:29 +00008590 return;
8591
8592 case VarDecl::TentativeDefinition:
8593 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8594 // object that has file scope without an initializer, and without a
8595 // storage-class specifier or with the storage-class specifier "static",
8596 // constitutes a tentative definition. Note: A tentative definition with
8597 // external linkage is valid (C99 6.2.2p5).
8598 if (!Var->isInvalidDecl()) {
8599 if (const IncompleteArrayType *ArrayT
8600 = Context.getAsIncompleteArrayType(Type)) {
8601 if (RequireCompleteType(Var->getLocation(),
8602 ArrayT->getElementType(),
8603 diag::err_illegal_decl_array_incomplete_type))
8604 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008605 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008606 // C99 6.9.2p3: If the declaration of an identifier for an object is
8607 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8608 // declared type shall not be an incomplete type.
8609 // NOTE: code such as the following
8610 // static struct s;
8611 // struct s { int a; };
8612 // is accepted by gcc. Hence here we issue a warning instead of
8613 // an error and we do not invalidate the static declaration.
8614 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008615 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008616 RequireCompleteType(Var->getLocation(), Type,
8617 diag::ext_typecheck_decl_incomplete_type);
8618 }
8619 }
8620
8621 // Record the tentative definition; we're done.
8622 if (!Var->isInvalidDecl())
8623 TentativeDefinitions.push_back(Var);
8624 return;
8625 }
8626
8627 // Provide a specific diagnostic for uninitialized variable
8628 // definitions with incomplete array type.
8629 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008630 Diag(Var->getLocation(),
8631 diag::err_typecheck_incomplete_array_needs_initializer);
8632 Var->setInvalidDecl();
8633 return;
8634 }
8635
John McCalla755f0f2010-08-01 01:25:24 +00008636 // Provide a specific diagnostic for uninitialized variable
8637 // definitions with reference type.
8638 if (Type->isReferenceType()) {
8639 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8640 << Var->getDeclName()
8641 << SourceRange(Var->getLocation(), Var->getLocation());
8642 Var->setInvalidDecl();
8643 return;
8644 }
Douglas Gregore6565622010-02-09 07:26:29 +00008645
8646 // Do not attempt to type-check the default initializer for a
8647 // variable with dependent type.
8648 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008649 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008650
Douglas Gregore6565622010-02-09 07:26:29 +00008651 if (Var->isInvalidDecl())
8652 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008653
Douglas Gregore6565622010-02-09 07:26:29 +00008654 if (RequireCompleteType(Var->getLocation(),
8655 Context.getBaseElementType(Type),
8656 diag::err_typecheck_decl_incomplete_type)) {
8657 Var->setInvalidDecl();
8658 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008659 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008660
Douglas Gregore6565622010-02-09 07:26:29 +00008661 // The variable can not have an abstract class type.
8662 if (RequireNonAbstractType(Var->getLocation(), Type,
8663 diag::err_abstract_type_in_decl,
8664 AbstractVariableType)) {
8665 Var->setInvalidDecl();
8666 return;
8667 }
8668
Douglas Gregor9574af62011-05-21 17:52:48 +00008669 // Check for jumps past the implicit initializer. C++0x
8670 // clarifies that this applies to a "variable with automatic
8671 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008672 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008673 // A program that jumps from a point where a variable with automatic
8674 // storage duration is not in scope to a point where it is in scope is
8675 // ill-formed unless the variable has scalar type, class type with a
8676 // trivial default constructor and a trivial destructor, a cv-qualified
8677 // version of one of these types, or an array of one of the preceding
8678 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008679 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008680 if (const RecordType *Record
8681 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008682 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008683 // Mark the function for further checking even if the looser rules of
8684 // C++11 do not require such checks, so that we can diagnose
8685 // incompatibilities with C++98.
8686 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008687 getCurFunction()->setHasBranchProtectedScope();
8688 }
Douglas Gregore6565622010-02-09 07:26:29 +00008689 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008690
8691 // C++03 [dcl.init]p9:
8692 // If no initializer is specified for an object, and the
8693 // object is of (possibly cv-qualified) non-POD class type (or
8694 // array thereof), the object shall be default-initialized; if
8695 // the object is of const-qualified type, the underlying class
8696 // type shall have a user-declared default
8697 // constructor. Otherwise, if no initializer is specified for
8698 // a non- static object, the object and its subobjects, if
8699 // any, have an indeterminate initial value); if the object
8700 // or any of its subobjects are of const-qualified type, the
8701 // program is ill-formed.
8702 // C++0x [dcl.init]p11:
8703 // If no initializer is specified for an object, the object is
8704 // default-initialized; [...].
8705 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8706 InitializationKind Kind
8707 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008708
8709 InitializationSequence InitSeq(*this, Entity, Kind, None);
8710 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008711 if (Init.isInvalid())
8712 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008713 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008714 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008715 // This is important for template substitution.
8716 Var->setInitStyle(VarDecl::CallInit);
8717 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008718
John McCall8b7fd8f12011-01-19 11:48:09 +00008719 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008720 }
8721}
8722
Richard Smith02e85f32011-04-14 22:09:26 +00008723void Sema::ActOnCXXForRangeDecl(Decl *D) {
8724 VarDecl *VD = dyn_cast<VarDecl>(D);
8725 if (!VD) {
8726 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8727 D->setInvalidDecl();
8728 return;
8729 }
8730
8731 VD->setCXXForRangeDecl(true);
8732
8733 // for-range-declaration cannot be given a storage class specifier.
8734 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008735 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008736 case SC_None:
8737 break;
8738 case SC_Extern:
8739 Error = 0;
8740 break;
8741 case SC_Static:
8742 Error = 1;
8743 break;
8744 case SC_PrivateExtern:
8745 Error = 2;
8746 break;
8747 case SC_Auto:
8748 Error = 3;
8749 break;
8750 case SC_Register:
8751 Error = 4;
8752 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008753 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008754 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008755 }
Richard Smith2316cd82011-09-29 19:11:37 +00008756 if (VD->isConstexpr())
8757 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008758 if (Error != -1) {
8759 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8760 << VD->getDeclName() << Error;
8761 D->setInvalidDecl();
8762 }
8763}
8764
John McCall8b7fd8f12011-01-19 11:48:09 +00008765void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8766 if (var->isInvalidDecl()) return;
8767
John McCall31168b02011-06-15 23:02:42 +00008768 // In ARC, don't allow jumps past the implicit initialization of a
8769 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008770 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008771 var->hasLocalStorage()) {
8772 switch (var->getType().getObjCLifetime()) {
8773 case Qualifiers::OCL_None:
8774 case Qualifiers::OCL_ExplicitNone:
8775 case Qualifiers::OCL_Autoreleasing:
8776 break;
8777
8778 case Qualifiers::OCL_Weak:
8779 case Qualifiers::OCL_Strong:
8780 getCurFunction()->setHasBranchProtectedScope();
8781 break;
8782 }
8783 }
8784
John McCall8a4e2e42014-01-29 08:33:09 +00008785 // Warn about externally-visible variables being defined without a
8786 // prior declaration. We only want to do this for global
8787 // declarations, but we also specifically need to avoid doing it for
8788 // class members because the linkage of an anonymous class can
8789 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008790 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008791 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008792 var->isExternallyVisible() && var->hasLinkage() &&
Manuel Klimek5704e4e2012-12-12 13:26:54 +00008793 getDiagnostics().getDiagnosticLevel(
8794 diag::warn_missing_variable_declarations,
8795 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008796 // Find a previous declaration that's not a definition.
8797 VarDecl *prev = var->getPreviousDecl();
8798 while (prev && prev->isThisDeclarationADefinition())
8799 prev = prev->getPreviousDecl();
8800
8801 if (!prev)
8802 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8803 }
8804
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008805 if (var->getTLSKind() == VarDecl::TLS_Static &&
8806 var->getType().isDestructedType()) {
8807 // GNU C++98 edits for __thread, [basic.start.term]p3:
8808 // The type of an object with thread storage duration shall not
8809 // have a non-trivial destructor.
8810 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8811 if (getLangOpts().CPlusPlus11)
8812 Diag(var->getLocation(), diag::note_use_thread_local);
8813 }
8814
John McCall8b7fd8f12011-01-19 11:48:09 +00008815 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008816 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008817
Richard Smithde63d362012-11-09 23:03:14 +00008818 QualType type = var->getType();
8819 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00008820
8821 // __block variables might require us to capture a copy-initializer.
8822 if (var->hasAttr<BlocksAttr>()) {
8823 // It's currently invalid to ever have a __block variable with an
8824 // array type; should we diagnose that here?
8825
8826 // Regardless, we don't want to ignore array nesting when
8827 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00008828 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00008829 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00008830 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00008831 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00008832 ExprResult result
8833 = PerformMoveOrCopyInitialization(
8834 InitializedEntity::InitializeBlock(poi, type, false),
8835 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00008836 if (!result.isInvalid()) {
8837 result = MaybeCreateExprWithCleanups(result);
8838 Expr *init = result.takeAs<Expr>();
8839 Context.setBlockVarCopyInits(var, init);
8840 }
8841 }
8842 }
8843
Richard Smitheda3c842011-11-07 22:16:17 +00008844 Expr *Init = var->getInit();
8845 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00008846 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00008847
Richard Smithbf830092012-10-29 18:26:47 +00008848 if (!var->getDeclContext()->isDependentContext() &&
8849 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008850 if (IsGlobal && !var->isConstexpr() &&
8851 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8852 var->getLocation())
Eli Friedman4c27ac22013-07-16 22:40:53 +00008853 != DiagnosticsEngine::Ignored) {
8854 // Warn about globals which don't have a constant initializer. Don't
8855 // warn about globals with a non-trivial destructor because we already
8856 // warned about them.
8857 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8858 if (!(RD && !RD->hasTrivialDestructor()) &&
8859 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8860 Diag(var->getLocation(), diag::warn_global_constructor)
8861 << Init->getSourceRange();
8862 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00008863
Richard Smithd0b4dd62011-12-19 06:19:21 +00008864 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008865 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00008866 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8867 SourceLocation DiagLoc = var->getLocation();
8868 // If the note doesn't add any useful information other than a source
8869 // location, fold it into the primary diagnostic.
8870 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8871 diag::note_invalid_subexpr_in_const_expr) {
8872 DiagLoc = Notes[0].first;
8873 Notes.clear();
8874 }
8875 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8876 << var << Init->getSourceRange();
8877 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8878 Diag(Notes[I].first, Notes[I].second);
8879 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00008880 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00008881 // Check whether the initializer of a const variable of integral or
8882 // enumeration type is an ICE now, since we can't tell whether it was
8883 // initialized by a constant expression if we check later.
8884 var->checkInitIsICE();
8885 }
Richard Smitheda3c842011-11-07 22:16:17 +00008886 }
John McCall8b7fd8f12011-01-19 11:48:09 +00008887
8888 // Require the destructor.
8889 if (const RecordType *recordType = baseType->getAs<RecordType>())
8890 FinalizeVarWithDestructor(var, recordType);
8891}
8892
Richard Smithb2bc2e62011-02-21 20:05:19 +00008893/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8894/// any semantic actions necessary after any initializer has been attached.
8895void
8896Sema::FinalizeDeclaration(Decl *ThisDecl) {
8897 // Note that we are no longer parsing the initializer for this declaration.
8898 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008899
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008900 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00008901 if (!VD)
8902 return;
8903
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00008904 checkAttributesAfterMerging(*this, *VD);
8905
Rafael Espindola87198cd2013-08-16 23:18:50 +00008906 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8907 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00008908 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00008909 VD->dropAttr<UsedAttr>();
8910 }
8911 }
8912
Rafael Espindolad53ffa02013-10-22 21:39:03 +00008913 if (!VD->isInvalidDecl() &&
8914 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8915 if (const VarDecl *Def = VD->getDefinition()) {
8916 if (Def->hasAttr<AliasAttr>()) {
8917 Diag(VD->getLocation(), diag::err_tentative_after_alias)
8918 << VD->getDeclName();
8919 Diag(Def->getLocation(), diag::note_previous_definition);
8920 VD->setInvalidDecl();
8921 }
8922 }
8923 }
8924
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008925 const DeclContext *DC = VD->getDeclContext();
8926 // If there's a #pragma GCC visibility in scope, and this isn't a class
8927 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00008928 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00008929 AddPushedVisibilityAttribute(VD);
8930
Rafael Espindolad2ecc132013-01-03 04:29:20 +00008931 if (VD->isFileVarDecl())
8932 MarkUnusedFileScopedDecl(VD);
8933
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008934 // Now we have parsed the initializer and can update the table of magic
8935 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00008936 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8937 !VD->getType()->isIntegralOrEnumerationType())
8938 return;
8939
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00008940 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00008941 const Expr *MagicValueExpr = VD->getInit();
8942 if (!MagicValueExpr) {
8943 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008944 }
Rafael Espindola60470f12013-01-03 04:05:19 +00008945 llvm::APSInt MagicValueInt;
8946 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8947 Diag(I->getRange().getBegin(),
8948 diag::err_type_tag_for_datatype_not_ice)
8949 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8950 continue;
8951 }
8952 if (MagicValueInt.getActiveBits() > 64) {
8953 Diag(I->getRange().getBegin(),
8954 diag::err_type_tag_for_datatype_too_large)
8955 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8956 continue;
8957 }
8958 uint64_t MagicValue = MagicValueInt.getZExtValue();
8959 RegisterTypeTagForDatatype(I->getArgumentKind(),
8960 MagicValue,
8961 I->getMatchingCType(),
8962 I->getLayoutCompatible(),
8963 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008964 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00008965}
8966
Rafael Espindolaab417692013-07-09 12:05:01 +00008967Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8968 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008969 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008970
8971 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00008972 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00008973
David Majnemer50ce8352013-09-17 23:57:10 +00008974 DeclaratorDecl *FirstDeclaratorInGroup = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00008975 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00008976 if (Decl *D = Group[i]) {
8977 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8978 if (!FirstDeclaratorInGroup)
8979 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00008980 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00008981 }
Richard Smith2abf6762011-02-23 00:37:57 +00008982
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008983 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00008984 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00008985 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00008986 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8987 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8988 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008989 }
David Blaikie095deba2012-11-14 01:52:05 +00008990
Rafael Espindolaab417692013-07-09 12:05:01 +00008991 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00008992}
8993
8994/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8995/// group, performing any necessary semantic checking.
8996Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00008997Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00008998 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00008999 // C++0x [dcl.spec.auto]p7:
9000 // If the type deduced for the template parameter U is not the same in each
9001 // deduction, the program is ill-formed.
9002 // FIXME: When initializer-list support is added, a distinction is needed
9003 // between the deduced type U and the deduced type which 'auto' stands for.
9004 // auto a = 0, b = { 1, 2, 3 };
9005 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009006 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009007 QualType Deduced;
9008 CanQualType DeducedCanon;
9009 VarDecl *DeducedDecl = 0;
Rafael Espindolaab417692013-07-09 12:05:01 +00009010 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009011 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9012 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009013 // Don't reissue diagnostics when instantiating a template.
9014 if (AT && D->isInvalidDecl())
9015 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009016 QualType U = AT ? AT->getDeducedType() : QualType();
9017 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009018 CanQualType UCanon = Context.getCanonicalType(U);
9019 if (Deduced.isNull()) {
9020 Deduced = U;
9021 DeducedCanon = UCanon;
9022 DeducedDecl = D;
9023 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009024 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9025 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009026 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009027 << Deduced << DeducedDecl->getDeclName()
9028 << U << D->getDeclName()
9029 << DeducedDecl->getInit()->getSourceRange()
9030 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009031 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009032 break;
9033 }
9034 }
9035 }
9036 }
9037 }
9038
Rafael Espindolaab417692013-07-09 12:05:01 +00009039 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009040
Rafael Espindolaab417692013-07-09 12:05:01 +00009041 return DeclGroupPtrTy::make(
9042 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009043}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009044
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009045void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009046 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009047}
9048
Rafael Espindolaab417692013-07-09 12:05:01 +00009049void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009050 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009051 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009052 return;
9053
9054 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9055 Group[0]->getLocation())
9056 == DiagnosticsEngine::Ignored)
9057 return;
9058
Rafael Espindolaab417692013-07-09 12:05:01 +00009059 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009060 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009061 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009062 // additional declaration references:
9063 // 'typedef struct S {} S;'
9064 // 'typedef struct S *S;'
9065 // 'struct S *pS;'
9066 // FinalizeDeclaratorGroup adds these as separate declarations.
9067 Decl *MaybeTagDecl = Group[0];
9068 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009069 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009070 }
9071 }
9072
9073 // See if there are any new comments that are not attached to a decl.
9074 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9075 if (!Comments.empty() &&
9076 !Comments.back()->isAttached()) {
9077 // There is at least one comment that not attached to a decl.
9078 // Maybe it should be attached to one of these decls?
9079 //
9080 // Note that this way we pick up not only comments that precede the
9081 // declaration, but also comments that *follow* the declaration -- thanks to
9082 // the lookahead in the lexer: we've consumed the semicolon and looked
9083 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009084 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009085 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009086 }
9087}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009088
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009089/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9090/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009091Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009092 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009093
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009094 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009095
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009096 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009097 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009098 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009099 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009100 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009101 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9102 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009103 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009104 Diag(DS.getStorageClassSpecLoc(),
9105 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009106 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009107 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009108
Richard Smithb4a9e862013-04-12 22:46:28 +00009109 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9110 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9111 << DeclSpec::getSpecifierName(TSCS);
9112 if (DS.isConstexprSpecified())
9113 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009114 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009115
Richard Smithb4a9e862013-04-12 22:46:28 +00009116 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009117
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009119 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009120
David Blaikiebbafb8a2012-03-11 07:00:24 +00009121 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009122 // Check that there are no default arguments inside the type of this
9123 // parameter.
9124 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009125
9126 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9127 if (D.getCXXScopeSpec().isSet()) {
9128 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9129 << D.getCXXScopeSpec().getRange();
9130 D.getCXXScopeSpec().clear();
9131 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009132 }
9133
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009134 // Ensure we have a valid name
9135 IdentifierInfo *II = 0;
9136 if (D.hasName()) {
9137 II = D.getIdentifier();
9138 if (!II) {
9139 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009140 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009141 D.setInvalidType(true);
9142 }
9143 }
9144
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009145 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009146 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009147 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9148 ForRedeclaration);
9149 LookupName(R, S);
9150 if (R.isSingleResult()) {
9151 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009152 if (PrevDecl->isTemplateParameter()) {
9153 // Maybe we will complain about the shadowed template parameter.
9154 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9155 // Just pretend that we didn't see the previous declaration.
9156 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00009157 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009158 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009159 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009160
Chris Lattnerd9773512009-01-21 02:38:50 +00009161 // Recover by removing the name
9162 II = 0;
9163 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009164 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009165 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009166 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009167 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009168
John McCallf7b2fb52010-01-22 00:28:27 +00009169 // Temporarily put parameter variables in the translation unit, not
9170 // the enclosing context. This prevents them from accidentally
9171 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009172 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009173 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009174 D.getIdentifierLoc(), II,
9175 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009176 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009177
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009178 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009179 New->setInvalidDecl();
9180
9181 assert(S->isFunctionPrototypeScope());
9182 assert(S->getFunctionPrototypeDepth() >= 1);
9183 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9184 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009185
Douglas Gregor91f84212008-12-11 16:49:14 +00009186 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009187 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009188 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009189 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009190
Douglas Gregor758a8692009-06-17 21:51:59 +00009191 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009192
Douglas Gregor41866812011-09-12 18:37:38 +00009193 if (D.getDeclSpec().isModulePrivateSpecified())
9194 Diag(New->getLocation(), diag::err_module_private_local)
9195 << 1 << New->getDeclName()
9196 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9197 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9198
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009199 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009200 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9201 }
John McCall48871652010-08-21 09:40:31 +00009202 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009203}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009204
John McCalla3ccba02010-06-04 11:21:44 +00009205/// \brief Synthesizes a variable for a parameter arising from a
9206/// typedef.
9207ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9208 SourceLocation Loc,
9209 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009210 /* FIXME: setting StartLoc == Loc.
9211 Would it be worth to modify callers so as to provide proper source
9212 location for the unnamed parameters, embedding the parameter's type? */
9213 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00009214 T, Context.getTrivialTypeSourceInfo(T, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009215 SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00009216 Param->setImplicit();
9217 return Param;
9218}
9219
John McCallc5990642010-08-24 09:05:15 +00009220void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9221 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009222 // Don't diagnose unused-parameter errors in template instantiations; we
9223 // will already have done so in the template itself.
9224 if (!ActiveTemplateInstantiations.empty())
9225 return;
9226
9227 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009228 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009229 !(*Param)->hasAttr<UnusedAttr>()) {
9230 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9231 << (*Param)->getDeclName();
9232 }
9233 }
9234}
9235
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009236void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9237 ParmVarDecl * const *ParamEnd,
9238 QualType ReturnTy,
9239 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009240 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009241 return;
9242
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009243 // Warn if the return value is pass-by-value and larger than the specified
9244 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009245 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009246 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009247 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009248 Diag(D->getLocation(), diag::warn_return_value_size)
9249 << D->getDeclName() << Size;
9250 }
9251
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009252 // Warn if any parameter is pass-by-value and larger than the specified
9253 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009254 for (; Param != ParamEnd; ++Param) {
9255 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009256 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009257 continue;
9258 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009259 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009260 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9261 << (*Param)->getDeclName() << Size;
9262 }
9263}
9264
Abramo Bagnaradff19302011-03-08 08:55:46 +00009265ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9266 SourceLocation NameLoc, IdentifierInfo *Name,
9267 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009268 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009269 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009270 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009271 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009272 T->isObjCLifetimeType()) {
9273
9274 Qualifiers::ObjCLifetime lifetime;
9275
9276 // Special cases for arrays:
9277 // - if it's const, use __unsafe_unretained
9278 // - otherwise, it's an error
9279 if (T->isArrayType()) {
9280 if (!T.isConstQualified()) {
9281 DelayedDiagnostics.add(
9282 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009283 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009284 }
9285 lifetime = Qualifiers::OCL_ExplicitNone;
9286 } else {
9287 lifetime = T->getObjCARCImplicitLifetime();
9288 }
9289 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009290 }
9291
Abramo Bagnaradff19302011-03-08 08:55:46 +00009292 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009293 Context.getAdjustedParameterType(T),
9294 TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009295 StorageClass, 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00009296
9297 // Parameters can not be abstract class types.
9298 // For record types, this is done by the AbstractClassUsageDiagnoser once
9299 // the class has been completely parsed.
9300 if (!CurContext->isRecord() &&
9301 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9302 AbstractParamType))
9303 New->setInvalidDecl();
9304
9305 // Parameter declarators cannot be interface types. All ObjC objects are
9306 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009307 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009308 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009309 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009310 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009311 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009312 T = Context.getObjCObjectPointerType(T);
9313 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009314 }
9315
9316 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9317 // duration shall not be qualified by an address-space qualifier."
9318 // Since all parameters have automatic store duration, they can not have
9319 // an address space.
9320 if (T.getAddressSpace() != 0) {
9321 Diag(NameLoc, diag::err_arg_with_address_space);
9322 New->setInvalidDecl();
9323 }
9324
9325 return New;
9326}
9327
Douglas Gregor170512f2009-04-01 23:51:29 +00009328void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9329 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009330 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009331
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009332 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9333 // for a K&R function.
9334 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009335 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009336 --i;
Alp Tokerc5350722014-02-26 22:27:52 +00009337 if (FTI.Params[i].Param == 0) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009338 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009339 llvm::raw_svector_ostream(Code)
9340 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9341 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9342 << FTI.Params[i].Ident
9343 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009344
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009345 // Implicitly declare the argument as type 'int' for lack of a better
9346 // type.
John McCall084e83d2011-03-24 11:26:52 +00009347 AttributeFactory attrs;
9348 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009349 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009350 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009351 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9352 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009353 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009354 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9355 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009356 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009357 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9358 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009359 }
9360 }
Mike Stump11289f42009-09-09 15:08:12 +00009361 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009362}
9363
Richard Smith79a52e52012-04-17 22:30:01 +00009364Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00009365 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009366 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009367 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009368
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009369 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009370 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009371 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009372}
9373
Anders Carlsson2a45e402012-12-18 01:29:20 +00009374static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9375 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009376 // Don't warn about invalid declarations.
9377 if (FD->isInvalidDecl())
9378 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009379
Anders Carlsson31c7e882009-12-09 03:30:09 +00009380 // Or declarations that aren't global.
9381 if (!FD->isGlobal())
9382 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009383
Anders Carlsson31c7e882009-12-09 03:30:09 +00009384 // Don't warn about C++ member functions.
9385 if (isa<CXXMethodDecl>(FD))
9386 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009387
Anders Carlsson31c7e882009-12-09 03:30:09 +00009388 // Don't warn about 'main'.
9389 if (FD->isMain())
9390 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009391
Anders Carlsson31c7e882009-12-09 03:30:09 +00009392 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009393 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009394 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009395
9396 // Don't warn about function templates.
9397 if (FD->getDescribedFunctionTemplate())
9398 return false;
9399
9400 // Don't warn about function template specializations.
9401 if (FD->isFunctionTemplateSpecialization())
9402 return false;
9403
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009404 // Don't warn for OpenCL kernels.
9405 if (FD->hasAttr<OpenCLKernelAttr>())
9406 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009407
Anders Carlsson31c7e882009-12-09 03:30:09 +00009408 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009409 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9410 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009411 // Ignore any declarations that occur in function or method
9412 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009413 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009414 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009415
Anders Carlsson31c7e882009-12-09 03:30:09 +00009416 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009417 if (FD->getNumParams() == 0)
9418 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009419 break;
9420 }
Richard Smith541b38b2013-09-20 01:15:31 +00009421
Anders Carlsson31c7e882009-12-09 03:30:09 +00009422 return MissingPrototype;
9423}
9424
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009425void
9426Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9427 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009428 // Don't complain if we're in GNU89 mode and the previous definition
9429 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009430 const FunctionDecl *Definition = EffectiveDefinition;
9431 if (!Definition)
9432 if (!FD->isDefined(Definition))
9433 return;
9434
9435 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009436 return;
9437
9438 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9439 Definition->getStorageClass() == SC_Extern)
9440 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009441 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009442 else
9443 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9444
9445 Diag(Definition->getLocation(), diag::note_previous_definition);
9446 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009447}
Faisal Valia17d19f2013-11-07 05:17:06 +00009448
9449
Faisal Valic1a6dc42013-10-23 16:10:50 +00009450static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9451 Sema &S) {
9452 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009453
9454 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009455 LSI->CallOperator = CallOperator;
9456 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009457 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009458 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9459
9460 if (LCD == LCD_None)
9461 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9462 else if (LCD == LCD_ByCopy)
9463 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9464 else if (LCD == LCD_ByRef)
9465 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9466 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9467
9468 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9469 LSI->Mutable = !CallOperator->isConst();
9470
Faisal Valia17d19f2013-11-07 05:17:06 +00009471 // Add the captures to the LSI so they can be noted as already
9472 // captured within tryCaptureVar.
Aaron Ballman6def98a2014-03-13 17:08:33 +00009473 for (const auto &C : LambdaClass->captures()) {
9474 if (C.capturesVariable()) {
9475 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +00009476 if (VD->isInitCapture())
9477 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9478 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +00009479 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +00009480 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +00009481 /*RefersToEnclosingLocal*/true, C.getLocation(),
9482 /*EllipsisLoc*/C.isPackExpansion()
9483 ? C.getEllipsisLoc() : SourceLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009484 CaptureType, /*Expr*/ 0);
9485
Aaron Ballman6def98a2014-03-13 17:08:33 +00009486 } else if (C.capturesThis()) {
9487 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Faisal Valia17d19f2013-11-07 05:17:06 +00009488 S.getCurrentThisType(), /*Expr*/ 0);
9489 }
9490 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009491}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009492
John McCall48871652010-08-21 09:40:31 +00009493Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009494 // Clear the last template instantiation error context.
9495 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9496
Douglas Gregor17a7c122009-06-24 00:54:41 +00009497 if (!D)
9498 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009499 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00009500
John McCall48871652010-08-21 09:40:31 +00009501 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009502 FD = FunTmpl->getTemplatedDecl();
9503 else
John McCall48871652010-08-21 09:40:31 +00009504 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009505 // If we are instantiating a generic lambda call operator, push
9506 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009507 // that's already been calculated (ActOnLambdaExpr) to prime the current
9508 // LambdaScopeInfo.
9509 // When the template operator is being specialized, the LambdaScopeInfo,
9510 // has to be properly restored so that tryCaptureVariable doesn't try
9511 // and capture any new variables. In addition when calculating potential
9512 // captures during transformation of nested lambdas, it is necessary to
9513 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009514 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009515 assert(ActiveTemplateInstantiations.size() &&
9516 "There should be an active template instantiation on the stack "
9517 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009518 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009519 }
9520 else
9521 // Enter a new function scope
9522 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009523
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009524 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009525 if (!FD->isLateTemplateParsed())
9526 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009527
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009528 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009529 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009530 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9531 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009532 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009533 FD->setInvalidDecl();
9534 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009535 }
9536
Eli Friedman9ad72442009-03-04 07:30:59 +00009537 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009538 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009539 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009540 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009541 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009542 RequireCompleteType(FD->getLocation(), ResultType,
9543 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009544 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009545
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009546 // GNU warning -Wmissing-prototypes:
9547 // Warn if a global function is defined without a previous
9548 // prototype declaration. This warning is issued even if the
9549 // definition itself provides a prototype. The aim is to detect
9550 // global functions that fail to be declared in header files.
Anders Carlsson2a45e402012-12-18 01:29:20 +00009551 const FunctionDecl *PossibleZeroParamPrototype = 0;
9552 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009553 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009554
Anders Carlsson2a45e402012-12-18 01:29:20 +00009555 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009556 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009557 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009558 if (TypeSourceInfo *TI =
9559 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9560 TypeLoc TL = TI->getTypeLoc();
9561 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9562 Diag(PossibleZeroParamPrototype->getLocation(),
9563 diag::note_declaration_not_a_prototype)
9564 << PossibleZeroParamPrototype
9565 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9566 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009567 }
9568 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009569
Douglas Gregor67da0d92009-05-15 17:59:04 +00009570 if (FnBodyScope)
9571 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009572
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009573 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009574 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9575 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009576
9577 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009578 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009579 Param->setOwningFunction(FD);
9580
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009581 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009582 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009583 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009584
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009585 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009586 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009587 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009588
James Molloy6f8780b2012-02-29 10:24:19 +00009589 // If we had any tags defined in the function prototype,
9590 // introduce them into the function scope.
9591 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009592 for (ArrayRef<NamedDecl *>::iterator
9593 I = FD->getDeclsInPrototypeScope().begin(),
9594 E = FD->getDeclsInPrototypeScope().end();
9595 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009596 NamedDecl *D = *I;
9597
9598 // Some of these decls (like enums) may have been pinned to the translation unit
9599 // for lack of a real context earlier. If so, remove from the translation unit
9600 // and reattach to the current context.
9601 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9602 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009603 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9604 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009605 Context.getTranslationUnitDecl()->removeDecl(D);
9606 break;
9607 }
9608 }
9609 // Either way, reassign the lexical decl context to our FunctionDecl.
9610 D->setLexicalDeclContext(CurContext);
9611 }
9612
9613 // If the decl has a non-null name, make accessible in the current scope.
9614 if (!D->getName().empty())
9615 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9616
9617 // Similarly, dive into enums and fish their constants out, making them
9618 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009619 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9620 for (auto *EI : ED->enumerators())
9621 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009622 }
9623 }
9624 }
9625
Richard Smith79a52e52012-04-17 22:30:01 +00009626 // Ensure that the function's exception specification is instantiated.
9627 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9628 ResolveExceptionSpec(D->getLocation(), FPT);
9629
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009630 // Checking attributes of current function definition
9631 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009632 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
Aaron Ballman9ead1242013-12-19 02:39:40 +00009633 if (DA && (!FD->hasAttr<DLLExportAttr>())) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009634 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00009635 // Microsoft accepts dllimport for functions defined within class scope.
9636 if (!DA->isInherited() &&
Francois Pichet0706d202011-09-17 17:15:52 +00009637 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009638 Diag(FD->getLocation(),
9639 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
Aaron Ballman3e424b52013-12-26 18:30:57 +00009640 << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009641 FD->setInvalidDecl();
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009642 return D;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00009643 }
9644
9645 // Visual C++ appears to not think this is an issue, so only issue
9646 // a warning when Microsoft extensions are disabled.
Francois Pichet0706d202011-09-17 17:15:52 +00009647 if (!LangOpts.MicrosoftExt) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009648 // If a symbol previously declared dllimport is later defined, the
9649 // attribute is ignored in subsequent references, and a warning is
9650 // emitted.
9651 Diag(FD->getLocation(),
9652 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Aaron Ballman44ebc072014-01-02 22:29:41 +00009653 << FD << DA;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009654 }
9655 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009656 // We want to attach documentation to original Decl (which might be
9657 // a function template).
9658 ActOnDocumentableDecl(D);
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009659 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009660}
9661
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009662/// \brief Given the set of return statements within a function body,
9663/// compute the variables that are subject to the named return value
9664/// optimization.
9665///
9666/// Each of the variables that is subject to the named return value
9667/// optimization will be marked as NRVO variables in the AST, and any
9668/// return statement that has a marked NRVO variable as its NRVO candidate can
9669/// use the named return value optimization.
9670///
9671/// This function applies a very simplistic algorithm for NRVO: if every return
9672/// statement in the function has the same NRVO candidate, that candidate is
9673/// the NRVO variable.
9674///
9675/// FIXME: Employ a smarter algorithm that accounts for multiple return
9676/// statements and the lifetimes of the NRVO candidates. We should be able to
9677/// find a maximal set of NRVO variables.
Douglas Gregor49695f02011-09-06 20:46:03 +00009678void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009679 ReturnStmt **Returns = Scope->Returns.data();
9680
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009681 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00009682 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009683 if (!Returns[I]->getNRVOCandidate())
9684 return;
9685
9686 if (!NRVOCandidate)
9687 NRVOCandidate = Returns[I]->getNRVOCandidate();
9688 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9689 return;
9690 }
9691
9692 if (NRVOCandidate)
9693 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9694}
9695
Richard Smith8e6002f2014-03-12 23:14:33 +00009696bool Sema::canDelayFunctionBody(const Declarator &D) {
9697 // We can't delay parsing the body of a constexpr function template (yet).
9698 if (D.getDeclSpec().isConstexprSpecified())
9699 return false;
9700
9701 // We can't delay parsing the body of a function template with a deduced
9702 // return type (yet).
9703 if (D.getDeclSpec().containsPlaceholderType()) {
9704 // If the placeholder introduces a non-deduced trailing return type,
9705 // we can still delay parsing it.
9706 if (D.getNumTypeObjects()) {
9707 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9708 if (Outer.Kind == DeclaratorChunk::Function &&
9709 Outer.Fun.hasTrailingReturnType()) {
9710 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9711 return Ty.isNull() || !Ty->isUndeducedType();
9712 }
9713 }
9714 return false;
9715 }
9716
9717 return true;
9718}
9719
Richard Smith1ab34b32012-11-19 21:13:18 +00009720bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009721 // We cannot skip the body of a function (or function template) which is
9722 // constexpr, since we may need to evaluate its body in order to parse the
9723 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009724 // We cannot skip the body of a function with an undeduced return type,
9725 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009726 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009727 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009728 return false;
9729 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009730}
9731
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009732Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009733 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009734 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009735 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009736 MD->setHasSkippedBody();
9737 return ActOnFinishFunctionBody(Decl, 0);
9738}
9739
John McCallfaf5fb42010-08-26 23:41:50 +00009740Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009741 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009742}
9743
John McCallb268a282010-08-23 23:25:46 +00009744Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9745 bool IsInstantiation) {
Alp Tokera2794f92014-01-22 07:29:52 +00009746 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009747
Ted Kremenek0b405322010-03-23 00:13:23 +00009748 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00009749 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00009750
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009751 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009752 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009753
Richard Smith7500ab22013-05-10 04:31:10 +00009754 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009755 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009756 // If the function has a deduced result type but contains no 'return'
9757 // statements, the result type as written must be exactly 'auto', and
9758 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009759 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009760 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009761 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009762 FD->setInvalidDecl();
9763 } else {
9764 // Substitute 'void' for the 'auto' in the type.
9765 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009766 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009767 Context.adjustDeducedFunctionResultType(
9768 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009769 }
9770 }
9771
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009772 // The only way to be included in UndefinedButUsed is if there is an
9773 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009774 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009775 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009776 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009777 UndefinedButUsed.erase(FD);
9778 else if (FD->isInlined() &&
9779 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9780 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9781 UndefinedButUsed.erase(FD);
9782 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009783
John McCall5ed3caf2012-02-14 19:50:52 +00009784 // If the function implicitly returns zero (like 'main') or is naked,
9785 // don't complain about missing return statements.
9786 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009787 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +00009788
Francois Pichet3abc9b82011-05-11 02:14:46 +00009789 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +00009790 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +00009791 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +00009792 Diag(FD->getLocation(), diag::warn_pure_function_definition);
9793
Douglas Gregor88d292c2010-05-13 16:44:06 +00009794 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009795 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009796 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009797 FD->getReturnType(), FD);
9798
Douglas Gregor88d292c2010-05-13 16:44:06 +00009799 // If this is a constructor, we need a vtable.
9800 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9801 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009802
Jordan Rosed39e5f12012-07-02 21:19:23 +00009803 // Try to apply the named return value optimization. We have to check
9804 // if we can do this here because lambdas keep return statements around
9805 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +00009806 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +00009807 !FD->isDependentContext())
9808 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00009809 }
9810
Douglas Gregor21f46922012-02-08 20:17:14 +00009811 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9812 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00009813 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00009814 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00009815 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009816 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009817 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009818 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +00009819 MD->getReturnType(), MD);
9820
Douglas Gregore3f3ea02011-09-06 20:33:37 +00009821 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +00009822 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009823 }
Jordan Rose2afd6612012-10-19 16:05:26 +00009824 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +00009825 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9826 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +00009827 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +00009828 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009829 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9830 const ObjCMethodDecl *InitMethod = 0;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00009831 bool isDesignated =
9832 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00009833 assert(isDesignated && InitMethod);
9834 (void)isDesignated;
9835 Diag(MD->getLocation(),
9836 diag::warn_objc_designated_init_missing_super_call);
9837 Diag(InitMethod->getLocation(),
9838 diag::note_objc_designated_init_marked_here);
9839 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9840 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00009841 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9842 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9843 getCurFunction()->ObjCWarnForNoInitDelegation = false;
9844 }
Ted Kremenek5a201952009-02-07 01:47:29 +00009845 } else {
John McCall48871652010-08-21 09:40:31 +00009846 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00009847 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00009848
Jordan Rose2afd6612012-10-19 16:05:26 +00009849 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +00009850 "This should only be set for ObjC methods, which should have been "
9851 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +00009852
Chris Lattnere2473062007-05-28 06:28:18 +00009853 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00009854 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009855 // C++ constructors that have function-try-blocks can't have return
9856 // statements in the handlers of that block. (C++ [except.handle]p14)
9857 // Verify this.
9858 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9859 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9860
Richard Smithdef8bdb2011-08-12 18:44:32 +00009861 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00009862 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00009863 !dcl->isInvalidDecl() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +00009864 !hasAnyUnrecoverableErrorsInThisFunction() &&
9865 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +00009866 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00009867
John McCalldeb646e2010-08-04 01:04:25 +00009868 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9869 if (!Destructor->getParent()->isDependentType())
9870 CheckDestructor(Destructor);
9871
John McCalla6309952010-03-16 21:39:52 +00009872 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9873 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00009874 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00009875
9876 // If any errors have occurred, clear out any temporaries that may have
9877 // been leftover. This ensures that these temporaries won't be picked up for
9878 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00009879 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00009880 PP.getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +00009881 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00009882 }
9883 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9884 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00009885 // Since the body is valid, issue any analysis-based warnings that are
9886 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00009887 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00009888 }
9889
Richard Smith3607ffe2012-02-13 03:54:03 +00009890 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9891 (!CheckConstexprFunctionDecl(FD) ||
9892 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00009893 FD->setInvalidDecl();
9894
John McCall28fc7092011-11-10 05:35:25 +00009895 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00009896 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +00009897 assert(MaybeODRUseExprs.empty() &&
9898 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +00009899 }
9900
John McCalle99d5f32010-03-25 22:08:03 +00009901 if (!IsInstantiation)
9902 PopDeclContext();
9903
Eli Friedman71c80552012-01-05 03:35:19 +00009904 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +00009905 // If any errors have occurred, clear out any temporaries that may have
9906 // been leftover. This ensures that these temporaries won't be picked up for
9907 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00009908 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +00009909 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +00009910 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00009911
John McCall48871652010-08-21 09:40:31 +00009912 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00009913}
9914
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009915
9916/// When we finish delayed parsing of an attribute, we must attach it to the
9917/// relevant Decl.
9918void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9919 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +00009920 // Always attach attributes to the underlying decl.
9921 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9922 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +00009923 ProcessDeclAttributeList(S, D, Attrs.getList());
9924
9925 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9926 if (Method->isStatic())
9927 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +00009928}
9929
9930
Chris Lattnerac18be92006-11-20 06:49:47 +00009931/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9932/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00009933NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00009934 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009935 // Before we produce a declaration for an implicitly defined
9936 // function, see whether there was a locally-scoped declaration of
9937 // this name as a function or variable. If so, use that
9938 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +00009939 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9940 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9941 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9942 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00009943 }
9944
Chris Lattner00e26072008-05-05 21:18:06 +00009945 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +00009946 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +00009947 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +00009948 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009949 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +00009950 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +00009951 else
Hans Wennborg70a13242011-12-08 15:56:07 +00009952 diag_id = diag::warn_implicit_function_decl;
9953 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00009954
Hans Wennborg70a13242011-12-08 15:56:07 +00009955 // Because typo correction is expensive, only do it if the implicit
9956 // function declaration is going to be treated as an error.
9957 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9958 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00009959 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +00009960 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Richard Smithf9b15102013-08-17 00:46:16 +00009961 LookupOrdinaryName, S, 0, Validator)))
9962 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9963 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +00009964 }
9965
Chris Lattnerac18be92006-11-20 06:49:47 +00009966 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00009967 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00009968 AttributeFactory attrFactory;
9969 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00009970 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +00009971 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9972 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009973 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00009974 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009975 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +00009976 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00009977 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9978 /*IsAmbiguous=*/false,
9979 /*RParenLoc=*/NoLoc,
9980 /*ArgInfo=*/0,
9981 /*NumArgs=*/0,
9982 /*EllipsisLoc=*/NoLoc,
9983 /*RParenLoc=*/NoLoc,
9984 /*TypeQuals=*/0,
9985 /*RefQualifierIsLvalueRef=*/true,
9986 /*RefQualifierLoc=*/NoLoc,
9987 /*ConstQualifierLoc=*/NoLoc,
9988 /*VolatileQualifierLoc=*/NoLoc,
9989 /*MutableLoc=*/NoLoc,
9990 EST_None,
9991 /*ESpecLoc=*/NoLoc,
9992 /*Exceptions=*/0,
9993 /*ExceptionRanges=*/0,
9994 /*NumExceptions=*/0,
9995 /*NoexceptExpr=*/0,
9996 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00009997 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00009998 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00009999 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010000
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010001 // Insert this function into translation-unit scope.
10002
10003 DeclContext *PrevDC = CurContext;
10004 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010005
Jordan Rosed03d99d2013-03-05 01:27:54 +000010006 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010007 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010008
10009 CurContext = PrevDC;
10010
Douglas Gregore711f702009-02-14 18:57:46 +000010011 AddKnownFunctionAttributes(FD);
10012
Steve Naroff3913ea42008-04-04 14:32:09 +000010013 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010014}
10015
Douglas Gregore711f702009-02-14 18:57:46 +000010016/// \brief Adds any function attributes that we know a priori based on
10017/// the declaration of this function.
10018///
10019/// These attributes can apply both to implicitly-declared builtins
10020/// (like __builtin___printf_chk) or to library-declared functions
10021/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010022///
10023/// We need to check for duplicate attributes both here and where user-written
10024/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010025void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10026 if (FD->isInvalidDecl())
10027 return;
10028
10029 // If this is a built-in function, map its builtin attributes to
10030 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010031 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010032 // Handle printf-formatting attributes.
10033 unsigned FormatIdx;
10034 bool HasVAListArg;
10035 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010036 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010037 const char *fmt = "printf";
10038 unsigned int NumParams = FD->getNumParams();
10039 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10040 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10041 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010042 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010043 &Context.Idents.get(fmt),
10044 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010045 HasVAListArg ? 0 : FormatIdx+2,
10046 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010047 }
Douglas Gregore711f702009-02-14 18:57:46 +000010048 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010049 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10050 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010051 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010052 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010053 &Context.Idents.get("scanf"),
10054 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010055 HasVAListArg ? 0 : FormatIdx+2,
10056 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010057 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010058
10059 // Mark const if we don't care about errno and that is the only
10060 // thing preventing the function from being const. This allows
10061 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010062 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010063 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010064 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010065 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010066 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010067
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010068 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010069 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010070 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10071 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010072 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010073 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010074 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010075 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010076 }
10077
10078 IdentifierInfo *Name = FD->getIdentifier();
10079 if (!Name)
10080 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010081 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010082 FD->getDeclContext()->isTranslationUnit()) ||
10083 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010084 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010085 LinkageSpecDecl::lang_c)) {
10086 // Okay: this could be a libc/libm/Objective-C function we know
10087 // about.
10088 } else
10089 return;
10090
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010091 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010092 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010093 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010094 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010095 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010096 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010097 Name->isStr("vasprintf") ? 0 : 3,
10098 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010099 }
Jordan Rose742c6072012-08-08 21:17:31 +000010100
10101 if (Name->isStr("__CFStringMakeConstantString")) {
10102 // We already have a __builtin___CFStringMakeConstantString,
10103 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010104 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010105 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10106 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010107 }
Douglas Gregore711f702009-02-14 18:57:46 +000010108}
Chris Lattner302b4be2006-11-19 02:31:38 +000010109
John McCall703a3f82009-10-24 08:00:42 +000010110TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010111 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010112 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010113 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010114
John McCallbcd03502009-12-07 02:54:59 +000010115 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010116 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010117 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010118 }
10119
Chris Lattner18b19622007-01-22 07:39:13 +000010120 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010121 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010122 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010123 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010124 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010125 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010126
John McCall04fcd0d2011-02-01 08:20:08 +000010127 // Bail out immediately if we have an invalid declaration.
10128 if (D.isInvalidType()) {
10129 NewTD->setInvalidDecl();
10130 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010131 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010132
Douglas Gregor41866812011-09-12 18:37:38 +000010133 if (D.getDeclSpec().isModulePrivateSpecified()) {
10134 if (CurContext->isFunctionOrMethod())
10135 Diag(NewTD->getLocation(), diag::err_module_private_local)
10136 << 2 << NewTD->getDeclName()
10137 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10138 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10139 else
10140 NewTD->setModulePrivate();
10141 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010142
John McCall04fcd0d2011-02-01 08:20:08 +000010143 // C++ [dcl.typedef]p8:
10144 // If the typedef declaration defines an unnamed class (or
10145 // enum), the first typedef-name declared by the declaration
10146 // to be that class type (or enum type) is used to denote the
10147 // class type (or enum type) for linkage purposes only.
10148 // We need to check whether the type was declared in the declaration.
10149 switch (D.getDeclSpec().getTypeSpecType()) {
10150 case TST_enum:
10151 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010152 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010153 case TST_union:
10154 case TST_class: {
10155 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10156
10157 // Do nothing if the tag is not anonymous or already has an
10158 // associated typedef (from an earlier typedef in this decl group).
10159 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010160 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010161
10162 // A well-formed anonymous tag must always be a TUK_Definition.
10163 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10164
10165 // The type must match the tag exactly; no qualifiers allowed.
10166 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10167 break;
10168
John McCall2575d882014-01-30 01:12:53 +000010169 // If we've already computed linkage for the anonymous tag, then
10170 // adding a typedef name for the anonymous decl can change that
10171 // linkage, which might be a serious problem. Diagnose this as
10172 // unsupported and ignore the typedef name. TODO: we should
10173 // pursue this as a language defect and establish a formal rule
10174 // for how to handle it.
10175 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10176 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10177
10178 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10179 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10180 getLangOpts());
10181
10182 llvm::SmallString<40> textToInsert;
10183 textToInsert += ' ';
10184 textToInsert += D.getIdentifier()->getName();
10185 Diag(tagLoc, diag::note_typedef_changes_linkage)
10186 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10187 break;
10188 }
10189
John McCall04fcd0d2011-02-01 08:20:08 +000010190 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010191 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010192 break;
10193 }
10194
10195 default:
10196 break;
10197 }
10198
Steve Narofff93b6722007-08-28 20:14:24 +000010199 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010200}
10201
Douglas Gregord9034f02009-05-14 16:41:31 +000010202
Richard Smith4b38ded2012-03-14 23:13:10 +000010203/// \brief Check that this is a valid underlying type for an enum declaration.
10204bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10205 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10206 QualType T = TI->getType();
10207
Eli Friedman52f32b92012-12-18 02:37:32 +000010208 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010209 return false;
10210
Eli Friedman52f32b92012-12-18 02:37:32 +000010211 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10212 if (BT->isInteger())
10213 return false;
10214
Richard Smith4b38ded2012-03-14 23:13:10 +000010215 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10216 return true;
10217}
10218
10219/// Check whether this is a valid redeclaration of a previous enumeration.
10220/// \return true if the redeclaration was invalid.
10221bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10222 QualType EnumUnderlyingTy,
10223 const EnumDecl *Prev) {
10224 bool IsFixed = !EnumUnderlyingTy.isNull();
10225
10226 if (IsScoped != Prev->isScoped()) {
10227 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10228 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010229 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010230 return true;
10231 }
10232
10233 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010234 if (!EnumUnderlyingTy->isDependentType() &&
10235 !Prev->getIntegerType()->isDependentType() &&
10236 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010237 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010238 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010239 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10240 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010241 Diag(Prev->getLocation(), diag::note_previous_declaration)
10242 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010243 return true;
10244 }
10245 } else if (IsFixed != Prev->isFixed()) {
10246 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10247 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010248 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010249 return true;
10250 }
10251
10252 return false;
10253}
10254
Joao Matosdc86f942012-08-31 18:45:21 +000010255/// \brief Get diagnostic %select index for tag kind for
10256/// redeclaration diagnostic message.
10257/// WARNING: Indexes apply to particular diagnostics only!
10258///
10259/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010260static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010261 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010262 case TTK_Struct: return 0;
10263 case TTK_Interface: return 1;
10264 case TTK_Class: return 2;
10265 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010266 }
Joao Matosdc86f942012-08-31 18:45:21 +000010267}
10268
10269/// \brief Determine if tag kind is a class-key compatible with
10270/// class for redeclaration (class, struct, or __interface).
10271///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010272/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010273static bool isClassCompatTagKind(TagTypeKind Tag)
10274{
10275 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10276}
10277
Douglas Gregord9034f02009-05-14 16:41:31 +000010278/// \brief Determine whether a tag with a given kind is acceptable
10279/// as a redeclaration of the given tag declaration.
10280///
10281/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010282bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010283 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010284 SourceLocation NewTagLoc,
10285 const IdentifierInfo &Name) {
10286 // C++ [dcl.type.elab]p3:
10287 // The class-key or enum keyword present in the
10288 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010289 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010290 // refers. This rule also applies to the form of
10291 // elaborated-type-specifier that declares a class-name or
10292 // friend class since it can be construed as referring to the
10293 // definition of the class. Thus, in any
10294 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010295 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010296 // used to refer to a union (clause 9), and either the class or
10297 // struct class-key shall be used to refer to a class (clause 9)
10298 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010299 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010300 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010301 if (OldTag == NewTag)
10302 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010303
Joao Matosdc86f942012-08-31 18:45:21 +000010304 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010305 // Warn about the struct/class tag mismatch.
10306 bool isTemplate = false;
10307 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10308 isTemplate = Record->getDescribedClassTemplate();
10309
Richard Trieucaa33d32011-06-10 03:11:26 +000010310 if (!ActiveTemplateInstantiations.empty()) {
10311 // In a template instantiation, do not offer fix-its for tag mismatches
10312 // since they usually mess up the template instead of fixing the problem.
10313 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010314 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10315 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010316 return true;
10317 }
10318
10319 if (isDefinition) {
10320 // On definitions, check previous tags and issue a fix-it for each
10321 // one that doesn't match the current tag.
10322 if (Previous->getDefinition()) {
10323 // Don't suggest fix-its for redefinitions.
10324 return true;
10325 }
10326
10327 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010328 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010329 if (I->getTagKind() != NewTag) {
10330 if (!previousMismatch) {
10331 previousMismatch = true;
10332 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010333 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10334 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010335 }
10336 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010337 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010338 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010339 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010340 }
10341 }
10342 return true;
10343 }
10344
10345 // Check for a previous definition. If current tag and definition
10346 // are same type, do nothing. If no definition, but disagree with
10347 // with previous tag type, give a warning, but no fix-it.
10348 const TagDecl *Redecl = Previous->getDefinition() ?
10349 Previous->getDefinition() : Previous;
10350 if (Redecl->getTagKind() == NewTag) {
10351 return true;
10352 }
10353
Douglas Gregord9034f02009-05-14 16:41:31 +000010354 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010355 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10356 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010357 Diag(Redecl->getLocation(), diag::note_previous_use);
10358
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010359 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010360 if (Previous->getDefinition()) {
10361 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010362 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010363 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010364 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010365 }
10366
Douglas Gregord9034f02009-05-14 16:41:31 +000010367 return true;
10368 }
10369 return false;
10370}
10371
Steve Naroff30d242c2007-09-15 18:49:24 +000010372/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010373/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010374/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010375/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010376///
10377/// IsTypeSpecifier is true if this is a type-specifier (or
10378/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010379Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010380 SourceLocation KWLoc, CXXScopeSpec &SS,
10381 IdentifierInfo *Name, SourceLocation NameLoc,
10382 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010383 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010384 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010385 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010386 SourceLocation ScopedEnumKWLoc,
10387 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010388 TypeResult UnderlyingType,
10389 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010390 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010391 IdentifierInfo *OrigName = Name;
John McCall9bb74a52009-07-31 02:45:11 +000010392 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010393 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010394 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010395
Douglas Gregord6ab8742009-05-28 23:31:59 +000010396 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010397 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010398 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010399
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010400 // FIXME: Check explicit specializations more carefully.
10401 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010402 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010403
10404 // We only need to do this matching if we have template parameters
10405 // or a scope specifier, which also conveniently avoids this work
10406 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010407 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010408 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010409 if (TemplateParameterList *TemplateParams =
10410 MatchTemplateParametersToScopeSpecifier(
10411 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10412 isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010413 if (Kind == TTK_Enum) {
10414 Diag(KWLoc, diag::err_enum_template);
10415 return 0;
10416 }
10417
Douglas Gregor3dad8422009-09-26 06:47:28 +000010418 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010419 // This is a declaration or definition of a class template (which may
10420 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010421
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010422 if (Invalid)
John McCall48871652010-08-21 09:40:31 +000010423 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010424
Douglas Gregore93e46c2009-07-22 23:48:44 +000010425 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010426 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010427 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010428 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010429 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010430 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010431 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010432 return Result.get();
10433 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010434 // The "template<>" header is extraneous.
10435 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010436 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010437 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010438 }
Mike Stump11289f42009-09-09 15:08:12 +000010439 }
10440 }
10441
Douglas Gregor0bf31402010-10-08 23:50:27 +000010442 // Figure out the underlying type if this a enum declaration. We need to do
10443 // this early, because it's needed to detect if this is an incompatible
10444 // redeclaration.
10445 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10446
10447 if (Kind == TTK_Enum) {
10448 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10449 // No underlying type explicitly specified, or we failed to parse the
10450 // type, default to int.
10451 EnumUnderlying = Context.IntTy.getTypePtr();
10452 else if (UnderlyingType.get()) {
10453 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10454 // integral type; any cv-qualification is ignored.
10455 TypeSourceInfo *TI = 0;
Richard Smitheece8c32012-03-15 00:22:18 +000010456 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010457 EnumUnderlying = TI;
10458
Richard Smith4b38ded2012-03-14 23:13:10 +000010459 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010460 // Recover by falling back to int.
10461 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010462
Richard Smith4b38ded2012-03-14 23:13:10 +000010463 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010464 UPPC_FixedUnderlyingType))
10465 EnumUnderlying = Context.IntTy.getTypePtr();
10466
Alp Tokerbfa39342014-01-14 12:51:41 +000010467 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010468 // Microsoft enums are always of int type.
10469 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010470 }
10471
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010472 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010473 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010474 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010475
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010476 RedeclarationKind Redecl = ForRedeclaration;
10477 if (TUK == TUK_Friend || TUK == TUK_Reference)
10478 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010479
10480 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010481 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010482 if (Name && SS.isNotEmpty()) {
10483 // We have a nested-name tag ('struct foo::bar').
10484
10485 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010486 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010487 Name = 0;
10488 goto CreateNewDecl;
10489 }
10490
John McCall7f41d982009-09-11 04:59:25 +000010491 // If this is a friend or a reference to a class in a dependent
10492 // context, don't try to make a decl for it.
10493 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10494 DC = computeDeclContext(SS, false);
10495 if (!DC) {
10496 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010497 return 0;
John McCall7f41d982009-09-11 04:59:25 +000010498 }
John McCall0b66eb32010-05-01 00:40:08 +000010499 } else {
10500 DC = computeDeclContext(SS, true);
10501 if (!DC) {
10502 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10503 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +000010504 return 0;
John McCall0b66eb32010-05-01 00:40:08 +000010505 }
John McCall7f41d982009-09-11 04:59:25 +000010506 }
10507
John McCall0b66eb32010-05-01 00:40:08 +000010508 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +000010509 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010510
Douglas Gregor8761da52009-02-03 00:34:39 +000010511 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010512 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010513 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010514
John McCall1f82f242009-11-18 22:49:29 +000010515 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010516 return 0;
John McCall6538c932009-10-10 05:48:19 +000010517
John McCall1f82f242009-11-18 22:49:29 +000010518 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010519 // Name lookup did not find anything. However, if the
10520 // nested-name-specifier refers to the current instantiation,
10521 // and that current instantiation has any dependent base
10522 // classes, we might find something at instantiation time: treat
10523 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010524 // But this only makes any sense for reference-like lookups.
10525 if (Previous.wasNotFoundInCurrentInstantiation() &&
10526 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010527 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +000010528 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010529 }
10530
10531 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010532 Diag(NameLoc, diag::err_not_tag_in_scope)
10533 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010534 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010535 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010536 goto CreateNewDecl;
10537 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010538 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010539 // If this is a named struct, check to see if there was a previous forward
10540 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010541 // FIXME: We're looking into outer scopes here, even when we
10542 // shouldn't be. Doing so can result in ambiguities that we
10543 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010544 LookupName(Previous, S);
10545
John McCall3c581bf2013-03-20 01:53:00 +000010546 // When declaring or defining a tag, ignore ambiguities introduced
10547 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010548 if (Previous.isAmbiguous() &&
10549 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010550 LookupResult::Filter F = Previous.makeFilter();
10551 while (F.hasNext()) {
10552 NamedDecl *ND = F.next();
10553 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10554 F.erase();
10555 }
10556 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010557 }
John McCall3c581bf2013-03-20 01:53:00 +000010558
10559 // C++11 [namespace.memdef]p3:
10560 // If the name in a friend declaration is neither qualified nor
10561 // a template-id and the declaration is a function or an
10562 // elaborated-type-specifier, the lookup to determine whether
10563 // the entity has been previously declared shall not consider
10564 // any scopes outside the innermost enclosing namespace.
10565 //
10566 // Does it matter that this should be by scope instead of by
10567 // semantic context?
10568 if (!Previous.empty() && TUK == TUK_Friend) {
10569 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10570 LookupResult::Filter F = Previous.makeFilter();
10571 while (F.hasNext()) {
10572 NamedDecl *ND = F.next();
10573 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010574 if (DC->isFileContext() &&
10575 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010576 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010577 FriendSawTagOutsideEnclosingNamespace = true;
10578 }
John McCall3c581bf2013-03-20 01:53:00 +000010579 }
10580 F.done();
10581 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010582
John McCall1f82f242009-11-18 22:49:29 +000010583 // Note: there used to be some attempt at recovery here.
10584 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +000010585 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010586
David Blaikiebbafb8a2012-03-11 07:00:24 +000010587 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010588 // FIXME: This makes sure that we ignore the contexts associated
10589 // with C structs, unions, and enums when looking for a matching
10590 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010591 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010592 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10593 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010594 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010595 } else if (S->isFunctionPrototypeScope()) {
10596 // If this is an enum declaration in function prototype scope, set its
10597 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010598 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010599 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010600 }
10601
John McCall1f82f242009-11-18 22:49:29 +000010602 if (Previous.isSingleResult() &&
10603 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010604 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010605 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010606 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010607 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010608 }
10609
David Blaikiebbafb8a2012-03-11 07:00:24 +000010610 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010611 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010612 // This is a declaration of or a reference to "std::bad_alloc".
10613 isStdBadAlloc = true;
10614
John McCall1f82f242009-11-18 22:49:29 +000010615 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010616 // std::bad_alloc has been implicitly declared (but made invisible to
10617 // name lookup). Fill in this implicit declaration as the previous
10618 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010619 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010620 }
10621 }
John McCall1f82f242009-11-18 22:49:29 +000010622
John McCalle9eaf8e2010-03-25 21:28:06 +000010623 // If we didn't find a previous declaration, and this is a reference
10624 // (or friend reference), move to the correct scope. In C++, we
10625 // also need to do a redeclaration lookup there, just in case
10626 // there's a shadow friend decl.
10627 if (Name && Previous.empty() &&
10628 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10629 if (Invalid) goto CreateNewDecl;
10630 assert(SS.isEmpty());
10631
10632 if (TUK == TUK_Reference) {
10633 // C++ [basic.scope.pdecl]p5:
10634 // -- for an elaborated-type-specifier of the form
10635 //
10636 // class-key identifier
10637 //
10638 // if the elaborated-type-specifier is used in the
10639 // decl-specifier-seq or parameter-declaration-clause of a
10640 // function defined in namespace scope, the identifier is
10641 // declared as a class-name in the namespace that contains
10642 // the declaration; otherwise, except as a friend
10643 // declaration, the identifier is declared in the smallest
10644 // non-class, non-function-prototype scope that contains the
10645 // declaration.
10646 //
10647 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10648 // C structs and unions.
10649 //
10650 // It is an error in C++ to declare (rather than define) an enum
10651 // type, including via an elaborated type specifier. We'll
10652 // diagnose that later; for now, declare the enum in the same
10653 // scope as we would have picked for any other tag type.
10654 //
10655 // GNU C also supports this behavior as part of its incomplete
10656 // enum types extension, while GNU C++ does not.
10657 //
10658 // Find the context where we'll be declaring the tag.
10659 // FIXME: We would like to maintain the current DeclContext as the
10660 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010661 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010662 SearchDC = SearchDC->getParent();
10663
10664 // Find the scope where we'll be declaring the tag.
10665 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010666 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010667 S->isFunctionPrototypeScope()) ||
10668 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010669 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010670 S = S->getParent();
10671 } else {
10672 assert(TUK == TUK_Friend);
10673 // C++ [namespace.memdef]p3:
10674 // If a friend declaration in a non-local class first declares a
10675 // class or function, the friend class or function is a member of
10676 // the innermost enclosing namespace.
10677 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010678 }
10679
John McCalle87beb22010-04-23 18:46:30 +000010680 // In C++, we need to do a redeclaration lookup to properly
10681 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010682 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010683 Previous.setRedeclarationKind(ForRedeclaration);
10684 LookupQualifiedName(Previous, SearchDC);
10685 }
10686 }
10687
John McCall1f82f242009-11-18 22:49:29 +000010688 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010689 NamedDecl *PrevDecl = Previous.getFoundDecl();
10690 NamedDecl *DirectPrevDecl =
10691 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010692
10693 // It's okay to have a tag decl in the same scope as a typedef
10694 // which hides a tag decl in the same scope. Finding this
10695 // insanity with a redeclaration lookup can only actually happen
10696 // in C++.
10697 //
10698 // This is also okay for elaborated-type-specifiers, which is
10699 // technically forbidden by the current standard but which is
10700 // okay according to the likely resolution of an open issue;
10701 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010702 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010703 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010704 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10705 TagDecl *Tag = TT->getDecl();
10706 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010707 Tag->getDeclContext()->getRedeclContext()
10708 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010709 PrevDecl = Tag;
10710 Previous.clear();
10711 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010712 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010713 }
10714 }
10715 }
10716 }
10717
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010718 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010719 // If this is a use of a previous tag, or if the tag is already declared
10720 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010721 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010722 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010723 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010724 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010725 // Make sure that this wasn't declared as an enum and now used as a
10726 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010727 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10728 TUK == TUK_Definition, KWLoc,
10729 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010730 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010731 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10732 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010733 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010734 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010735 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010736 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10737 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010738 else
10739 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010740 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010741
Mike Stump11289f42009-09-09 15:08:12 +000010742 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010743 Kind = PrevTagDecl->getTagKind();
10744 else {
10745 // Recover by making this an anonymous redefinition.
10746 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010747 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010748 Invalid = true;
10749 }
10750 }
10751
Douglas Gregor0bf31402010-10-08 23:50:27 +000010752 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10753 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10754
Richard Smith0f8ee222012-01-10 01:33:14 +000010755 // If this is an elaborated-type-specifier for a scoped enumeration,
10756 // the 'class' keyword is not necessary and not permitted.
10757 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10758 if (ScopedEnum)
10759 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10760 << PrevEnum->isScoped()
10761 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10762 return PrevTagDecl;
10763 }
10764
Richard Smith4b38ded2012-03-14 23:13:10 +000010765 QualType EnumUnderlyingTy;
10766 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010767 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010768 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10769 EnumUnderlyingTy = QualType(T, 0);
10770
Douglas Gregor0bf31402010-10-08 23:50:27 +000010771 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000010772 // returning the previous declaration, unless this is a definition,
10773 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000010774 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10775 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Richard Smithb66d7772012-03-23 23:09:08 +000010776 return TUK == TUK_Declaration ? PrevTagDecl : 0;
Douglas Gregor0bf31402010-10-08 23:50:27 +000010777 }
10778
David Majnemer55890bf2013-06-11 03:51:23 +000010779 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000010780 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000010781 // except that a nested class or member class template can be declared
10782 // and then later defined.
10783 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10784 S->isDeclScope(PrevDecl)) {
10785 Diag(NameLoc, diag::ext_member_redeclared);
10786 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10787 }
10788
Douglas Gregor170512f2009-04-01 23:51:29 +000010789 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010790 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +000010791
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010792 // FIXME: In the future, return a variant or some other clue
10793 // for the consumer of this Decl to know it doesn't own it.
10794 // For our current ASTs this shouldn't be a problem, but will
10795 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +000010796 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010797 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +000010798 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010799
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010800 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000010801 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000010802 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010803 // If we're defining a specialization and the previous definition
10804 // is from an implicit instantiation, don't emit an error
10805 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000010806 bool IsExplicitSpecializationAfterInstantiation = false;
10807 if (isExplicitSpecialization) {
10808 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10809 IsExplicitSpecializationAfterInstantiation =
10810 RD->getTemplateSpecializationKind() !=
10811 TSK_ExplicitSpecialization;
10812 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10813 IsExplicitSpecializationAfterInstantiation =
10814 ED->getTemplateSpecializationKind() !=
10815 TSK_ExplicitSpecialization;
10816 }
10817
10818 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000010819 // A redeclaration in function prototype scope in C isn't
10820 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010821 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000010822 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10823 else
10824 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000010825 Diag(Def->getLocation(), diag::note_previous_definition);
10826 // If this is a redefinition, recover by making this
10827 // struct be anonymous, which will make any later
10828 // references get the previous definition.
10829 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010830 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000010831 Invalid = true;
10832 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010833 } else {
10834 // If the type is currently being defined, complain
10835 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000010836 const TagType *Tag
10837 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000010838 if (Tag->isBeingDefined()) {
10839 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000010840 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000010841 diag::note_previous_definition);
10842 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +000010843 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000010844 Invalid = true;
10845 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010846 }
Douglas Gregordee1be82009-01-17 00:42:38 +000010847
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010848 // Okay, this is definition of a previously declared or referenced
10849 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +000010850 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010851 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010852 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000010853 // have a definition. Just create a new decl.
10854
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010855 } else {
10856 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000010857 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010858 // new decl/type. We set PrevDecl to NULL so that the entities
10859 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000010860 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000010861 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010862 // If we get here, we're going to create a new Decl. If PrevDecl
10863 // is non-NULL, it's a definition of the tag declared by
10864 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000010865
10866
10867 // Otherwise, PrevDecl is not a tag, but was found with tag
10868 // lookup. This is only actually possible in C++, where a few
10869 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010870 } else {
John McCalle87beb22010-04-23 18:46:30 +000010871 // Use a better diagnostic if an elaborated-type-specifier
10872 // found the wrong kind of type on the first
10873 // (non-redeclaration) lookup.
10874 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10875 !Previous.isForRedeclaration()) {
10876 unsigned Kind = 0;
10877 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010878 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10879 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010880 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10881 Diag(PrevDecl->getLocation(), diag::note_declared_at);
10882 Invalid = true;
10883
10884 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000010885 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10886 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000010887 // do nothing
10888
10889 // Diagnose implicit declarations introduced by elaborated types.
10890 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10891 unsigned Kind = 0;
10892 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000010893 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10894 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000010895 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10896 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10897 Invalid = true;
10898
10899 // Otherwise it's a declaration. Call out a particularly common
10900 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000010901 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10902 unsigned Kind = 0;
10903 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000010904 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000010905 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000010906 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10907 Invalid = true;
10908
10909 // Otherwise, diagnose.
10910 } else {
10911 // The tag name clashes with something else in the target scope,
10912 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000010913 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000010914 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010915 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +000010916 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000010917 }
John McCalle87beb22010-04-23 18:46:30 +000010918
10919 // The existing declaration isn't relevant to us; we're in a
10920 // new scope, so clear out the previous declaration.
10921 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000010922 }
Chris Lattner18b19622007-01-22 07:39:13 +000010923 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000010924
Chris Lattner438e5012008-12-17 07:13:27 +000010925CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000010926
John McCall1f82f242009-11-18 22:49:29 +000010927 TagDecl *PrevDecl = 0;
10928 if (Previous.isSingleResult())
10929 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10930
Chris Lattnerbf0b7982007-01-23 04:27:41 +000010931 // If there is an identifier, use the location of the identifier as the
10932 // location of the decl, otherwise use the location of the struct/union
10933 // keyword.
10934 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000010935
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010936 // Otherwise, create a new declaration. If there is a previous
10937 // declaration of the same entity, the two will be linked via
10938 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000010939 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000010940
Douglas Gregor0bf31402010-10-08 23:50:27 +000010941 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010942 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000010943 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10944 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010945 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000010946 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010947 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000010948 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010949 if (TUK != TUK_Definition && !Invalid) {
10950 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000010951 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10952 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000010953 // C++0x: 7.2p2: opaque-enum-declaration.
10954 // Conflicts are diagnosed above. Do nothing.
10955 }
10956 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010957 Diag(Loc, diag::ext_forward_ref_enum_def)
10958 << New;
10959 Diag(Def->getLocation(), diag::note_previous_definition);
10960 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000010961 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000010962 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000010963 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010964 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000010965 DiagID = diag::err_forward_ref_enum;
10966 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010967
10968 // If this is a forward-declared reference to an enumeration, make a
10969 // note of it; we won't actually be introducing the declaration into
10970 // the declaration context.
10971 if (TUK == TUK_Reference)
10972 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000010973 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000010974 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000010975
10976 if (EnumUnderlying) {
10977 EnumDecl *ED = cast<EnumDecl>(New);
10978 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10979 ED->setIntegerTypeSourceInfo(TI);
10980 else
10981 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10982 ED->setPromotionType(ED->getIntegerType());
10983 }
10984
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000010985 } else {
10986 // struct/union/class
10987
Chris Lattner776fac82007-06-09 00:53:06 +000010988 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10989 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010990 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000010991 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010992 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010993 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010994
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010995 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000010996 StdBadAlloc = cast<CXXRecordDecl>(New);
10997 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000010998 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010999 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011000 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011001
Richard Smith649c7b062014-01-08 00:56:48 +000011002 // C++11 [dcl.type]p3:
11003 // A type-specifier-seq shall not define a class or enumeration [...].
11004 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11005 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11006 << Context.getTagDeclType(New);
11007 Invalid = true;
11008 }
11009
John McCall3e11ebe2010-03-15 10:12:16 +000011010 // Maybe add qualifier info.
11011 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011012 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011013 // If this is either a declaration or a definition, check the
11014 // nested-name-specifier against the current context. We don't do this
11015 // for explicit specializations, because they have similar checking
11016 // (with more specific diagnostics) in the call to
11017 // CheckMemberSpecialization, below.
11018 if (!isExplicitSpecialization &&
11019 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11020 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11021 Invalid = true;
11022
Douglas Gregor14454802011-02-25 02:25:35 +000011023 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011024 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011025 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011026 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011027 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011028 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011029 }
11030 else
11031 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011032 }
11033
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011034 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11035 // Add alignment attributes if necessary; these attributes are checked when
11036 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011037 //
11038 // It is important for implementing the correct semantics that this
11039 // happen here (in act on tag decl). The #pragma pack stack is
11040 // maintained as a result of parser callbacks which can occur at
11041 // many points during the parsing of a struct declaration (because
11042 // the #pragma tokens are effectively skipped over during the
11043 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011044 if (TUK == TUK_Definition) {
11045 AddAlignmentAttributesForRecord(RD);
11046 AddMsStructLayoutForRecord(RD);
11047 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011048 }
11049
Douglas Gregor21823bf2011-12-20 18:11:52 +000011050 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011051 if (isExplicitSpecialization)
11052 Diag(New->getLocation(), diag::err_module_private_specialization)
11053 << 2
11054 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011055 // __module_private__ does not apply to local classes. However, we only
11056 // diagnose this as an error when the declaration specifiers are
11057 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011058 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011059 New->setModulePrivate();
11060 }
11061
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011062 // If this is a specialization of a member class (of a class template),
11063 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011064 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011065 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011066
Douglas Gregordee1be82009-01-17 00:42:38 +000011067 if (Invalid)
11068 New->setInvalidDecl();
11069
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011070 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011071 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011072
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011073 // If we're declaring or defining a tag in function prototype scope in C,
11074 // note that this type can only be used within the function and add it to
11075 // the list of decls to inject into the function definition scope.
11076 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11077 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
Douglas Gregor658b9552009-01-09 22:42:13 +000011078 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011079 DeclsInPrototypeScope.push_back(New);
11080 }
Douglas Gregor658b9552009-01-09 22:42:13 +000011081
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011082 // Set the lexical context. If the tag has a C++ scope specifier, the
11083 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011084 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011085
John McCallaa74a0c2009-08-28 07:59:38 +000011086 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011087 // In Microsoft mode, a friend declaration also acts as a forward
11088 // declaration so we always pass true to setObjectOfFriendDecl to make
11089 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011090 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011091 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11092 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011093
Anders Carlsson5558ca12009-03-26 01:19:02 +000011094 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011095 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011096 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011097
John McCall9bb74a52009-07-31 02:45:11 +000011098 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011099 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011100
Chris Lattner18b19622007-01-22 07:39:13 +000011101 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011102 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011103 // We might be replacing an existing declaration in the lookup tables;
11104 // if so, borrow its access specifier.
11105 if (PrevDecl)
11106 New->setAccess(PrevDecl->getAccess());
11107
Sebastian Redl50c68252010-08-31 00:36:30 +000011108 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011109 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011110 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011111 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11112 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011113 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011114 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011115 PushOnScopeChains(New, S, !IsForwardReference);
11116 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011117 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011118
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011119 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011120 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011121 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011122
Douglas Gregor27821ce2009-07-07 16:35:42 +000011123 // If this is the C FILE type, notify the AST context.
11124 if (IdentifierInfo *II = New->getIdentifier())
11125 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011126 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011127 II->isStr("FILE"))
11128 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011129
Rafael Espindolac67f2232012-05-10 02:50:16 +000011130 if (PrevDecl)
11131 mergeDeclAttributes(New, PrevDecl);
11132
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011133 // If there's a #pragma GCC visibility in scope, set the visibility of this
11134 // record.
11135 AddPushedVisibilityAttribute(New);
11136
Douglas Gregord6ab8742009-05-28 23:31:59 +000011137 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011138 // In C++, don't return an invalid declaration. We can't recover well from
11139 // the cases where we make the type anonymous.
11140 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011141}
Chris Lattner1300fb92007-01-23 23:42:53 +000011142
John McCall48871652010-08-21 09:40:31 +000011143void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011144 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011145 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011146
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011147 // Enter the tag context.
11148 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011149
11150 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011151
11152 // If there's a #pragma GCC visibility in scope, set the visibility of this
11153 // record.
11154 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011155}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011156
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011157Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011158 assert(isa<ObjCContainerDecl>(IDecl) &&
11159 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11160 DeclContext *OCD = cast<DeclContext>(IDecl);
11161 assert(getContainingDC(OCD) == CurContext &&
11162 "The next DeclContext should be lexically contained in the current one.");
11163 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011164 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011165}
11166
John McCall48871652010-08-21 09:40:31 +000011167void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011168 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011169 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011170 SourceLocation LBraceLoc) {
11171 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011172 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011173
John McCall1c7e6ec2009-12-20 07:58:13 +000011174 FieldCollector->StartClass();
11175
11176 if (!Record->getIdentifier())
11177 return;
11178
Anders Carlsson30f29442011-03-25 14:31:08 +000011179 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011180 Record->addAttr(new (Context)
11181 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11182
John McCall1c7e6ec2009-12-20 07:58:13 +000011183 // C++ [class]p2:
11184 // [...] The class-name is also inserted into the scope of the
11185 // class itself; this is known as the injected-class-name. For
11186 // purposes of access checking, the injected-class-name is treated
11187 // as if it were a public member name.
11188 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011189 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11190 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011191 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011192 /*PrevDecl=*/0,
11193 /*DelayTypeCreation=*/true);
11194 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011195 InjectedClassName->setImplicit();
11196 InjectedClassName->setAccess(AS_public);
11197 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11198 InjectedClassName->setDescribedClassTemplate(Template);
11199 PushOnScopeChains(InjectedClassName, S);
11200 assert(InjectedClassName->isInjectedClassName() &&
11201 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011202}
11203
John McCall48871652010-08-21 09:40:31 +000011204void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011205 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011206 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011207 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011208 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011209
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011210 // Make sure we "complete" the definition even it is invalid.
11211 if (Tag->isBeingDefined()) {
11212 assert(Tag->isInvalidDecl() && "We should already have completed it");
11213 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11214 RD->completeDefinition();
11215 }
11216
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011217 if (isa<CXXRecordDecl>(Tag))
11218 FieldCollector->FinishClass();
11219
11220 // Exit this scope of this tag's definition.
11221 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011222
11223 if (getCurLexicalContext()->isObjCContainer() &&
11224 Tag->getDeclContext()->isFileContext())
11225 Tag->setTopLevelDeclInObjCContainer();
11226
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011227 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011228 if (!Tag->isInvalidDecl())
11229 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011230}
Chris Lattner535b8302008-06-21 19:39:06 +000011231
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011232void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011233 // Exit this scope of this interface definition.
11234 PopDeclContext();
11235}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011236
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011237void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011238 assert(DC == CurContext && "Mismatch of container contexts");
11239 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011240 ActOnObjCContainerFinishDefinition();
11241}
11242
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011243void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11244 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011245 OriginalLexicalContext = 0;
11246}
11247
John McCall48871652010-08-21 09:40:31 +000011248void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011249 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011250 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011251 Tag->setInvalidDecl();
11252
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011253 // Make sure we "complete" the definition even it is invalid.
11254 if (Tag->isBeingDefined()) {
11255 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11256 RD->completeDefinition();
11257 }
11258
John McCall71ba5f22010-03-17 19:25:57 +000011259 // We're undoing ActOnTagStartDefinition here, not
11260 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11261 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011262
11263 PopDeclContext();
11264}
11265
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011266// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011267ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11268 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011269 QualType FieldTy, bool IsMsStruct,
11270 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011271 // Default to true; that shouldn't confuse checks for emptiness
11272 if (ZeroWidth)
11273 *ZeroWidth = true;
11274
Chris Lattner73bf7b42009-03-05 22:45:59 +000011275 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011276 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011277 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011278 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011279 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011280 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011281 if (FieldName)
11282 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11283 << FieldName << FieldTy << BitWidth->getSourceRange();
11284 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11285 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011286 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11287 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011288 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011289
11290 // If the bit-width is type- or value-dependent, don't try to check
11291 // it now.
11292 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Richard Smithf4c51d92012-02-04 09:53:13 +000011293 return Owned(BitWidth);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011294
Anders Carlsson5df391e2008-12-06 20:33:04 +000011295 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011296 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11297 if (ICE.isInvalid())
11298 return ICE;
11299 BitWidth = ICE.take();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011300
Eli Friedmanc96d4962009-08-15 21:55:26 +000011301 if (Value != 0 && ZeroWidth)
11302 *ZeroWidth = false;
11303
Chris Lattner81ed6802008-12-12 04:56:04 +000011304 // Zero-width bitfield is ok for anonymous field.
11305 if (Value == 0 && FieldName)
11306 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011307
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011308 if (Value.isSigned() && Value.isNegative()) {
11309 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011310 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011311 << FieldName << Value.toString(10);
11312 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11313 << Value.toString(10);
11314 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011315
Douglas Gregor1efa4372009-03-11 18:59:21 +000011316 if (!FieldTy->isDependentType()) {
11317 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011318 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011319 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11320 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011321 if (FieldName)
11322 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11323 << FieldName << (unsigned)Value.getZExtValue()
11324 << (unsigned)TypeSize;
11325
11326 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11327 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11328 }
11329
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011330 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011331 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11332 << FieldName << (unsigned)Value.getZExtValue()
11333 << (unsigned)TypeSize;
11334 else
11335 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11336 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011337 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011338 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011339
Richard Smithf4c51d92012-02-04 09:53:13 +000011340 return Owned(BitWidth);
Anders Carlsson5df391e2008-12-06 20:33:04 +000011341}
11342
Richard Smith938f40b2011-06-11 17:19:42 +000011343/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011344/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011345Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011346 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011347 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011348 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011349 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011350 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011351}
11352
11353/// HandleField - Analyze a field of a C struct or a C++ data member.
11354///
11355FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11356 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011357 Declarator &D, Expr *BitWidth,
11358 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011359 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011360 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011361 SourceLocation Loc = DeclStart;
11362 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011363
John McCall8cb7bdf2010-06-04 23:28:52 +000011364 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11365 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011366 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011367 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011368
Douglas Gregora02a72a2010-12-15 23:18:36 +000011369 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11370 UPPC_DataMemberType)) {
11371 D.setInvalidType();
11372 T = Context.IntTy;
11373 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11374 }
11375 }
11376
Matt Arsenault376f7202013-02-26 21:16:00 +000011377 // TR 18037 does not allow fields to be declared with address spaces.
11378 if (T.getQualifiers().hasAddressSpace()) {
11379 Diag(Loc, diag::err_field_with_address_space);
11380 D.setInvalidType();
11381 }
11382
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011383 // OpenCL 1.2 spec, s6.9 r:
11384 // The event type cannot be used to declare a structure or union field.
11385 if (LangOpts.OpenCL && T->isEventT()) {
11386 Diag(Loc, diag::err_event_t_struct_field);
11387 D.setInvalidType();
11388 }
11389
Richard Smithb1402ae2013-03-18 22:52:47 +000011390 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011391
Richard Smithb4a9e862013-04-12 22:46:28 +000011392 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11393 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11394 diag::err_invalid_thread)
11395 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011396
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011397 // Check to see if this name was declared as a member previously
Douglas Gregorfbf87522011-10-21 15:47:52 +000011398 NamedDecl *PrevDecl = 0;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011399 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11400 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011401 switch (Previous.getResultKind()) {
11402 case LookupResult::Found:
11403 case LookupResult::FoundUnresolvedValue:
11404 PrevDecl = Previous.getAsSingle<NamedDecl>();
11405 break;
11406
11407 case LookupResult::FoundOverloaded:
11408 PrevDecl = Previous.getRepresentativeDecl();
11409 break;
11410
11411 case LookupResult::NotFound:
11412 case LookupResult::NotFoundInCurrentInstantiation:
11413 case LookupResult::Ambiguous:
11414 break;
11415 }
11416 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011417
11418 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11419 // Maybe we will complain about the shadowed template parameter.
11420 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11421 // Just pretend that we didn't see the previous declaration.
11422 PrevDecl = 0;
11423 }
11424
Douglas Gregor1efa4372009-03-11 18:59:21 +000011425 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11426 PrevDecl = 0;
11427
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011428 bool Mutable
11429 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011430 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011431 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011432 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011433 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011434
11435 if (NewFD->isInvalidDecl())
11436 Record->setInvalidDecl();
11437
Douglas Gregor3baa6702011-09-12 16:11:24 +000011438 if (D.getDeclSpec().isModulePrivateSpecified())
11439 NewFD->setModulePrivate();
11440
Douglas Gregor1efa4372009-03-11 18:59:21 +000011441 if (NewFD->isInvalidDecl() && PrevDecl) {
11442 // Don't introduce NewFD into scope; there's already something
11443 // with the same name in the same scope.
11444 } else if (II) {
11445 PushOnScopeChains(NewFD, S);
11446 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011447 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011448
11449 return NewFD;
11450}
11451
11452/// \brief Build a new FieldDecl and check its well-formedness.
11453///
11454/// This routine builds a new FieldDecl given the fields name, type,
11455/// record, etc. \p PrevDecl should refer to any previous declaration
11456/// with the same name and in the same scope as the field to be
11457/// created.
11458///
11459/// \returns a new FieldDecl.
11460///
Mike Stump11289f42009-09-09 15:08:12 +000011461/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011462FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011463 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011464 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011465 bool Mutable, Expr *BitWidth,
11466 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011467 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011468 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011469 Declarator *D) {
11470 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011471 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011472 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011473
Douglas Gregor1efa4372009-03-11 18:59:21 +000011474 // If we receive a broken type, recover by assuming 'int' and
11475 // marking this declaration as invalid.
11476 if (T.isNull()) {
11477 InvalidDecl = true;
11478 T = Context.IntTy;
11479 }
11480
Eli Friedmand0e8de22009-12-07 00:22:08 +000011481 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011482 if (!EltTy->isDependentType()) {
11483 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11484 // Fields of incomplete type force their record to be invalid.
11485 Record->setInvalidDecl();
11486 InvalidDecl = true;
11487 } else {
11488 NamedDecl *Def;
11489 EltTy->isIncompleteType(&Def);
11490 if (Def && Def->isInvalidDecl()) {
11491 Record->setInvalidDecl();
11492 InvalidDecl = true;
11493 }
11494 }
John McCall2677e102010-08-16 23:42:35 +000011495 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011496
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011497 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11498 if (BitWidth && getLangOpts().OpenCL) {
11499 Diag(Loc, diag::err_opencl_bitfields);
11500 InvalidDecl = true;
11501 }
11502
Steve Naroff8eeeb132007-05-08 21:09:37 +000011503 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11504 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011505 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011506 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011507 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011508
11509 TypeSourceInfo *FixedTInfo =
11510 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11511 SizeIsNegative,
11512 Oversized);
11513 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011514 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011515 TInfo = FixedTInfo;
11516 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011517 } else {
11518 if (SizeIsNegative)
11519 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011520 else if (Oversized.getBoolValue())
11521 Diag(Loc, diag::err_array_too_large)
11522 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011523 else
11524 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011525 InvalidDecl = true;
11526 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011527 }
Mike Stump11289f42009-09-09 15:08:12 +000011528
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011529 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011530 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11531 diag::err_abstract_type_in_decl,
11532 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011533 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011534
Eli Friedmanc96d4962009-08-15 21:55:26 +000011535 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011536 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011537 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011538 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11539 &ZeroWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011540 if (!BitWidth) {
11541 InvalidDecl = true;
11542 BitWidth = 0;
11543 ZeroWidth = false;
11544 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011545 }
Mike Stump11289f42009-09-09 15:08:12 +000011546
John McCallb1cd7da2010-06-04 08:34:12 +000011547 // Check that 'mutable' is consistent with the type of the declaration.
11548 if (!InvalidDecl && Mutable) {
11549 unsigned DiagID = 0;
11550 if (T->isReferenceType())
11551 DiagID = diag::err_mutable_reference;
11552 else if (T.isConstQualified())
11553 DiagID = diag::err_mutable_const;
11554
11555 if (DiagID) {
11556 SourceLocation ErrLoc = Loc;
11557 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11558 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11559 Diag(ErrLoc, DiagID);
11560 Mutable = false;
11561 InvalidDecl = true;
11562 }
11563 }
11564
Richard Smithab44d5b2013-12-10 08:25:00 +000011565 // C++11 [class.union]p8 (DR1460):
11566 // At most one variant member of a union may have a
11567 // brace-or-equal-initializer.
11568 if (InitStyle != ICIS_NoInit)
11569 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11570
Abramo Bagnaradff19302011-03-08 08:55:46 +000011571 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011572 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011573 if (InvalidDecl)
11574 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011575
Douglas Gregor1efa4372009-03-11 18:59:21 +000011576 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11577 Diag(Loc, diag::err_duplicate_member) << II;
11578 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11579 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011580 }
11581
David Blaikiebbafb8a2012-03-11 07:00:24 +000011582 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011583 if (Record->isUnion()) {
11584 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11585 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11586 if (RDecl->getDefinition()) {
11587 // C++ [class.union]p1: An object of a class with a non-trivial
11588 // constructor, a non-trivial copy constructor, a non-trivial
11589 // destructor, or a non-trivial copy assignment operator
11590 // cannot be a member of a union, nor can an array of such
11591 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011592 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011593 NewFD->setInvalidDecl();
11594 }
11595 }
11596
11597 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011598 // the program is ill-formed, except when compiling with MSVC extensions
11599 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011600 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011601 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11602 diag::ext_union_member_of_reference_type :
11603 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011604 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011605 if (!getLangOpts().MicrosoftExt)
11606 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011607 }
11608 }
11609 }
11610
Douglas Gregor1efa4372009-03-11 18:59:21 +000011611 // FIXME: We need to pass in the attributes given an AST
11612 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011613 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011614 // FIXME: The current scope is almost... but not entirely... correct here.
11615 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011616
Richard Smith848e1f12013-02-01 08:12:08 +000011617 if (NewFD->hasAttrs())
11618 CheckAlignasUnderalignment(NewFD);
11619 }
11620
John McCall31168b02011-06-15 23:02:42 +000011621 // In auto-retain/release, infer strong retension for fields of
11622 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011623 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011624 NewFD->setInvalidDecl();
11625
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011626 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011627 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011628
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011629 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011630 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011631}
11632
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011633bool Sema::CheckNontrivialField(FieldDecl *FD) {
11634 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011635 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011636
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011637 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11638 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011639
11640 QualType EltTy = Context.getBaseElementType(FD->getType());
11641 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011642 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011643 if (RDecl->getDefinition()) {
11644 // We check for copy constructors before constructors
11645 // because otherwise we'll never get complaints about
11646 // copy constructors.
11647
11648 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011649 // We're required to check for any non-trivial constructors. Since the
11650 // implicit default constructor is suppressed if there are any
11651 // user-declared constructors, we just need to check that there is a
11652 // trivial default constructor and a trivial copy constructor. (We don't
11653 // worry about move constructors here, since this is a C++98 check.)
11654 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011655 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011656 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011657 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011658 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011659 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011660 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011661 member = CXXDestructor;
11662
11663 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011664 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011665 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011666 // Objective-C++ ARC: it is an error to have a non-trivial field of
11667 // a union. However, system headers in Objective-C programs
11668 // occasionally have Objective-C lifetime objects within unions,
11669 // and rather than cause the program to fail, we make those
11670 // members unavailable.
11671 SourceLocation Loc = FD->getLocation();
11672 if (getSourceManager().isInSystemHeader(Loc)) {
11673 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011674 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11675 "this system field has retaining ownership",
11676 Loc));
John McCall31168b02011-06-15 23:02:42 +000011677 return false;
11678 }
11679 }
Richard Smithf720df02011-10-19 20:41:51 +000011680
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011681 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011682 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11683 diag::err_illegal_union_or_anon_struct_member)
11684 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011685 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011686 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011687 }
11688 }
11689 }
Richard Smith92f241f2012-12-08 02:53:02 +000011690
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011691 return false;
11692}
11693
Mike Stump11289f42009-09-09 15:08:12 +000011694/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011695/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011696static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011697TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011698 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011699 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011700 case tok::objc_private: return ObjCIvarDecl::Private;
11701 case tok::objc_public: return ObjCIvarDecl::Public;
11702 case tok::objc_protected: return ObjCIvarDecl::Protected;
11703 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011704 }
11705}
11706
Mike Stump11289f42009-09-09 15:08:12 +000011707/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011708/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011709Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011710 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011711 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011712 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011713
Fariborz Jahaniande615832008-04-10 23:32:45 +000011714 IdentifierInfo *II = D.getIdentifier();
11715 Expr *BitWidth = (Expr*)BitfieldWidth;
11716 SourceLocation Loc = DeclStart;
11717 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011718
Fariborz Jahaniande615832008-04-10 23:32:45 +000011719 // FIXME: Unnamed fields can be handled in various different ways, for
11720 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011721
John McCall8cb7bdf2010-06-04 23:28:52 +000011722 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11723 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011724
Fariborz Jahaniande615832008-04-10 23:32:45 +000011725 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011726 // 6.7.2.1p3, 6.7.2.1p4
Warren Hunt8f8bad72013-10-11 20:19:00 +000011727 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
Richard Smithf4c51d92012-02-04 09:53:13 +000011728 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011729 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011730 } else {
11731 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011732
Fariborz Jahaniande615832008-04-10 23:32:45 +000011733 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011734
Fariborz Jahaniande615832008-04-10 23:32:45 +000011735 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011736 if (T->isReferenceType()) {
11737 Diag(Loc, diag::err_ivar_reference_type);
11738 D.setInvalidType();
11739 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011740 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11741 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011742 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011743 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011744 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011745 }
Mike Stump11289f42009-09-09 15:08:12 +000011746
Ted Kremenek73295fa2008-07-23 18:04:17 +000011747 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011748 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011749 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11750 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011751 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011752 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011753 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11754 return 0;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011755 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011756 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011757 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011758 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011759 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000011760 EnclosingContext = IMPDecl->getClassInterface();
11761 assert(EnclosingContext && "Implementation has no class interface!");
11762 }
11763 else
11764 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011765 } else {
11766 if (ObjCCategoryDecl *CDecl =
11767 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011768 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011769 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +000011770 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011771 }
11772 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000011773 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000011774 }
Mike Stump11289f42009-09-09 15:08:12 +000011775
Ted Kremenek73295fa2008-07-23 18:04:17 +000011776 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011777 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11778 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000011779 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000011780
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011781 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011782 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000011783 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000011784 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011785 && !isa<TagDecl>(PrevDecl)) {
11786 Diag(Loc, diag::err_duplicate_member) << II;
11787 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11788 NewID->setInvalidDecl();
11789 }
11790 }
11791
Ted Kremenek73295fa2008-07-23 18:04:17 +000011792 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000011793 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000011794
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011795 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000011796 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000011797
John McCall31168b02011-06-15 23:02:42 +000011798 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011799 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000011800 NewID->setInvalidDecl();
11801
Douglas Gregor3baa6702011-09-12 16:11:24 +000011802 if (D.getDeclSpec().isModulePrivateSpecified())
11803 NewID->setModulePrivate();
11804
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011805 if (II) {
11806 // FIXME: When interfaces are DeclContexts, we'll need to add
11807 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000011808 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011809 IdResolver.AddDecl(NewID);
11810 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011811
John McCall5fb5df92012-06-20 06:18:46 +000011812 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011813 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000011814 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000011815
John McCall48871652010-08-21 09:40:31 +000011816 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000011817}
11818
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011819/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000011820/// class and class extensions. For every class \@interface and class
11821/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011822/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011823void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011824 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000011825 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011826 return;
11827
11828 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11829 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11830
Richard Smithcaf33902011-10-10 18:28:20 +000011831 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011832 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011833 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011834 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011835 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011836 if (!CD->IsClassExtension())
11837 return;
11838 }
11839 // No need to add this to end of @implementation.
11840 else
11841 return;
11842 }
11843 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000011844 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11845 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011846
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011847 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011848 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011849 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000011850 Context.getTrivialTypeSourceInfo(Context.CharTy,
11851 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000011852 ObjCIvarDecl::Private, BW,
11853 true);
11854 AllIvarDecls.push_back(Ivar);
11855}
11856
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011857void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11858 ArrayRef<Decl *> Fields, SourceLocation LBrac,
11859 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000011860 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000011861
Eric Christopher7457aaf2012-07-19 22:22:51 +000011862 // If this is an Objective-C @implementation or category and we have
11863 // new fields here we should reset the layout of the interface since
11864 // it will now change.
11865 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11866 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11867 switch (DC->getKind()) {
11868 default: break;
11869 case Decl::ObjCCategory:
11870 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11871 break;
11872 case Decl::ObjCImplementation:
11873 Context.
11874 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11875 break;
11876 }
11877 }
11878
Eli Friedmana7679412012-02-07 05:00:47 +000011879 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11880
11881 // Start counting up the number of named members; make sure to include
11882 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000011883 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000011884 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000011885 for (const auto *I : Record->decls()) {
11886 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000011887 if (IFD->getDeclName())
11888 ++NumNamedMembers;
11889 }
11890 }
11891
11892 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011893 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000011894
John McCall31168b02011-06-15 23:02:42 +000011895 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000011896 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000011897 i != end; ++i) {
11898 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000011899
Chris Lattner720a0542007-01-25 00:44:24 +000011900 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000011901 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000011902
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011903 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000011904 // Remember all fields written by the user.
11905 RecFields.push_back(FD);
11906 }
Mike Stump11289f42009-09-09 15:08:12 +000011907
Chris Lattner73bf7b42009-03-05 22:45:59 +000011908 // If the field is already invalid for some reason, don't emit more
11909 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011910 if (FD->isInvalidDecl()) {
11911 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000011912 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000011913 }
Mike Stump11289f42009-09-09 15:08:12 +000011914
Douglas Gregorac1fb652009-03-24 19:52:54 +000011915 // C99 6.7.2.1p2:
11916 // A structure or union shall not contain a member with
11917 // incomplete or function type (hence, a structure shall not
11918 // contain an instance of itself, but may contain a pointer to
11919 // an instance of itself), except that the last member of a
11920 // structure with more than one named member may have incomplete
11921 // array type; such a structure (and any union containing,
11922 // possibly recursively, a member that is such a structure)
11923 // shall not be a member of a structure or an element of an
11924 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000011925 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011926 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000011927 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011928 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000011929 FD->setInvalidDecl();
11930 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000011931 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000011932 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000011933 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000011934 ((getLangOpts().MicrosoftExt ||
11935 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000011936 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000011937 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000011938 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000011939 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000011940 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000011941 unsigned DiagID = 0;
11942 if (Record->isUnion())
11943 DiagID = getLangOpts().MicrosoftExt
11944 ? diag::ext_flexible_array_union_ms
11945 : getLangOpts().CPlusPlus
11946 ? diag::ext_flexible_array_union_gnu
11947 : diag::err_flexible_array_union;
11948 else if (Fields.size() == 1)
11949 DiagID = getLangOpts().MicrosoftExt
11950 ? diag::ext_flexible_array_empty_aggregate_ms
11951 : getLangOpts().CPlusPlus
11952 ? diag::ext_flexible_array_empty_aggregate_gnu
11953 : NumNamedMembers < 1
11954 ? diag::err_flexible_array_empty_aggregate
11955 : 0;
11956
11957 if (DiagID)
11958 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11959 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000011960 // While the layout of types that contain virtual bases is not specified
11961 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11962 // virtual bases after the derived members. This would make a flexible
11963 // array member declared at the end of an object not adjacent to the end
11964 // of the type.
11965 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11966 if (RD->getNumVBases() != 0)
11967 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11968 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000011969 if (!getLangOpts().C99)
11970 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11971 << FD->getDeclName() << Record->getTagKind();
11972
Richard Smith6fa28ff2014-01-11 00:53:35 +000011973 // If the element type has a non-trivial destructor, we would not
11974 // implicitly destroy the elements, so disallow it for now.
11975 //
11976 // FIXME: GCC allows this. We should probably either implicitly delete
11977 // the destructor of the containing class, or just allow this.
11978 QualType BaseElem = Context.getBaseElementType(FD->getType());
11979 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11980 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000011981 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011982 FD->setInvalidDecl();
11983 EnclosingDecl->setInvalidDecl();
11984 continue;
11985 }
Chris Lattner720a0542007-01-25 00:44:24 +000011986 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000011987 if (Record)
11988 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000011989 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000011990 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000011991 diag::err_field_incomplete)) {
11992 // Incomplete type
11993 FD->setInvalidDecl();
11994 EnclosingDecl->setInvalidDecl();
11995 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011996 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000011997 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11998 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011999 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012000 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012001 } else {
12002 // If this is a struct/class and this is not the last element, reject
12003 // it. Note that GCC supports variable sized arrays in the middle of
12004 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012005 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012006 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012007 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012008 else {
12009 // We support flexible arrays at the end of structs in
12010 // other structs as an extension.
12011 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12012 << FD->getDeclName();
12013 if (Record)
12014 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012015 }
Chris Lattner720a0542007-01-25 00:44:24 +000012016 }
12017 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012018 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12019 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12020 diag::err_abstract_type_in_decl,
12021 AbstractIvarType)) {
12022 // Ivars can not have abstract class types
12023 FD->setInvalidDecl();
12024 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012025 if (Record && FDTTy->getDecl()->hasObjectMember())
12026 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012027 if (Record && FDTTy->getDecl()->hasVolatileMember())
12028 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012029 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012030 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012031 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12032 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12033 QualType T = Context.getObjCObjectPointerType(FD->getType());
12034 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012035 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12036 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12037 // It's an error in ARC if a field has lifetime.
12038 // We don't want to report this in a system header, though,
12039 // so we just make the field unavailable.
12040 // FIXME: that's really not sufficient; we need to make the type
12041 // itself invalid to, say, initialize or copy.
12042 QualType T = FD->getType();
12043 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12044 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12045 SourceLocation loc = FD->getLocation();
12046 if (getSourceManager().isInSystemHeader(loc)) {
12047 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012048 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12049 "this system field has retaining ownership",
12050 loc));
John McCall31168b02011-06-15 23:02:42 +000012051 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012052 } else {
12053 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012054 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012055 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012056 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012057 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012058 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012059 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012060 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012061 if (FD->getType()->isObjCObjectPointerType() ||
12062 FD->getType().isObjCGCStrong())
12063 Record->setHasObjectMember(true);
12064 else if (Context.getAsArrayType(FD->getType())) {
12065 QualType BaseType = Context.getBaseElementType(FD->getType());
12066 if (BaseType->isRecordType() &&
12067 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012068 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012069 else if (BaseType->isObjCObjectPointerType() ||
12070 BaseType.isObjCGCStrong())
12071 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012072 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012073 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012074 if (Record && FD->getType().isVolatileQualified())
12075 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012076 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012077 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012078 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012079 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012080
Chris Lattner82625602007-01-24 02:26:21 +000012081 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012082 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012083 bool Completed = false;
12084 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12085 if (!CXXRecord->isInvalidDecl()) {
12086 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012087 for (CXXRecordDecl::conversion_iterator
12088 I = CXXRecord->conversion_begin(),
12089 E = CXXRecord->conversion_end(); I != E; ++I)
12090 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012091
12092 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012093 if (CXXRecord->hasUserDeclaredDestructor()) {
12094 // Adjust user-defined destructor exception spec.
12095 if (getLangOpts().CPlusPlus11)
12096 AdjustDestructorExceptionSpec(CXXRecord,
12097 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012098 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012099
Douglas Gregor8fb95122010-09-29 00:15:42 +000012100 // Add any implicitly-declared members to this class.
12101 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12102
12103 // If we have virtual base classes, we may end up finding multiple
12104 // final overriders for a given virtual function. Check for this
12105 // problem now.
12106 if (CXXRecord->getNumVBases()) {
12107 CXXFinalOverriderMap FinalOverriders;
12108 CXXRecord->getFinalOverriders(FinalOverriders);
12109
12110 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12111 MEnd = FinalOverriders.end();
12112 M != MEnd; ++M) {
12113 for (OverridingMethods::iterator SO = M->second.begin(),
12114 SOEnd = M->second.end();
12115 SO != SOEnd; ++SO) {
12116 assert(SO->second.size() > 0 &&
12117 "Virtual function without overridding functions?");
12118 if (SO->second.size() == 1)
12119 continue;
12120
12121 // C++ [class.virtual]p2:
12122 // In a derived class, if a virtual member function of a base
12123 // class subobject has more than one final overrider the
12124 // program is ill-formed.
12125 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012126 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012127 Diag(M->first->getLocation(),
12128 diag::note_overridden_virtual_function);
12129 for (OverridingMethods::overriding_iterator
12130 OM = SO->second.begin(),
12131 OMEnd = SO->second.end();
12132 OM != OMEnd; ++OM)
12133 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012134 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012135
12136 Record->setInvalidDecl();
12137 }
12138 }
12139 CXXRecord->completeDefinition(&FinalOverriders);
12140 Completed = true;
12141 }
12142 }
12143 }
12144 }
12145
12146 if (!Completed)
12147 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012148
David Majnemer2c4e00a2014-01-29 22:07:36 +000012149 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012150 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012151
David Majnemer98c9ee22014-02-07 00:43:07 +000012152 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012153 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012154 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012155 IA->getSemanticSpelling());
12156 }
12157
Serge Pavlov3cb80222013-11-14 02:13:03 +000012158 // Check if the structure/union declaration is a type that can have zero
12159 // size in C. For C this is a language extension, for C++ it may cause
12160 // compatibility problems.
12161 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012162 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012163 CheckForZeroSize = true;
12164 } else {
12165 // For C++ filter out types that cannot be referenced in C code.
12166 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12167 CheckForZeroSize =
12168 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12169 !CXXRecord->isDependentType() &&
12170 CXXRecord->isCLike();
12171 }
12172 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012173 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012174 bool IsEmpty = true;
12175 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012176 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012177 E = Record->field_end();
12178 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12179 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012180 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012181 if (I->getBitWidthValue(Context) > 0)
12182 ZeroSize = false;
12183 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012184 ++NonBitFields;
12185 QualType FieldType = I->getType();
12186 if (FieldType->isIncompleteType() ||
12187 !Context.getTypeSizeInChars(FieldType).isZero())
12188 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012189 }
12190 }
12191
Serge Pavlov3cb80222013-11-14 02:13:03 +000012192 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12193 // allowed in C++, but warn if its declaration is inside
12194 // extern "C" block.
12195 if (ZeroSize) {
12196 Diag(RecLoc, getLangOpts().CPlusPlus ?
12197 diag::warn_zero_size_struct_union_in_extern_c :
12198 diag::warn_zero_size_struct_union_compat)
12199 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12200 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012201
Serge Pavlov3cb80222013-11-14 02:13:03 +000012202 // Structs without named members are extension in C (C99 6.7.2.1p7),
12203 // but are accepted by GCC.
12204 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12205 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12206 diag::ext_no_named_members_in_struct_union)
12207 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012208 }
12209 }
Chris Lattner622c1932008-02-06 00:51:33 +000012210 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012211 ObjCIvarDecl **ClsFields =
12212 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012213 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012214 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012215 // Add ivar's to class's DeclContext.
12216 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12217 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012218 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012219 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012220 // Must enforce the rule that ivars in the base classes may not be
12221 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012222 if (ID->getSuperClass())
12223 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012224 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012225 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012226 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012227 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12228 // Ivar declared in @implementation never belongs to the implementation.
12229 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012230 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012231 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012232 IMPDecl->setIvarLBraceLoc(LBrac);
12233 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012234 } else if (ObjCCategoryDecl *CDecl =
12235 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012236 // case of ivars in class extension; all other cases have been
12237 // reported as errors elsewhere.
12238 // FIXME. Class extension does not have a LocEnd field.
12239 // CDecl->setLocEnd(RBrac);
12240 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012241 // Diagnose redeclaration of private ivars.
12242 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012243 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012244 if (IDecl) {
12245 if (const ObjCIvarDecl *ClsIvar =
12246 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12247 Diag(ClsFields[i]->getLocation(),
12248 diag::err_duplicate_ivar_declaration);
12249 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12250 continue;
12251 }
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012252 for (ObjCInterfaceDecl::known_extensions_iterator
12253 Ext = IDecl->known_extensions_begin(),
12254 ExtEnd = IDecl->known_extensions_end();
12255 Ext != ExtEnd; ++Ext) {
12256 if (const ObjCIvarDecl *ClsExtIvar
12257 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012258 Diag(ClsFields[i]->getLocation(),
12259 diag::err_duplicate_ivar_declaration);
12260 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12261 continue;
12262 }
12263 }
12264 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012265 ClsFields[i]->setLexicalDeclContext(CDecl);
12266 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012267 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012268 CDecl->setIvarLBraceLoc(LBrac);
12269 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012270 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012271 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012272
12273 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012274 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012275}
12276
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012277/// \brief Determine whether the given integral value is representable within
12278/// the given type T.
12279static bool isRepresentableIntegerValue(ASTContext &Context,
12280 llvm::APSInt &Value,
12281 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012282 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012283 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012284
Douglas Gregor0bf31402010-10-08 23:50:27 +000012285 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012286 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012287 --BitWidth;
12288 return Value.getActiveBits() <= BitWidth;
12289 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012290 return Value.getMinSignedBits() <= BitWidth;
12291}
12292
12293// \brief Given an integral type, return the next larger integral type
12294// (or a NULL type of no such type exists).
12295static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12296 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12297 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012298 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012299 const unsigned NumTypes = 4;
12300 QualType SignedIntegralTypes[NumTypes] = {
12301 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12302 };
12303 QualType UnsignedIntegralTypes[NumTypes] = {
12304 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12305 Context.UnsignedLongLongTy
12306 };
12307
12308 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012309 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12310 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012311 for (unsigned I = 0; I != NumTypes; ++I)
12312 if (Context.getTypeSize(Types[I]) > BitWidth)
12313 return Types[I];
12314
12315 return QualType();
12316}
12317
Douglas Gregor954f6b272009-03-17 19:05:46 +000012318EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12319 EnumConstantDecl *LastEnumConst,
12320 SourceLocation IdLoc,
12321 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012322 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012323 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012324 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012325 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012326
12327 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12328 Val = 0;
12329
Eli Friedman7c6515a2011-12-06 00:10:34 +000012330 if (Val)
12331 Val = DefaultLvalueConversion(Val).take();
12332
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012333 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012334 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012335 EltTy = Context.DependentTy;
12336 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012337 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012338 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012339 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012340 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12341 // constant-expression in the enumerator-definition shall be a converted
12342 // constant expression of the underlying type.
12343 EltTy = Enum->getIntegerType();
12344 ExprResult Converted =
12345 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12346 CCEK_Enumerator);
12347 if (Converted.isInvalid())
12348 Val = 0;
12349 else
12350 Val = Converted.take();
12351 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012352 !(Val = VerifyIntegerConstantExpression(Val,
12353 &EnumVal).take())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012354 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012355 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012356 if (Enum->isFixed()) {
12357 EltTy = Enum->getIntegerType();
12358
Richard Smithf8379a02012-01-18 23:55:52 +000012359 // In Obj-C and Microsoft mode, require the enumeration value to be
12360 // representable in the underlying type of the enumeration. In C++11,
12361 // we perform a non-narrowing conversion as part of converted constant
12362 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012363 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012364 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012365 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +000012366 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Richard Smithf8379a02012-01-18 23:55:52 +000012367 } else
12368 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012369 } else
John Wiegley01296292011-04-08 18:41:53 +000012370 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012371 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012372 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012373 // If the underlying type is not fixed, the type of each enumerator
12374 // is the type of its initializing value:
12375 // - If an initializer is specified for an enumerator, the
12376 // initializing value has the same type as the expression.
12377 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012378 } else {
12379 // C99 6.7.2.2p2:
12380 // The expression that defines the value of an enumeration constant
12381 // shall be an integer constant expression that has a value
12382 // representable as an int.
12383
12384 // Complain if the value is not representable in an int.
12385 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12386 Diag(IdLoc, diag::ext_enum_value_not_int)
12387 << EnumVal.toString(10) << Val->getSourceRange()
12388 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12389 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12390 // Force the type of the expression to 'int'.
12391 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12392 }
12393 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012394 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012395 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012396 }
12397 }
Mike Stump11289f42009-09-09 15:08:12 +000012398
Douglas Gregor954f6b272009-03-17 19:05:46 +000012399 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012400 if (Enum->isDependentType())
12401 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012402 else if (!LastEnumConst) {
12403 // C++0x [dcl.enum]p5:
12404 // If the underlying type is not fixed, the type of each enumerator
12405 // is the type of its initializing value:
12406 // - If no initializer is specified for the first enumerator, the
12407 // initializing value has an unspecified integral type.
12408 //
12409 // GCC uses 'int' for its unspecified integral type, as does
12410 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012411 if (Enum->isFixed()) {
12412 EltTy = Enum->getIntegerType();
12413 }
12414 else {
12415 EltTy = Context.IntTy;
12416 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012417 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012418 // Assign the last value + 1.
12419 EnumVal = LastEnumConst->getInitVal();
12420 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012421 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012422
12423 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012424 if (EnumVal < LastEnumConst->getInitVal()) {
12425 // C++0x [dcl.enum]p5:
12426 // If the underlying type is not fixed, the type of each enumerator
12427 // is the type of its initializing value:
12428 //
12429 // - Otherwise the type of the initializing value is the same as
12430 // the type of the initializing value of the preceding enumerator
12431 // unless the incremented value is not representable in that type,
12432 // in which case the type is an unspecified integral type
12433 // sufficient to contain the incremented value. If no such type
12434 // exists, the program is ill-formed.
12435 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012436 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012437 // There is no integral type larger enough to represent this
12438 // value. Complain, then allow the value to wrap around.
12439 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012440 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012441 ++EnumVal;
12442 if (Enum->isFixed())
12443 // When the underlying type is fixed, this is ill-formed.
12444 Diag(IdLoc, diag::err_enumerator_wrapped)
12445 << EnumVal.toString(10)
12446 << EltTy;
12447 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012448 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012449 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012450 } else {
12451 EltTy = T;
12452 }
12453
12454 // Retrieve the last enumerator's value, extent that type to the
12455 // type that is supposed to be large enough to represent the incremented
12456 // value, then increment.
12457 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012458 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012459 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012460 ++EnumVal;
12461
12462 // If we're not in C++, diagnose the overflow of enumerator values,
12463 // which in C99 means that the enumerator value is not representable in
12464 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12465 // permits enumerator values that are representable in some larger
12466 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012467 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012468 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012469 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012470 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12471 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12472 Diag(IdLoc, diag::ext_enum_value_not_int)
12473 << EnumVal.toString(10) << 1;
12474 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012475 }
12476 }
Mike Stump11289f42009-09-09 15:08:12 +000012477
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012478 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012479 // Make the enumerator value match the signedness and size of the
12480 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012481 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012482 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012483 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012484
Douglas Gregor954f6b272009-03-17 19:05:46 +000012485 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012486 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012487}
12488
12489
John McCall811a0f52010-10-22 23:36:17 +000012490Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12491 SourceLocation IdLoc, IdentifierInfo *Id,
12492 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012493 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012494 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012495 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012496 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012497
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012498 // The scope passed in may not be a decl scope. Zip up the scope tree until
12499 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012500 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012501
Chris Lattner8116d1b2007-01-25 22:38:29 +000012502 // Verify that there isn't already something declared with this name in this
12503 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012504 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012505 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012506 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012507 // Maybe we will complain about the shadowed template parameter.
12508 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12509 // Just pretend that we didn't see the previous declaration.
12510 PrevDecl = 0;
12511 }
12512
12513 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012514 // When in C++, we may get a TagDecl with the same name; in this case the
12515 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012516 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012517 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012518 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012519 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012520 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012521 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012522 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012523 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +000012524 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012525 }
12526 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012527
Aaron Ballman24a10472012-07-19 03:12:23 +000012528 // C++ [class.mem]p15:
12529 // If T is the name of a class, then each of the following shall have a name
12530 // different from T:
12531 // - every enumerator of every member of class T that is an unscoped
12532 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012533 if (CXXRecordDecl *Record
12534 = dyn_cast<CXXRecordDecl>(
12535 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012536 if (!TheEnumDecl->isScoped() &&
12537 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012538 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12539
John McCall811a0f52010-10-22 23:36:17 +000012540 EnumConstantDecl *New =
12541 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012542
John McCall553c0792010-01-23 00:46:32 +000012543 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012544 // Process attributes.
12545 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12546
12547 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012548 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012549 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012550 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012551
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012552 ActOnDocumentableDecl(New);
12553
John McCall48871652010-08-21 09:40:31 +000012554 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012555}
12556
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012557// Returns true when the enum initial expression does not trigger the
12558// duplicate enum warning. A few common cases are exempted as follows:
12559// Element2 = Element1
12560// Element2 = Element1 + 1
12561// Element2 = Element1 - 1
12562// Where Element2 and Element1 are from the same enum.
12563static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12564 Expr *InitExpr = ECD->getInitExpr();
12565 if (!InitExpr)
12566 return true;
12567 InitExpr = InitExpr->IgnoreImpCasts();
12568
12569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12570 if (!BO->isAdditiveOp())
12571 return true;
12572 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12573 if (!IL)
12574 return true;
12575 if (IL->getValue() != 1)
12576 return true;
12577
12578 InitExpr = BO->getLHS();
12579 }
12580
12581 // This checks if the elements are from the same enum.
12582 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12583 if (!DRE)
12584 return true;
12585
12586 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12587 if (!EnumConstant)
12588 return true;
12589
12590 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12591 Enum)
12592 return true;
12593
12594 return false;
12595}
12596
12597struct DupKey {
12598 int64_t val;
12599 bool isTombstoneOrEmptyKey;
12600 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12601 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12602};
12603
12604static DupKey GetDupKey(const llvm::APSInt& Val) {
12605 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12606 false);
12607}
12608
12609struct DenseMapInfoDupKey {
12610 static DupKey getEmptyKey() { return DupKey(0, true); }
12611 static DupKey getTombstoneKey() { return DupKey(1, true); }
12612 static unsigned getHashValue(const DupKey Key) {
12613 return (unsigned)(Key.val * 37);
12614 }
12615 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12616 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12617 LHS.val == RHS.val;
12618 }
12619};
12620
12621// Emits a warning when an element is implicitly set a value that
12622// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012623static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12624 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012625 QualType EnumType) {
12626 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12627 Enum->getLocation()) ==
12628 DiagnosticsEngine::Ignored)
12629 return;
12630 // Avoid anonymous enums
12631 if (!Enum->getIdentifier())
12632 return;
12633
12634 // Only check for small enums.
12635 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12636 return;
12637
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012638 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12639 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012640
12641 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12642 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12643 ValueToVectorMap;
12644
12645 DuplicatesVector DupVector;
12646 ValueToVectorMap EnumMap;
12647
12648 // Populate the EnumMap with all values represented by enum constants without
12649 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012650 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012651 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012652
12653 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12654 // this constant. Skip this enum since it may be ill-formed.
12655 if (!ECD) {
12656 return;
12657 }
12658
12659 if (ECD->getInitExpr())
12660 continue;
12661
12662 DupKey Key = GetDupKey(ECD->getInitVal());
12663 DeclOrVector &Entry = EnumMap[Key];
12664
12665 // First time encountering this value.
12666 if (Entry.isNull())
12667 Entry = ECD;
12668 }
12669
12670 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012671 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012672 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12673 if (!ValidDuplicateEnum(ECD, Enum))
12674 continue;
12675
12676 DupKey Key = GetDupKey(ECD->getInitVal());
12677
12678 DeclOrVector& Entry = EnumMap[Key];
12679 if (Entry.isNull())
12680 continue;
12681
12682 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12683 // Ensure constants are different.
12684 if (D == ECD)
12685 continue;
12686
12687 // Create new vector and push values onto it.
12688 ECDVector *Vec = new ECDVector();
12689 Vec->push_back(D);
12690 Vec->push_back(ECD);
12691
12692 // Update entry to point to the duplicates vector.
12693 Entry = Vec;
12694
12695 // Store the vector somewhere we can consult later for quick emission of
12696 // diagnostics.
12697 DupVector.push_back(Vec);
12698 continue;
12699 }
12700
12701 ECDVector *Vec = Entry.get<ECDVector*>();
12702 // Make sure constants are not added more than once.
12703 if (*Vec->begin() == ECD)
12704 continue;
12705
12706 Vec->push_back(ECD);
12707 }
12708
12709 // Emit diagnostics.
12710 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12711 DupVectorEnd = DupVector.end();
12712 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12713 ECDVector *Vec = *DupVectorIter;
12714 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12715
12716 // Emit warning for one enum constant.
12717 ECDVector::iterator I = Vec->begin();
12718 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12719 << (*I)->getName() << (*I)->getInitVal().toString(10)
12720 << (*I)->getSourceRange();
12721 ++I;
12722
12723 // Emit one note for each of the remaining enum constants with
12724 // the same value.
12725 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12726 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12727 << (*I)->getName() << (*I)->getInitVal().toString(10)
12728 << (*I)->getSourceRange();
12729 delete Vec;
12730 }
12731}
12732
Mike Stump6814d1c2009-05-16 07:06:02 +000012733void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012734 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012735 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012736 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012737 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012738 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012739
12740 if (Attr)
12741 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012742
Eli Friedmand0e60972009-12-11 01:34:50 +000012743 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012744 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012745 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012746 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012747 if (!ECD) continue;
12748
12749 ECD->setType(EnumType);
12750 }
12751
John McCall9aa35be2010-05-06 08:49:23 +000012752 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012753 return;
12754 }
12755
Chris Lattner67933c02007-08-28 05:10:31 +000012756 // TODO: If the result value doesn't fit in an int, it must be a long or long
12757 // long value. ISO C does not support this, but GCC does as an extension,
12758 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012759 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12760 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12761 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012762
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012763 // Verify that all the values are okay, compute the size of the values, and
12764 // reverse the list.
12765 unsigned NumNegativeBits = 0;
12766 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000012767
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012768 // Keep track of whether all elements have type int.
12769 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000012770
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012771 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000012772 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012773 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012774 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000012775
Chris Lattnerbf478cb2007-08-28 05:27:00 +000012776 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000012777
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012778 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000012779 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000012780 NumPositiveBits = std::max(NumPositiveBits,
12781 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012782 else
Chris Lattner49f980c2008-01-14 21:47:29 +000012783 NumNegativeBits = std::max(NumNegativeBits,
12784 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000012785
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012786 // Keep track of whether every enum element has type int (very commmon).
12787 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000012788 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012789 }
Mike Stump11289f42009-09-09 15:08:12 +000012790
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012791 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012792 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012793 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012794
John McCall56774992009-12-09 09:09:27 +000012795 // C++0x N3000 [conv.prom]p3:
12796 // An rvalue of an unscoped enumeration type whose underlying
12797 // type is not fixed can be converted to an rvalue of the first
12798 // of the following types that can represent all the values of
12799 // the enumeration: int, unsigned int, long int, unsigned long
12800 // int, long long int, or unsigned long long int.
12801 // C99 6.4.4.3p2:
12802 // An identifier declared as an enumeration constant has type int.
12803 // The C99 rule is modified by a gcc extension
12804 QualType BestPromotionType;
12805
Aaron Ballman9ead1242013-12-19 02:39:40 +000012806 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000012807 // -fshort-enums is the equivalent to specifying the packed attribute on all
12808 // enum definitions.
12809 if (LangOpts.ShortEnums)
12810 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012811
Douglas Gregor0bf31402010-10-08 23:50:27 +000012812 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000012813 BestType = Enum->getIntegerType();
12814 if (BestType->isPromotableIntegerType())
12815 BestPromotionType = Context.getPromotedIntegerType(BestType);
12816 else
12817 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000012818 // We don't need to set BestWidth, because BestType is going to be the type
12819 // of the enumerators, but we do anyway because otherwise some compilers
12820 // warn that it might be used uninitialized.
12821 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000012822 }
12823 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000012824 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012825 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012826 // If it's packed, check also if it fits a char or a short.
12827 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012828 BestType = Context.SignedCharTy;
12829 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000012830 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012831 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012832 BestType = Context.ShortTy;
12833 BestWidth = ShortWidth;
12834 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012835 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012836 BestWidth = IntWidth;
12837 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012838 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012839
John McCall56774992009-12-09 09:09:27 +000012840 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012841 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000012842 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012843 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012844
Chris Lattner3a370bf2007-08-29 17:31:48 +000012845 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000012846 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012847 BestType = Context.LongLongTy;
12848 }
12849 }
John McCall56774992009-12-09 09:09:27 +000012850 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012851 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000012852 // If there is no negative value, figure out the smallest type that fits
12853 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012854 // If it's packed, check also if it fits a char or a short.
12855 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000012856 BestType = Context.UnsignedCharTy;
12857 BestPromotionType = Context.IntTy;
12858 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012859 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000012860 BestType = Context.UnsignedShortTy;
12861 BestPromotionType = Context.IntTy;
12862 BestWidth = ShortWidth;
12863 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012864 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012865 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000012866 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012867 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012868 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000012869 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000012870 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012871 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012872 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012873 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012874 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000012875 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012876 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012877 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012878 "How could an initializer get larger than ULL?");
12879 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000012880 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000012881 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000012882 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012883 }
12884 }
Mike Stump11289f42009-09-09 15:08:12 +000012885
Chris Lattner3a370bf2007-08-29 17:31:48 +000012886 // Loop over all of the enumerator constants, changing their types to match
12887 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012888 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000012889 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012890 if (!ECD) continue; // Already issued a diagnostic.
12891
12892 // Standard C says the enumerators have int type, but we allow, as an
12893 // extension, the enumerators to be larger than int size. If each
12894 // enumerator value fits in an int, type it as an int, otherwise type it the
12895 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
12896 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000012897
12898 // Determine whether the value fits into an int.
12899 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012900
12901 // If it fits into an integer type, force it. Otherwise force it to match
12902 // the enum decl type.
12903 QualType NewTy;
12904 unsigned NewWidth;
12905 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000012906 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000012907 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012908 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000012909 NewTy = Context.IntTy;
12910 NewWidth = IntWidth;
12911 NewSign = true;
12912 } else if (ECD->getType() == BestType) {
12913 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000012914 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012915 // C++ [dcl.enum]p4: Following the closing brace of an
12916 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012917 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012918 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012919 continue;
12920 } else {
12921 NewTy = BestType;
12922 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012923 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000012924 }
12925
12926 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000012927 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012928 InitVal.setIsSigned(NewSign);
12929 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000012930
Chris Lattner3a370bf2007-08-29 17:31:48 +000012931 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000012932 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000012933 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000012934 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000012935 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000012936 ECD->getInitExpr(),
12937 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +000012938 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000012939 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000012940 // C++ [dcl.enum]p4: Following the closing brace of an
12941 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000012942 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000012943 ECD->setType(EnumType);
12944 else
12945 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000012946 }
Mike Stump11289f42009-09-09 15:08:12 +000012947
John McCall9aa35be2010-05-06 08:49:23 +000012948 Enum->completeDefinition(BestType, BestPromotionType,
12949 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000012950
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012951 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000012952
12953 // Now that the enum type is defined, ensure it's not been underaligned.
12954 if (Enum->hasAttrs())
12955 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000012956}
Chris Lattner1300fb92007-01-23 23:42:53 +000012957
Abramo Bagnara348823a2011-03-03 14:20:18 +000012958Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12959 SourceLocation StartLoc,
12960 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000012961 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000012962
Douglas Gregor278f52e2009-05-30 00:08:05 +000012963 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000012964 AsmString, StartLoc,
12965 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012966 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000012967 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000012968}
Eli Friedman5ed51982009-06-05 02:44:36 +000012969
Richard Smith77944862014-03-02 05:58:18 +000012970static void checkModuleImportContext(Sema &S, Module *M,
12971 SourceLocation ImportLoc,
12972 DeclContext *DC) {
12973 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
12974 switch (LSD->getLanguage()) {
12975 case LinkageSpecDecl::lang_c:
12976 if (!M->IsExternC) {
12977 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
12978 << M->getFullModuleName();
12979 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
12980 return;
12981 }
12982 break;
12983 case LinkageSpecDecl::lang_cxx:
12984 break;
12985 }
12986 DC = LSD->getParent();
12987 }
12988
12989 while (isa<LinkageSpecDecl>(DC))
12990 DC = DC->getParent();
12991 if (!isa<TranslationUnitDecl>(DC)) {
12992 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
12993 << M->getFullModuleName() << DC;
12994 S.Diag(cast<Decl>(DC)->getLocStart(),
12995 diag::note_module_import_not_at_top_level)
12996 << DC;
12997 }
12998}
12999
Douglas Gregor22d09742012-01-03 18:04:46 +000013000DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13001 SourceLocation ImportLoc,
13002 ModuleIdPath Path) {
Douglas Gregorff2be532011-12-01 17:11:21 +000013003 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
Douglas Gregorbcfc7d02011-12-02 23:42:12 +000013004 Module::AllVisible,
13005 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013006 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013007 return true;
Richard Smith77944862014-03-02 05:58:18 +000013008
13009 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13010
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013011 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013012 Module *ModCheck = Mod;
13013 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13014 // If we've run out of module parents, just drop the remaining identifiers.
13015 // We need the length to be consistent.
13016 if (!ModCheck)
13017 break;
13018 ModCheck = ModCheck->Parent;
13019
13020 IdentifierLocs.push_back(Path[I].second);
13021 }
13022
13023 ImportDecl *Import = ImportDecl::Create(Context,
13024 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013025 AtLoc.isValid()? AtLoc : ImportLoc,
13026 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013027 Context.getTranslationUnitDecl()->addDecl(Import);
13028 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013029}
13030
Richard Smithce587f52013-11-15 04:24:58 +000013031void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013032 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13033
Richard Smithce587f52013-11-15 04:24:58 +000013034 // FIXME: Should we synthesize an ImportDecl here?
13035 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13036 /*Complain=*/true);
13037}
13038
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013039void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13040 // Create the implicit import declaration.
13041 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13042 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13043 Loc, Mod, Loc);
13044 TU->addDecl(ImportD);
13045 Consumer.HandleImplicitImportDecl(ImportD);
13046
13047 // Make the module visible.
Douglas Gregorfb912652013-03-20 21:10:35 +000013048 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13049 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013050}
13051
David Chisnall0867d9c2012-02-18 16:12:34 +000013052void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13053 IdentifierInfo* AliasName,
13054 SourceLocation PragmaLoc,
13055 SourceLocation NameLoc,
13056 SourceLocation AliasNameLoc) {
13057 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13058 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013059 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13060 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013061
13062 if (PrevDecl)
13063 PrevDecl->addAttr(Attr);
13064 else
13065 (void)ExtnameUndeclaredIdentifiers.insert(
13066 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13067}
13068
Eli Friedman5ed51982009-06-05 02:44:36 +000013069void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13070 SourceLocation PragmaLoc,
13071 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013072 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013073
Eli Friedman5ed51982009-06-05 02:44:36 +000013074 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013075 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013076 } else {
13077 (void)WeakUndeclaredIdentifiers.insert(
13078 std::pair<IdentifierInfo*,WeakInfo>
13079 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013080 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013081}
13082
13083void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13084 IdentifierInfo* AliasName,
13085 SourceLocation PragmaLoc,
13086 SourceLocation NameLoc,
13087 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013088 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13089 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013090 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013091
Eli Friedman5ed51982009-06-05 02:44:36 +000013092 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013093 if (!PrevDecl->hasAttr<AliasAttr>())
13094 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013095 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013096 } else {
13097 (void)WeakUndeclaredIdentifiers.insert(
13098 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013099 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013100}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013101
13102Decl *Sema::getObjCDeclContext() const {
13103 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13104}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013105
13106AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013107 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013108 // If we are within an Objective-C method, we should consult
13109 // both the availability of the method as well as the
13110 // enclosing class. If the class is (say) deprecated,
13111 // the entire method is considered deprecated from the
13112 // purpose of checking if the current context is deprecated.
13113 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13114 AvailabilityResult R = MD->getAvailability();
13115 if (R != AR_Available)
13116 return R;
13117 D = MD->getClassInterface();
13118 }
13119 // If we are within an Objective-c @implementation, it
13120 // gets the same availability context as the @interface.
13121 else if (const ObjCImplementationDecl *ID =
13122 dyn_cast<ObjCImplementationDecl>(D)) {
13123 D = ID->getClassInterface();
13124 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013125 return D->getAvailability();
13126}