blob: 304fd46cf978b95017687960baeb3da0d7a8e489 [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000028#include "clang/Basic/Builtins.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000030#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000032#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Parse/ParseDiagnostic.h"
37#include "clang/Sema/CXXFieldCollector.h"
38#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/DelayedDiagnostic.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000045#include "clang/Sema/Template.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000046#include "llvm/ADT/SmallString.h"
John McCall0e21fcc2009-12-24 09:58:38 +000047#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000048#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000049#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000050#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000051using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000052using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000053
Richard Smithcd1c0552011-07-01 19:46:12 +000054Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 if (OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58 }
59
John McCall48871652010-08-21 09:40:31 +000060 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000061}
62
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000063namespace {
64
65class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66 public:
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000067 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowClassTemplates(AllowTemplates) {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000071 WantExpressionKeywords = false;
72 WantCXXNamedCasts = false;
73 WantRemainingKeywords = false;
74 }
75
Craig Toppere14c0f82014-03-12 04:55:44 +000076 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000077 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
82 }
83 return !WantClassName && candidate.isKeyword();
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000084 }
85
86 private:
87 bool AllowInvalidDecl;
Kaelyn Uhrain9cb8e9f2012-06-22 23:37:05 +000088 bool WantClassName;
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +000089 bool AllowClassTemplates;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000090};
91
92}
93
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +000094/// \brief Determine whether the token kind starts a simple-type-specifier.
95bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96 switch (Kind) {
97 // FIXME: Take into account the current language when deciding whether a
98 // token kind is a valid type specifier
99 case tok::kw_short:
100 case tok::kw_long:
101 case tok::kw___int64:
102 case tok::kw___int128:
103 case tok::kw_signed:
104 case tok::kw_unsigned:
105 case tok::kw_void:
106 case tok::kw_char:
107 case tok::kw_int:
108 case tok::kw_half:
109 case tok::kw_float:
110 case tok::kw_double:
111 case tok::kw_wchar_t:
112 case tok::kw_bool:
113 case tok::kw___underlying_type:
114 return true;
115
116 case tok::annot_typename:
117 case tok::kw_char16_t:
118 case tok::kw_char32_t:
119 case tok::kw_typeof:
David Majnemera5e92552013-09-22 01:24:26 +0000120 case tok::annot_decltype:
Kaelyn Uhrain237c7d32012-06-15 23:45:51 +0000121 case tok::kw_decltype:
122 return getLangOpts().CPlusPlus;
123
124 default:
125 break;
126 }
127
128 return false;
129}
130
Douglas Gregorec6e1892009-02-04 19:16:12 +0000131/// \brief If the identifier refers to a type name within this scope,
132/// return the declaration of that type.
133///
134/// This routine performs ordinary name lookup of the identifier II
135/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000136/// determine whether the name refers to a type. If so, returns an
137/// opaque pointer (actually a QualType) corresponding to that
138/// type. Otherwise, returns NULL.
Dmitri Gribenko5267fdf2013-05-03 13:12:11 +0000139ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
John McCallba7bf592010-08-24 05:47:05 +0000140 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +0000141 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +0000142 ParsedType ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000143 bool IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000144 bool WantNontrivialTypeSourceInfo,
145 IdentifierInfo **CorrectedII) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000146 // Determine where we will perform name lookup.
Craig Topperc3ec1492014-05-26 06:22:03 +0000147 DeclContext *LookupCtx = nullptr;
Douglas Gregora25d65d2009-11-20 22:03:38 +0000148 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +0000149 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000150 if (ObjectType->isRecordType())
151 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +0000152 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +0000153 LookupCtx = computeDeclContext(*SS, false);
154
155 if (!LookupCtx) {
156 if (isDependentScopeSpecifier(*SS)) {
157 // C++ [temp.res]p3:
158 // A qualified-id that refers to a type and in which the
159 // nested-name-specifier depends on a template-parameter (14.6.2)
160 // shall be prefixed by the keyword typename to indicate that the
161 // qualified-id denotes a type, forming an
162 // elaborated-type-specifier (7.1.5.3).
163 //
164 // We therefore do not perform any name lookup if the result would
165 // refer to a member of an unknown specialization.
Richard Smith23d55872012-04-02 01:30:27 +0000166 if (!isClassName && !IsCtorOrDtorName)
John McCallba7bf592010-08-24 05:47:05 +0000167 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000168
John McCallc392f372010-06-11 00:33:02 +0000169 // We know from the grammar that this name refers to a type,
170 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +0000171 if (WantNontrivialTypeSourceInfo)
172 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
173
174 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
Nico Weberdfc59202014-05-03 22:07:35 +0000175 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
176 II, NameLoc);
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 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000213
214 NamedDecl *IIDecl = nullptr;
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(),
John Thompson2255f2c2014-04-23 12:57:01 +0000221 Kind, S, SS, Validator,
222 CTK_ErrorRecovery);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
224 TemplateTy Template;
225 bool MemberOfUnknownSpecialization;
226 UnqualifiedId TemplateName;
227 TemplateName.setIdentifier(NewII, NameLoc);
228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
229 CXXScopeSpec NewSS, *NewSSPtr = SS;
230 if (SS && NNS) {
231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 NewSSPtr = &NewSS;
233 }
234 if (Correction && (NNS || NewII != &II) &&
235 // Ignore a correction to a template type as the to-be-corrected
236 // identifier is not a template (typo correction for template names
237 // is handled elsewhere).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000238 !(getLangOpts().CPlusPlus && NewSSPtr &&
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
240 false, Template, MemberOfUnknownSpecialization))) {
241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
242 isClassName, HasTrailingDot, ObjectTypePtr,
Abramo Bagnara4244b432012-01-27 08:46:19 +0000243 IsCtorOrDtorName,
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000244 WantNontrivialTypeSourceInfo);
245 if (Ty) {
Richard Smithf9b15102013-08-17 00:46:16 +0000246 diagnoseTypo(Correction,
247 PDiag(diag::err_unknown_type_or_class_name_suggest)
248 << Result.getLookupName() << isClassName);
Kaelyn Uhrain85308c62011-10-11 01:02:41 +0000249 if (SS && NNS)
250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
251 *CorrectedII = NewII;
252 return Ty;
253 }
254 }
255 }
256 // If typo correction failed or was not performed, fall through
Chris Lattnera3778332009-02-16 22:07:16 +0000257 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000258 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000259 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000260 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000261
Chris Lattnere40853a2009-10-25 22:09:09 +0000262 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000263 // Recover from type-hiding ambiguities by hiding the type. We'll
264 // do the lookup again when looking for an object, and we can
265 // diagnose the error then. If we don't do this, then the error
266 // about hiding the type will be immediately followed by an error
267 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
269 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000270 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000271 }
John McCall6538c932009-10-10 05:48:19 +0000272
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000273 // Look to see if we have a type anywhere in the list of results.
274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
275 Res != ResEnd; ++Res) {
276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000277 if (!IIDecl ||
278 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000279 IIDecl->getLocation().getRawEncoding())
280 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000281 }
282 }
283
284 if (!IIDecl) {
285 // None of the entities we found is a type, so there is no way
286 // to even assume that the result is a type. In this case, don't
287 // complain about the ambiguity. The parser will either try to
288 // perform this lookup again (e.g., as an object name), which
289 // will produce the ambiguity, or will complain that it expected
290 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000291 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000292 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000293 }
294
295 // We found a type within the ambiguous lookup; diagnose the
296 // ambiguity and then return that type. This might be the right
297 // answer, or it might not be, but it suppresses any attempt to
298 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000299 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000300
Chris Lattnera3778332009-02-16 22:07:16 +0000301 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000302 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000303 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000304 }
305
Chris Lattner17e15f12009-10-25 17:16:46 +0000306 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000307
Chris Lattner17e15f12009-10-25 17:16:46 +0000308 QualType T;
309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000310 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000311
Nico Weberdfc59202014-05-03 22:07:35 +0000312 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
Reid Klecknerdf6e4a02014-06-06 22:36:36 +0000346// Builds a fake NNS for the given decl context.
347static NestedNameSpecifier *
348synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
349 for (;; DC = DC->getLookupParent()) {
350 DC = DC->getPrimaryContext();
351 auto *ND = dyn_cast<NamespaceDecl>(DC);
352 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
353 return NestedNameSpecifier::Create(Context, nullptr, ND);
354 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
355 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
356 RD->getTypeForDecl());
357 else if (isa<TranslationUnitDecl>(DC))
358 return NestedNameSpecifier::GlobalSpecifier(Context);
359 }
360 llvm_unreachable("something isn't in TU scope?");
361}
362
363ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
364 SourceLocation NameLoc) {
365 // Accepting an undeclared identifier as a default argument for a template
366 // type parameter is a Microsoft extension.
367 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
368
369 // Build a fake DependentNameType that will perform lookup into CurContext at
370 // instantiation time. The name specifier isn't dependent, so template
371 // instantiation won't transform it. It will retry the lookup, however.
372 NestedNameSpecifier *NNS =
373 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
374 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
375
376 // Build type location information. We synthesized the qualifier, so we have
377 // to build a fake NestedNameSpecifierLoc.
378 NestedNameSpecifierLocBuilder NNSLocBuilder;
379 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
380 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
381
382 TypeLocBuilder Builder;
383 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
384 DepTL.setNameLoc(NameLoc);
385 DepTL.setElaboratedKeywordLoc(SourceLocation());
386 DepTL.setQualifierLoc(QualifierLoc);
387 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
388}
389
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000390/// isTagName() - This method is called *for error recovery purposes only*
391/// to determine if the specified name is a valid tag name ("struct foo"). If
392/// so, this returns the TST for the tag corresponding to it (TST_enum,
Joao Matosdc86f942012-08-31 18:45:21 +0000393/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
394/// cases in C where the user forgot to specify the tag.
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000395DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
396 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000397 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
398 LookupName(R, S, false);
399 R.suppressDiagnostics();
400 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000401 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000402 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000403 case TTK_Struct: return DeclSpec::TST_struct;
Joao Matosdc86f942012-08-31 18:45:21 +0000404 case TTK_Interface: return DeclSpec::TST_interface;
Abramo Bagnara6150c882010-05-11 21:36:43 +0000405 case TTK_Union: return DeclSpec::TST_union;
406 case TTK_Class: return DeclSpec::TST_class;
407 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000408 }
409 }
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000411 return DeclSpec::TST_unspecified;
412}
413
Francois Pichet48c946e2011-04-13 02:38:49 +0000414/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
415/// if a CXXScopeSpec's type is equal to the type of one of the base classes
416/// then downgrade the missing typename error to a warning.
417/// This is needed for MSVC compatibility; Example:
418/// @code
419/// template<class T> class A {
420/// public:
421/// typedef int TYPE;
422/// };
423/// template<class T> class B : public A<T> {
424/// public:
425/// A<T>::TYPE a; // no typename required because A<T> is a base class.
426/// };
427/// @endcode
Francois Pichet9a57fb52011-10-11 01:50:09 +0000428bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000429 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000430 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000431
432 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
Aaron Ballman574705e2014-03-13 15:41:46 +0000433 for (const auto &Base : RD->bases())
434 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
Francois Pichet48c946e2011-04-13 02:38:49 +0000435 return true;
Francois Pichet9a57fb52011-10-11 01:50:09 +0000436 return S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000437 }
Francois Pichet9a57fb52011-10-11 01:50:09 +0000438 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
Francois Pichet48c946e2011-04-13 02:38:49 +0000439}
440
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000441bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
Douglas Gregor15e56022009-10-13 23:27:22 +0000442 SourceLocation IILoc,
443 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000444 CXXScopeSpec *SS,
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000445 ParsedType &SuggestedType,
446 bool AllowClassTemplates) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000447 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000448 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000449
Douglas Gregor2d435302009-12-30 17:04:44 +0000450 // There may have been a typo in the name of the type. Look up typo
451 // results, in case we have something that we can suggest.
Kaelyn Uhrain67b44c92014-02-13 20:14:07 +0000452 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000453 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000454 LookupOrdinaryName, S, SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000455 Validator, CTK_ErrorRecovery)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000456 if (Corrected.isKeyword()) {
457 // We corrected to a keyword.
Richard Smithf9b15102013-08-17 00:46:16 +0000458 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
459 II = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000460 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000461 // We found a similarly-named type or interface; suggest that.
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000462 if (!SS || !SS->isSet()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000463 diagnoseTypo(Corrected,
464 PDiag(diag::err_unknown_typename_suggest) << II);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000465 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000466 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
467 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000468 II->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000469 diagnoseTypo(Corrected,
470 PDiag(diag::err_unknown_nested_typename_suggest)
471 << II << DC << DroppedSpecifier << SS->getRange());
472 } else {
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000473 llvm_unreachable("could not have corrected a typo here");
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000474 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000475
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000476 CXXScopeSpec tmpSS;
477 if (Corrected.getCorrectionSpecifier())
478 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
479 SourceRange(IILoc));
Richard Smithf9b15102013-08-17 00:46:16 +0000480 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
Kaelyn Uhrainf7343012013-09-26 21:13:05 +0000481 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
482 false, ParsedType(),
Abramo Bagnara4244b432012-01-27 08:46:19 +0000483 /*IsCtorOrDtorName=*/false,
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000484 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor2d435302009-12-30 17:04:44 +0000485 }
Kaelyn Uhrainb1378402012-01-18 21:41:41 +0000486 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000487 }
488
David Blaikiebbafb8a2012-03-11 07:00:24 +0000489 if (getLangOpts().CPlusPlus) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000490 // See if II is a class template that the user forgot to pass arguments to.
491 UnqualifiedId Name;
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000492 Name.setIdentifier(II, IILoc);
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000493 CXXScopeSpec EmptySS;
494 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000495 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000496 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000497 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000498 MemberOfUnknownSpecialization) == TNK_Type_template) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +0000499 TemplateName TplName = TemplateResult.get();
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000500 Diag(IILoc, diag::err_template_missing_args) << TplName;
501 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
502 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
503 << TplDecl->getTemplateParameters()->getSourceRange();
504 }
505 return true;
506 }
507 }
508
Douglas Gregor15e56022009-10-13 23:27:22 +0000509 // FIXME: Should we move the logic that tries to recover from a missing tag
510 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
511
Douglas Gregor2d435302009-12-30 17:04:44 +0000512 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000513 Diag(IILoc, diag::err_unknown_typename) << II;
Douglas Gregor15e56022009-10-13 23:27:22 +0000514 else if (DeclContext *DC = computeDeclContext(*SS, false))
515 Diag(IILoc, diag::err_typename_nested_not_found)
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000516 << II << DC << SS->getRange();
Douglas Gregor15e56022009-10-13 23:27:22 +0000517 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000518 unsigned DiagID = diag::err_typename_missing;
Alp Tokerbfa39342014-01-14 12:51:41 +0000519 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
Reid Kleckner32506ed2014-06-12 23:03:48 +0000520 DiagID = diag::ext_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000521
522 Diag(SS->getRange().getBegin(), DiagID)
Aaron Ballman691e2272014-01-03 14:48:20 +0000523 << SS->getScopeRep() << II->getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000524 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000525 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Kaelyn Uhrainb5b17fe2012-06-15 23:45:58 +0000526 SuggestedType = ActOnTypenameType(S, SourceLocation(),
527 *SS, *II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000528 } else {
529 assert(SS && SS->isInvalid() &&
530 "Invalid scope specifier has already been diagnosed");
531 }
532
533 return true;
534}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000535
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000536/// \brief Determine whether the given result set contains either a type name
537/// or
538static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000539 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000540 NextToken.is(tok::less);
541
542 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
543 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
544 return true;
545
546 if (CheckTemplate && isa<TemplateDecl>(*I))
547 return true;
548 }
549
550 return false;
551}
552
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000553static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
554 Scope *S, CXXScopeSpec &SS,
555 IdentifierInfo *&Name,
556 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000557 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
558 SemaRef.LookupParsedName(R, S, &SS);
559 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Alp Toker68837432014-05-20 22:03:47 +0000560 StringRef FixItTagName;
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000561 switch (Tag->getTagKind()) {
562 case TTK_Class:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000563 FixItTagName = "class ";
564 break;
565
566 case TTK_Enum:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000567 FixItTagName = "enum ";
568 break;
569
570 case TTK_Struct:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000571 FixItTagName = "struct ";
572 break;
573
Joao Matosdc86f942012-08-31 18:45:21 +0000574 case TTK_Interface:
Joao Matosdc86f942012-08-31 18:45:21 +0000575 FixItTagName = "__interface ";
576 break;
577
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000578 case TTK_Union:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000579 FixItTagName = "union ";
580 break;
581 }
582
Alp Toker68837432014-05-20 22:03:47 +0000583 StringRef TagName = FixItTagName.drop_back();
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000584 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
585 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
586 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
587
Richard Smithaa31b4b2012-09-06 01:37:56 +0000588 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
589 I != IEnd; ++I)
590 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
591 << Name << TagName;
592
593 // Replace lookup results with just the tag decl.
594 Result.clear(Sema::LookupTagName);
595 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000596 return true;
597 }
598
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000599 return false;
600}
601
Richard Smith4f605af2012-08-18 00:55:03 +0000602/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
603static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
604 QualType T, SourceLocation NameLoc) {
605 ASTContext &Context = S.Context;
606
607 TypeLocBuilder Builder;
608 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
609
610 T = S.getElaboratedType(ETK_None, SS, T);
611 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
612 ElabTL.setElaboratedKeywordLoc(SourceLocation());
613 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
614 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
615}
616
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000617Sema::NameClassification Sema::ClassifyName(Scope *S,
618 CXXScopeSpec &SS,
619 IdentifierInfo *&Name,
620 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000621 const Token &NextToken,
622 bool IsAddressOfOperand,
623 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000624 DeclarationNameInfo NameInfo(Name, NameLoc);
625 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000626
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000627 if (NextToken.is(tok::coloncolon)) {
628 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000629 QualType(), false, SS, nullptr, false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000630 }
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000631
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000632 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
633 LookupParsedName(Result, S, &SS, !CurMethod);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000634
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000635 // Perform lookup for Objective-C instance variables (including automatically
636 // synthesized instance variables), if we're in an Objective-C method.
637 // FIXME: This lookup really, really needs to be folded in to the normal
638 // unqualified lookup mechanism.
639 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
640 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000641 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000642 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000643 }
644
645 bool SecondTry = false;
646 bool IsFilteredTemplateName = false;
647
648Corrected:
649 switch (Result.getResultKind()) {
650 case LookupResult::NotFound:
651 // If an unqualified-id is followed by a '(', then we have a function
652 // call.
653 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
654 // In C++, this is an ADL-only call.
655 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000657 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
658
659 // C90 6.3.2.2:
660 // If the expression that precedes the parenthesized argument list in a
661 // function call consists solely of an identifier, and if no
662 // declaration is visible for this identifier, the identifier is
663 // implicitly declared exactly as if, in the innermost block containing
664 // the function call, the declaration
665 //
666 // extern int identifier ();
667 //
668 // appeared.
669 //
670 // We also allow this in C99 as an extension.
671 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
672 Result.addDecl(D);
673 Result.resolveKind();
674 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
675 }
676 }
677
678 // In C, we first see whether there is a tag type by the same name, in
679 // which case it's likely that the user just forget to write "enum",
680 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000681 if (!getLangOpts().CPlusPlus && !SecondTry &&
682 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
683 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000684 }
685
686 // Perform typo correction to determine if there is another name that is
687 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000688 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000689 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000690 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000691 Result.getLookupKind(), S,
John Thompson2255f2c2014-04-23 12:57:01 +0000692 &SS, *CCC,
693 CTK_ErrorRecovery)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000694 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
695 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000696
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000697 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000698 NamedDecl *UnderlyingFirstDecl
Craig Topperc3ec1492014-05-26 06:22:03 +0000699 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000700 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000701 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000702 UnqualifiedDiag = diag::err_no_template_suggest;
703 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000704 } else if (UnderlyingFirstDecl &&
705 (isa<TypeDecl>(UnderlyingFirstDecl) ||
706 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
707 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000708 UnqualifiedDiag = diag::err_unknown_typename_suggest;
709 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
710 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000711
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000712 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000713 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000714 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000715 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
716 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000717 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000718 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
719 << Name << computeDeclContext(SS, false)
720 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000721 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000722
723 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000724 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000725
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000726 // Typo correction corrected to a keyword.
727 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000728 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000729
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000730 // Also update the LookupResult...
731 // FIXME: This should probably go away at some point
732 Result.clear();
733 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000734 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000735 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000736
737 // If we found an Objective-C instance variable, let
738 // LookupInObjCMethod build the appropriate expression to
739 // reference the ivar.
740 // FIXME: This is a gross hack.
741 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
742 Result.clear();
743 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000744 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000745 }
746
747 goto Corrected;
748 }
749 }
750
751 // We failed to correct; just fall through and let the parser deal with it.
752 Result.suppressDiagnostics();
753 return NameClassification::Unknown();
754
Abramo Bagnara7945c982012-01-27 09:46:47 +0000755 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000756 // We performed name lookup into the current instantiation, and there were
757 // dependent bases, so we treat this result the same way as any other
758 // dependent nested-name-specifier.
759
760 // C++ [temp.res]p2:
761 // A name used in a template declaration or definition and that is
762 // dependent on a template-parameter is assumed not to name a type
763 // unless the applicable name lookup finds a type name or the name is
764 // qualified by the keyword typename.
765 //
766 // FIXME: If the next token is '<', we might want to ask the parser to
767 // perform some heroics to see if we actually have a
768 // template-argument-list, which would indicate a missing 'template'
769 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000770 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
771 NameInfo, IsAddressOfOperand,
Craig Topperc3ec1492014-05-26 06:22:03 +0000772 /*TemplateArgs=*/nullptr);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000773 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000774
775 case LookupResult::Found:
776 case LookupResult::FoundOverloaded:
777 case LookupResult::FoundUnresolvedValue:
778 break;
779
780 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000782 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000783 // C++ [temp.local]p3:
784 // A lookup that finds an injected-class-name (10.2) can result in an
785 // ambiguity in certain cases (for example, if it is found in more than
786 // one base class). If all of the injected-class-names that are found
787 // refer to specializations of the same class template, and if the name
788 // is followed by a template-argument-list, the reference refers to the
789 // class template itself and not a specialization thereof, and is not
790 // ambiguous.
791 //
792 // This filtering can make an ambiguous result into an unambiguous one,
793 // so try again after filtering out template names.
794 FilterAcceptableTemplateNames(Result);
795 if (!Result.isAmbiguous()) {
796 IsFilteredTemplateName = true;
797 break;
798 }
799 }
800
801 // Diagnose the ambiguity and return an error.
802 return NameClassification::Error();
803 }
804
David Blaikiebbafb8a2012-03-11 07:00:24 +0000805 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000806 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
807 // C++ [temp.names]p3:
808 // After name lookup (3.4) finds that a name is a template-name or that
809 // an operator-function-id or a literal- operator-id refers to a set of
810 // overloaded functions any member of which is a function template if
811 // this is followed by a <, the < is always taken as the delimiter of a
812 // template-argument-list and never as the less-than operator.
813 if (!IsFilteredTemplateName)
814 FilterAcceptableTemplateNames(Result);
815
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000816 if (!Result.empty()) {
817 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000818 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000819 TemplateName Template;
820 if (Result.end() - Result.begin() > 1) {
821 IsFunctionTemplate = true;
822 Template = Context.getOverloadedTemplateName(Result.begin(),
823 Result.end());
824 } else {
825 TemplateDecl *TD
826 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
827 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000828 IsVarTemplate = isa<VarTemplateDecl>(TD);
829
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000830 if (SS.isSet() && !SS.isInvalid())
831 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000832 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000833 TD);
834 else
835 Template = TemplateName(TD);
836 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000837
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000838 if (IsFunctionTemplate) {
839 // Function templates always go through overload resolution, at which
840 // point we'll perform the various checks (e.g., accessibility) we need
841 // to based on which function we selected.
842 Result.suppressDiagnostics();
843
844 return NameClassification::FunctionTemplate(Template);
845 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000846
847 return IsVarTemplate ? NameClassification::VarTemplate(Template)
848 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000849 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000850 }
Richard Smith4f605af2012-08-18 00:55:03 +0000851
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000852 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000853 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
854 DiagnoseUseOfDecl(Type, NameLoc);
855 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000856 if (SS.isNotEmpty())
857 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000858 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000859 }
Richard Smith4f605af2012-08-18 00:55:03 +0000860
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000861 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
862 if (!Class) {
863 // FIXME: It's unfortunate that we don't have a Type node for handling this.
Nico Weberdfc59202014-05-03 22:07:35 +0000864 if (ObjCCompatibleAliasDecl *Alias =
865 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000866 Class = Alias->getClassInterface();
867 }
868
869 if (Class) {
870 DiagnoseUseOfDecl(Class, NameLoc);
871
872 if (NextToken.is(tok::period)) {
873 // Interface. <something> is parsed as a property reference expression.
874 // Just return "unknown" as a fall-through for now.
875 Result.suppressDiagnostics();
876 return NameClassification::Unknown();
877 }
878
879 QualType T = Context.getObjCInterfaceType(Class);
880 return ParsedType::make(T);
881 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000882
Richard Smith4f605af2012-08-18 00:55:03 +0000883 // We can have a type template here if we're classifying a template argument.
884 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
885 return NameClassification::TypeTemplate(
886 TemplateName(cast<TemplateDecl>(FirstDecl)));
887
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000888 // Check for a tag type hidden by a non-type decl in a few cases where it
889 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000890 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
891 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000892 (NextIsOp &&
893 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000894 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
895 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
896 DiagnoseUseOfDecl(Type, NameLoc);
897 QualType T = Context.getTypeDeclType(Type);
898 if (SS.isNotEmpty())
899 return buildNestedType(*this, SS, T, NameLoc);
900 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000901 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000902
Richard Smith4f605af2012-08-18 00:55:03 +0000903 if (FirstDecl->isCXXClassMember())
Craig Topperc3ec1492014-05-26 06:22:03 +0000904 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
905 nullptr);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000906
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000907 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
908 return BuildDeclarationNameExpr(SS, Result, ADL);
909}
910
John McCall5ed6e8f2009-08-18 00:00:49 +0000911// Determines the context to return to after temporarily entering a
912// context. This depends in an unnecessarily complicated way on the
913// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000914DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000915
John McCall5ed6e8f2009-08-18 00:00:49 +0000916 // Functions defined inline within classes aren't parsed until we've
917 // finished parsing the top-level class, so the top-level class is
918 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000919 // A Lambda call operator whose parent is a class must not be treated
920 // as an inline member function. A Lambda can be used legally
921 // either as an in-class member initializer or a default argument. These
922 // are parsed once the class has been marked complete and so the containing
923 // context would be the nested class (when the lambda is defined in one);
924 // If the class is not complete, then the lambda is being used in an
925 // ill-formed fashion (such as to specify the width of a bit-field, or
926 // in an array-bound) - in which case we still want to return the
927 // lexically containing DC (which could be a nested class).
928 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000929 DC = DC->getLexicalParent();
930
931 // A function not defined within a class will always return to its
932 // lexical context.
933 if (!isa<CXXRecordDecl>(DC))
934 return DC;
935
936 // A C++ inline method/friend is parsed *after* the topmost class
937 // it was declared in is fully parsed ("complete"); the topmost
938 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000939 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000940 DC = RD;
941
942 // Return the declaration context of the topmost class the inline method is
943 // declared in.
944 return DC;
945 }
946
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000947 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948}
949
Douglas Gregor91f84212008-12-11 16:49:14 +0000950void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000951 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000952 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000953 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000954 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000955}
956
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000957void Sema::PopDeclContext() {
958 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000959
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000960 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000961 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000962}
963
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000964/// EnterDeclaratorContext - Used when we must lookup names in the context
965/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000966///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000967void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000968 // C++0x [basic.lookup.unqual]p13:
969 // A name used in the definition of a static data member of class
970 // X (after the qualified-id of the static member) is looked up as
971 // if the name was used in a member function of X.
972 // C++0x [basic.lookup.unqual]p14:
973 // If a variable member of a namespace is defined outside of the
974 // scope of its namespace then any name used in the definition of
975 // the variable member (after the declarator-id) is looked up as
976 // if the definition of the variable member occurred in its
977 // namespace.
978 // Both of these imply that we should push a scope whose context
979 // is the semantic context of the declaration. We can't use
980 // PushDeclContext here because that context is not necessarily
981 // lexically contained in the current context. Fortunately,
982 // the containing scope should have the appropriate information.
983
984 assert(!S->getEntity() && "scope already has entity");
985
986#ifndef NDEBUG
987 Scope *Ancestor = S->getParent();
988 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
989 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
990#endif
991
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000992 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000993 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000994}
995
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000996void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000997 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000998
John McCall6df5fef2009-12-19 10:49:29 +0000999 // Switch back to the lexical context. The safety of this is
1000 // enforced by an assert in EnterDeclaratorContext.
1001 Scope *Ancestor = S->getParent();
1002 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +00001003 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +00001004
1005 // We don't need to do anything with the scope, which is going to
1006 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001007}
1008
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001009
1010void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +00001011 // We assume that the caller has already called
1012 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1013 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001014 if (!FD)
1015 return;
1016
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001017 // Same implementation as PushDeclContext, but enters the context
1018 // from the lexical parent, rather than the top-level class.
1019 assert(CurContext == FD->getLexicalParent() &&
1020 "The next DeclContext should be lexically contained in the current one.");
1021 CurContext = FD;
1022 S->setEntity(CurContext);
1023
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001024 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1025 ParmVarDecl *Param = FD->getParamDecl(P);
1026 // If the parameter has an identifier, then add it to the scope
1027 if (Param->getIdentifier()) {
1028 S->AddDecl(Param);
1029 IdResolver.AddDecl(Param);
1030 }
1031 }
1032}
1033
1034
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001035void Sema::ActOnExitFunctionContext() {
1036 // Same implementation as PopDeclContext, but returns to the lexical parent,
1037 // rather than the top-level class.
1038 assert(CurContext && "DeclContext imbalance!");
1039 CurContext = CurContext->getLexicalParent();
1040 assert(CurContext && "Popped translation unit!");
1041}
1042
1043
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044/// \brief Determine whether we allow overloading of the function
1045/// PrevDecl with another declaration.
1046///
1047/// This routine determines whether overloading is possible, not
1048/// whether some new function is actually an overload. It will return
1049/// true in C++ (where we can always provide overloads) or, as an
1050/// extension, in C when the previous function is already an
1051/// overloaded function declaration or has the "overloadable"
1052/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001053static bool AllowOverloadingOfFunction(LookupResult &Previous,
1054 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001055 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 return true;
1057
John McCall1f82f242009-11-18 22:49:29 +00001058 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 return true;
1060
John McCall1f82f242009-11-18 22:49:29 +00001061 return (Previous.getResultKind() == LookupResult::Found
1062 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063}
1064
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001065/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001066void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001067 // Move up the scope chain until we find the nearest enclosing
1068 // non-transparent context. The declaration will be introduced into this
1069 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001070 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001071 S = S->getParent();
1072
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001073 // Add scoped declarations into their context, so that they can be
1074 // found later. Declarations without a context won't be inserted
1075 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001076 if (AddToContext)
1077 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001078
Richard Smith541b38b2013-09-20 01:15:31 +00001079 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1080 // are function-local declarations.
1081 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001082 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001083 D->getLexicalDeclContext()->getRedeclContext()) &&
1084 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001085 return;
1086
1087 // Template instantiations should also not be pushed into scope.
1088 if (isa<FunctionDecl>(D) &&
1089 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001090 return;
1091
John McCall9f3059a2009-10-09 21:13:30 +00001092 // If this replaces anything in the current scope,
1093 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1094 IEnd = IdResolver.end();
1095 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001096 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1097 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001098 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001099
John McCall9f3059a2009-10-09 21:13:30 +00001100 // Should only need to replace one decl.
1101 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001102 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001103 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001104
John McCall48871652010-08-21 09:40:31 +00001105 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001106
1107 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1108 // Implicitly-generated labels may end up getting generated in an order that
1109 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1110 // the label at the appropriate place in the identifier chain.
1111 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001112 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001113 if (IDC == CurContext) {
1114 if (!S->isDeclScope(*I))
1115 continue;
1116 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001117 break;
1118 }
1119
Douglas Gregor46c04e72011-03-16 16:39:03 +00001120 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001121 } else {
1122 IdResolver.AddDecl(D);
1123 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001124}
1125
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001126void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1127 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1128 TUScope->AddDecl(D);
1129}
1130
Richard Smith1c34fb72013-08-13 18:18:50 +00001131bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001132 bool AllowInlineNamespace) {
1133 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001134}
1135
John McCallcc14d1f2010-08-24 08:50:51 +00001136Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1137 DeclContext *TargetDC = DC->getPrimaryContext();
1138 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001139 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001140 if (ScopeDC->getPrimaryContext() == TargetDC)
1141 return S;
1142 } while ((S = S->getParent()));
1143
Craig Topperc3ec1492014-05-26 06:22:03 +00001144 return nullptr;
John McCallcc14d1f2010-08-24 08:50:51 +00001145}
1146
John McCall1f82f242009-11-18 22:49:29 +00001147static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1148 DeclContext*,
1149 ASTContext&);
1150
1151/// Filters out lookup results that don't fall within the given scope
1152/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001153void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001154 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001155 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001156 LookupResult::Filter F = R.makeFilter();
1157 while (F.hasNext()) {
1158 NamedDecl *D = F.next();
1159
Richard Smith72bcaec2013-12-05 04:30:04 +00001160 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001161 continue;
1162
Richard Smith72bcaec2013-12-05 04:30:04 +00001163 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001164 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001165
John McCall1f82f242009-11-18 22:49:29 +00001166 F.erase();
1167 }
1168
1169 F.done();
1170}
1171
1172static bool isUsingDecl(NamedDecl *D) {
1173 return isa<UsingShadowDecl>(D) ||
1174 isa<UnresolvedUsingTypenameDecl>(D) ||
1175 isa<UnresolvedUsingValueDecl>(D);
1176}
1177
1178/// Removes using shadow declarations from the lookup results.
1179static void RemoveUsingDecls(LookupResult &R) {
1180 LookupResult::Filter F = R.makeFilter();
1181 while (F.hasNext())
1182 if (isUsingDecl(F.next()))
1183 F.erase();
1184
1185 F.done();
1186}
1187
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001188/// \brief Check for this common pattern:
1189/// @code
1190/// class S {
1191/// S(const S&); // DO NOT IMPLEMENT
1192/// void operator=(const S&); // DO NOT IMPLEMENT
1193/// };
1194/// @endcode
1195static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1196 // FIXME: Should check for private access too but access is set after we get
1197 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001198 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001199 return false;
1200
1201 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1202 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001203 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1204 return Method->isCopyAssignmentOperator();
1205 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001206}
1207
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001208// We need this to handle
1209//
1210// typedef struct {
1211// void *foo() { return 0; }
1212// } A;
1213//
1214// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1215// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001216// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001217// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001218// Callers should verify at the end of the TU if it D has external linkage or
1219// not.
1220bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1221 const DeclContext *DC = D->getDeclContext();
1222 while (!DC->isTranslationUnit()) {
1223 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1224 if (!RD->hasNameForLinkage())
1225 return true;
1226 }
1227 DC = DC->getParent();
1228 }
1229
Rafael Espindola3ae00052013-05-13 00:12:11 +00001230 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001231}
1232
Eli Friedman5ef21752013-09-10 03:05:56 +00001233// FIXME: This needs to be refactored; some other isInMainFile users want
1234// these semantics.
1235static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1236 if (S.TUKind != TU_Complete)
1237 return false;
1238 return S.SourceMgr.isInMainFile(Loc);
1239}
1240
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001241bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1242 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001243
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001244 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1245 return false;
1246
Richard Smithc3926172014-04-02 18:28:36 +00001247 // Ignore all entities declared within templates, and out-of-line definitions
1248 // of members of class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001249 if (D->getDeclContext()->isDependentContext() ||
1250 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001251 return false;
1252
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001253 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001254 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1255 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001256
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001257 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1258 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1259 return false;
1260 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001261 // 'static inline' functions are defined in headers; don't warn.
Richard Smitha90ee352014-05-11 21:25:24 +00001262 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001263 return false;
1264 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001265
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001266 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001267 Context.DeclMustBeEmitted(FD))
1268 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001269 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001270 // Constants and utility variables are defined in headers with internal
1271 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1272 // like "inline".)
1273 if (!isMainFileLoc(*this, VD->getLocation()))
1274 return false;
1275
Eli Friedman5ef21752013-09-10 03:05:56 +00001276 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001277 return false;
1278
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001279 if (VD->isStaticDataMember() &&
1280 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1281 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001282 } else {
1283 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001284 }
1285
John McCalld37d35b2010-10-27 01:41:35 +00001286 // Only warn for unused decls internal to the translation unit.
Richard Smitha90ee352014-05-11 21:25:24 +00001287 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1288 // for inline functions defined in the main source file, for instance.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001289 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001290}
1291
1292void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001293 if (!D)
1294 return;
1295
1296 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001297 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001298 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1299 return; // First should already be in the vector.
1300 }
1301
1302 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001303 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001304 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1305 return; // First should already be in the vector.
1306 }
1307
David Blaikie3d8edc22012-05-26 05:35:39 +00001308 if (ShouldWarnIfUnusedFileScopedDecl(D))
1309 UnusedFileScopedDecls.push_back(D);
1310}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001311
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001312static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001313 if (D->isInvalidDecl())
1314 return false;
1315
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001316 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1317 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001318 return false;
John McCall67da35c2010-02-04 22:26:26 +00001319
Chris Lattnercab02a62011-02-17 20:34:02 +00001320 if (isa<LabelDecl>(D))
1321 return true;
1322
John McCall67da35c2010-02-04 22:26:26 +00001323 // White-list anything that isn't a local variable.
1324 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1325 !D->getDeclContext()->isFunctionOrMethod())
1326 return false;
1327
1328 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001329 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001330
1331 // White-list anything with an __attribute__((unused)) type.
1332 QualType Ty = VD->getType();
1333
1334 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001335 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001336 if (TT->getDecl()->hasAttr<UnusedAttr>())
1337 return false;
1338 }
1339
Douglas Gregor14f232e2010-05-08 23:05:03 +00001340 // If we failed to complete the type for some reason, or if the type is
1341 // dependent, don't diagnose the variable.
1342 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001343 return false;
1344
John McCallcef15822010-03-31 02:47:45 +00001345 if (const TagType *TT = Ty->getAs<TagType>()) {
1346 const TagDecl *Tag = TT->getDecl();
1347 if (Tag->hasAttr<UnusedAttr>())
1348 return false;
1349
1350 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001351 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001352 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001353
1354 if (const Expr *Init = VD->getInit()) {
Nico Weberdfc59202014-05-03 22:07:35 +00001355 if (const ExprWithCleanups *Cleanups =
1356 dyn_cast<ExprWithCleanups>(Init))
David Blaikiea9d4a932012-10-24 21:29:06 +00001357 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001358 const CXXConstructExpr *Construct =
1359 dyn_cast<CXXConstructExpr>(Init);
1360 if (Construct && !Construct->isElidable()) {
1361 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001362 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001363 return false;
1364 }
1365 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001366 }
1367 }
John McCallcef15822010-03-31 02:47:45 +00001368
1369 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001370 }
1371
John McCall67da35c2010-02-04 22:26:26 +00001372 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001373}
1374
Anna Zaks964f4c62011-07-28 20:52:06 +00001375static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1376 FixItHint &Hint) {
1377 if (isa<LabelDecl>(D)) {
1378 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001379 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001380 if (AfterColon.isInvalid())
1381 return;
1382 Hint = FixItHint::CreateRemoval(CharSourceRange::
1383 getCharRange(D->getLocStart(), AfterColon));
1384 }
1385 return;
1386}
1387
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001388/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1389/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001390void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1391 if (!ShouldDiagnoseUnusedDecl(D))
1392 return;
1393
Nico Weberdfc59202014-05-03 22:07:35 +00001394 FixItHint Hint;
Anna Zaks964f4c62011-07-28 20:52:06 +00001395 GenerateFixForUnusedDecl(D, Context, Hint);
1396
Chris Lattnercab02a62011-02-17 20:34:02 +00001397 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001398 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001399 DiagID = diag::warn_unused_exception_param;
1400 else if (isa<LabelDecl>(D))
1401 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001402 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001403 DiagID = diag::warn_unused_variable;
1404
Anna Zaks964f4c62011-07-28 20:52:06 +00001405 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001406}
1407
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001408static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1409 // Verify that we have no forward references left. If so, there was a goto
1410 // or address of a label taken, but no definition of it. Label fwd
1411 // definitions are indicated with a null substmt.
Craig Topperc3ec1492014-05-26 06:22:03 +00001412 if (L->getStmt() == nullptr)
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001413 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1414}
1415
Steve Naroffc62adb62007-10-09 22:01:59 +00001416void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00001417 S->mergeNRVOIntoParent();
1418
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001419 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001420 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001421 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001422
Aaron Ballman35c54952014-03-17 16:55:25 +00001423 for (auto *TmpD : S->decls()) {
Steve Naroff9324db12007-09-13 18:10:37 +00001424 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001425
Douglas Gregor91f84212008-12-11 16:49:14 +00001426 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1427 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001428
Douglas Gregor91f84212008-12-11 16:49:14 +00001429 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001430
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001431 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001432 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001433 DiagnoseUnusedDecl(D);
1434
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001435 // If this was a forward reference to a label, verify it was defined.
1436 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1437 CheckPoppedLabel(LD, *this);
1438
Douglas Gregor91f84212008-12-11 16:49:14 +00001439 // Remove this name from our lexical scope.
1440 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001441 }
1442}
1443
Douglas Gregor1c283312010-08-11 12:19:30 +00001444/// \brief Look for an Objective-C class in the translation unit.
1445///
1446/// \param Id The name of the Objective-C class we're looking for. If
1447/// typo-correction fixes this name, the Id will be updated
1448/// to the fixed name.
1449///
1450/// \param IdLoc The location of the name in the translation unit.
1451///
James Dennett41725122012-06-22 10:16:05 +00001452/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001453/// if there is no class with the given name.
1454///
1455/// \returns The declaration of the named Objective-C class, or NULL if the
1456/// class could not be found.
1457ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1458 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001459 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001460 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1461 // creation from this context.
1462 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1463
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001464 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001465 // Perform typo correction at the given location, but only if we
1466 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001467 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1468 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
Craig Topperc3ec1492014-05-26 06:22:03 +00001469 LookupOrdinaryName, TUScope, nullptr,
John Thompson2255f2c2014-04-23 12:57:01 +00001470 Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001471 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001472 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001473 Id = IDecl->getIdentifier();
1474 }
1475 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001476 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1477 // This routine must always return a class definition, if any.
1478 if (Def && Def->getDefinition())
1479 Def = Def->getDefinition();
1480 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001481}
1482
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001483/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1484/// from S, where a non-field would be declared. This routine copes
1485/// with the difference between C and C++ scoping rules in structs and
1486/// unions. For example, the following code is well-formed in C but
1487/// ill-formed in C++:
1488/// @code
1489/// struct S6 {
1490/// enum { BAR } e;
1491/// };
Mike Stump11289f42009-09-09 15:08:12 +00001492///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001493/// void test_S6() {
1494/// struct S6 a;
1495/// a.e = BAR;
1496/// }
1497/// @endcode
1498/// For the declaration of BAR, this routine will return a different
1499/// scope. The scope S will be the scope of the unnamed enumeration
1500/// within S6. In C++, this routine will return the scope associated
1501/// with S6, because the enumeration's scope is a transparent
1502/// context but structures can contain non-field names. In C, this
1503/// routine will return the translation unit scope, since the
1504/// enumeration's scope is a transparent context and structures cannot
1505/// contain non-field names.
1506Scope *Sema::getNonFieldDeclScope(Scope *S) {
1507 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001508 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001509 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001510 S = S->getParent();
1511 return S;
1512}
1513
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001514/// \brief Looks up the declaration of "struct objc_super" and
1515/// saves it for later use in building builtin declaration of
1516/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1517/// pre-existing declaration exists no action takes place.
1518static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1519 IdentifierInfo *II) {
1520 if (!II->isStr("objc_msgSendSuper"))
1521 return;
1522 ASTContext &Context = ThisSema.Context;
1523
1524 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1525 SourceLocation(), Sema::LookupTagName);
1526 ThisSema.LookupName(Result, S);
1527 if (Result.getResultKind() == LookupResult::Found)
1528 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1529 Context.setObjCSuperType(Context.getTagDeclType(TD));
1530}
1531
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001532/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1533/// file scope. lazily create a decl for it. ForRedeclaration is true
1534/// if we're creating this built-in in anticipation of redeclaring the
1535/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001536NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001537 Scope *S, bool ForRedeclaration,
1538 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001539 LookupPredefedObjCSuperType(*this, S, II);
1540
Chris Lattner9561a0b2007-01-28 08:20:04 +00001541 Builtin::ID BID = (Builtin::ID)bid;
1542
Chris Lattnerecd79c62009-06-14 00:45:47 +00001543 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001544 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001545 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001546 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001547 // Okay
1548 break;
1549
Mike Stump93246cc2009-07-28 23:57:15 +00001550 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001551 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001552 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001553 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001554 return nullptr;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001555
Mike Stump93246cc2009-07-28 23:57:15 +00001556 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001557 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001558 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001559 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001560 return nullptr;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001561
1562 case ASTContext::GE_Missing_ucontext:
1563 if (ForRedeclaration)
1564 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1565 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001566 return nullptr;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001567 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001568
1569 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1570 Diag(Loc, diag::ext_implicit_lib_function_decl)
1571 << Context.BuiltinInfo.GetName(BID)
1572 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001573 if (Context.BuiltinInfo.getHeaderName(BID) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001574 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001575 Diag(Loc, diag::note_please_include_header)
1576 << Context.BuiltinInfo.getHeaderName(BID)
1577 << Context.BuiltinInfo.GetName(BID);
1578 }
1579
Warren Hunt445d83e2013-11-01 23:46:51 +00001580 DeclContext *Parent = Context.getTranslationUnitDecl();
1581 if (getLangOpts().CPlusPlus) {
1582 LinkageSpecDecl *CLinkageDecl =
1583 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1584 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001585 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001586 Parent->addDecl(CLinkageDecl);
1587 Parent = CLinkageDecl;
1588 }
1589
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001590 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001591 Parent,
Craig Topperc3ec1492014-05-26 06:22:03 +00001592 Loc, Loc, II, R, /*TInfo=*/nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001593 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001594 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001595 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001596 New->setImplicit();
1597
Chris Lattner4dd27102008-05-05 22:18:14 +00001598 // Create Decl objects for each parameter, adding them to the
1599 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001600 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001601 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001602 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001603 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001604 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001605 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1606 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00001607 parm->setScopeInfo(0, i);
1608 Params.push_back(parm);
1609 }
David Blaikie9c70e042011-09-21 18:16:56 +00001610 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
1613 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001614 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001616 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001617 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1618 // relate Scopes to DeclContexts, and probably eliminate CurContext
1619 // entirely, but we're not there yet.
1620 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001621 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001622 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001623 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001624 return New;
1625}
1626
Douglas Gregor3552dab2013-01-09 00:47:56 +00001627/// \brief Filter out any previous declarations that the given declaration
1628/// should not consider because they are not permitted to conflict, e.g.,
1629/// because they come from hidden sub-modules and do not refer to the same
1630/// entity.
1631static void filterNonConflictingPreviousDecls(ASTContext &context,
1632 NamedDecl *decl,
1633 LookupResult &previous){
1634 // This is only interesting when modules are enabled.
1635 if (!context.getLangOpts().Modules)
1636 return;
1637
1638 // Empty sets are uninteresting.
1639 if (previous.empty())
1640 return;
1641
Douglas Gregor3552dab2013-01-09 00:47:56 +00001642 LookupResult::Filter filter = previous.makeFilter();
1643 while (filter.hasNext()) {
1644 NamedDecl *old = filter.next();
1645
1646 // Non-hidden declarations are never ignored.
1647 if (!old->isHidden())
1648 continue;
1649
Rafael Espindola3ae00052013-05-13 00:12:11 +00001650 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001651 filter.erase();
1652 }
1653
1654 filter.done();
1655}
1656
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001657bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1658 QualType OldType;
1659 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1660 OldType = OldTypedef->getUnderlyingType();
1661 else
1662 OldType = Context.getTypeDeclType(Old);
1663 QualType NewType = New->getUnderlyingType();
1664
Douglas Gregoraab36982012-01-11 22:33:48 +00001665 if (NewType->isVariablyModifiedType()) {
1666 // Must not redefine a typedef with a variably-modified type.
1667 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1668 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1669 << Kind << NewType;
1670 if (Old->getLocation().isValid())
1671 Diag(Old->getLocation(), diag::note_previous_definition);
1672 New->setInvalidDecl();
1673 return true;
1674 }
1675
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001676 if (OldType != NewType &&
1677 !OldType->isDependentType() &&
1678 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001679 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001680 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1681 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1682 << Kind << NewType << OldType;
1683 if (Old->getLocation().isValid())
1684 Diag(Old->getLocation(), diag::note_previous_definition);
1685 New->setInvalidDecl();
1686 return true;
1687 }
1688 return false;
1689}
1690
Richard Smithdda56e42011-04-15 14:24:37 +00001691/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001692/// same name and scope as a previous declaration 'Old'. Figure out
1693/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001694/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001695///
Richard Smithdda56e42011-04-15 14:24:37 +00001696void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001697 // If the new decl is known invalid already, don't bother doing any
1698 // merging checks.
1699 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001700
Steve Naroff44cfcb62008-09-09 14:32:20 +00001701 // Allow multiple definitions for ObjC built-in typedefs.
1702 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001703 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001704 const IdentifierInfo *TypeID = New->getIdentifier();
1705 switch (TypeID->getLength()) {
1706 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001707 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001708 {
1709 if (!TypeID->isStr("id"))
1710 break;
1711 QualType T = New->getUnderlyingType();
1712 if (!T->isPointerType())
1713 break;
1714 if (!T->isVoidPointerType()) {
1715 QualType PT = T->getAs<PointerType>()->getPointeeType();
1716 if (!PT->isStructureType())
1717 break;
1718 }
1719 Context.setObjCIdRedefinitionType(T);
1720 // Install the built-in type for 'id', ignoring the current definition.
1721 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1722 return;
1723 }
Chris Lattner66e32812008-11-20 05:41:43 +00001724 case 5:
1725 if (!TypeID->isStr("Class"))
1726 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001727 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001728 // Install the built-in type for 'Class', ignoring the current definition.
1729 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001730 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001731 case 3:
1732 if (!TypeID->isStr("SEL"))
1733 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001734 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001735 // Install the built-in type for 'SEL', ignoring the current definition.
1736 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001737 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001738 }
1739 // Fall through - the typedef name was not a builtin type.
1740 }
John McCall1f82f242009-11-18 22:49:29 +00001741
Douglas Gregorfb034662009-01-28 17:15:10 +00001742 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001743 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1744 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001745 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001746 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001747
1748 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001749 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001750 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001751
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001752 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001753 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001754
John McCall1f82f242009-11-18 22:49:29 +00001755 // If the old declaration is invalid, just give up here.
1756 if (Old->isInvalidDecl())
1757 return New->setInvalidDecl();
1758
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001759 // If the typedef types are not identical, reject them in all languages and
1760 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001761 if (isIncompatibleTypedef(Old, New))
1762 return;
Mike Stump11289f42009-09-09 15:08:12 +00001763
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001764 // The types match. Link up the redeclaration chain and merge attributes if
1765 // the old declaration was a typedef.
1766 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001767 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001768 mergeDeclAttributes(New, Old);
1769 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001770
David Blaikiebbafb8a2012-03-11 07:00:24 +00001771 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001772 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001773
David Blaikiebbafb8a2012-03-11 07:00:24 +00001774 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001775 // C++ [dcl.typedef]p2:
1776 // In a given non-class scope, a typedef specifier can be used to
1777 // redefine the name of any type declared in that scope to refer
1778 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001779 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001780 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001781
1782 // C++0x [dcl.typedef]p4:
1783 // In a given class scope, a typedef specifier can be used to redefine
1784 // any class-name declared in that scope that is not also a typedef-name
1785 // to refer to the type to which it already refers.
1786 //
1787 // This wording came in via DR424, which was a correction to the
1788 // wording in DR56, which accidentally banned code like:
1789 //
1790 // struct S {
1791 // typedef struct A { } A;
1792 // };
1793 //
1794 // in the C++03 standard. We implement the C++0x semantics, which
1795 // allow the above but disallow
1796 //
1797 // struct S {
1798 // typedef int I;
1799 // typedef int I;
1800 // };
1801 //
1802 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001803 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001804 return;
1805
Chris Lattner2581fc32009-04-17 22:04:20 +00001806 Diag(New->getLocation(), diag::err_redefinition)
1807 << New->getDeclName();
1808 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001809 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001810 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001811
Douglas Gregor7363fb02012-01-11 04:25:01 +00001812 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001813 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001814 return;
1815
Chris Lattner2581fc32009-04-17 22:04:20 +00001816 // If we have a redefinition of a typedef in C, emit a warning. This warning
1817 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001818 // -Wtypedef-redefinition. If either the original or the redefinition is
1819 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001820 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001821 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1822 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001823 return;
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattner2581fc32009-04-17 22:04:20 +00001825 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1826 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001827 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001828 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001829}
1830
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001831/// DeclhasAttr - returns true if decl Declaration already has the target
1832/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001833static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001834 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001835 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001836 for (const auto *i : D->attrs())
1837 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001838 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001839 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001840 return true;
1841 continue;
1842 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001843 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001844 if (OA && isa<OwnershipAttr>(i))
1845 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001846 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001847 }
Chris Lattner84966392008-03-03 03:28:21 +00001848
1849 return false;
1850}
1851
Richard Smithbc8caaf2013-02-22 04:55:39 +00001852static bool isAttributeTargetADefinition(Decl *D) {
1853 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1854 return VD->isThisDeclarationADefinition();
1855 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1856 return TD->isCompleteDefinition() || TD->isBeingDefined();
1857 return true;
1858}
1859
1860/// Merge alignment attributes from \p Old to \p New, taking into account the
1861/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1862///
1863/// \return \c true if any attributes were added to \p New.
1864static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1865 // Look for alignas attributes on Old, and pick out whichever attribute
1866 // specifies the strictest alignment requirement.
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 AlignedAttr *OldAlignasAttr = nullptr;
1868 AlignedAttr *OldStrictestAlignAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001869 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001870 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001871 // FIXME: We have no way of representing inherited dependent alignments
1872 // in a case like:
1873 // template<int A, int B> struct alignas(A) X;
1874 // template<int A, int B> struct alignas(B) X {};
1875 // For now, we just ignore any alignas attributes which are not on the
1876 // definition in such a case.
1877 if (I->isAlignmentDependent())
1878 return false;
1879
1880 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001881 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001882
1883 unsigned Align = I->getAlignment(S.Context);
1884 if (Align > OldAlign) {
1885 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001886 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001887 }
1888 }
1889
1890 // Look for alignas attributes on New.
Craig Topperc3ec1492014-05-26 06:22:03 +00001891 AlignedAttr *NewAlignasAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001892 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001893 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001894 if (I->isAlignmentDependent())
1895 return false;
1896
1897 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001898 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001899
1900 unsigned Align = I->getAlignment(S.Context);
1901 if (Align > NewAlign)
1902 NewAlign = Align;
1903 }
1904
1905 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1906 // Both declarations have 'alignas' attributes. We require them to match.
1907 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1908 // fall short. (If two declarations both have alignas, they must both match
1909 // every definition, and so must match each other if there is a definition.)
1910
1911 // If either declaration only contains 'alignas(0)' specifiers, then it
1912 // specifies the natural alignment for the type.
1913 if (OldAlign == 0 || NewAlign == 0) {
1914 QualType Ty;
1915 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1916 Ty = VD->getType();
1917 else
1918 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1919
1920 if (OldAlign == 0)
1921 OldAlign = S.Context.getTypeAlign(Ty);
1922 if (NewAlign == 0)
1923 NewAlign = S.Context.getTypeAlign(Ty);
1924 }
1925
1926 if (OldAlign != NewAlign) {
1927 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1928 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1929 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1930 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1931 }
1932 }
1933
1934 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1935 // C++11 [dcl.align]p6:
1936 // if any declaration of an entity has an alignment-specifier,
1937 // every defining declaration of that entity shall specify an
1938 // equivalent alignment.
1939 // C11 6.7.5/7:
1940 // If the definition of an object does not have an alignment
1941 // specifier, any other declaration of that object shall also
1942 // have no alignment specifier.
1943 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001944 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001946 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001947 }
1948
1949 bool AnyAdded = false;
1950
1951 // Ensure we have an attribute representing the strictest alignment.
1952 if (OldAlign > NewAlign) {
1953 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1954 Clone->setInherited(true);
1955 New->addAttr(Clone);
1956 AnyAdded = true;
1957 }
1958
1959 // Ensure we have an alignas attribute if the old declaration had one.
1960 if (OldAlignasAttr && !NewAlignasAttr &&
1961 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1962 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1963 Clone->setInherited(true);
1964 New->addAttr(Clone);
1965 AnyAdded = true;
1966 }
1967
1968 return AnyAdded;
1969}
1970
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001971static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
1972 const InheritableAttr *Attr, bool Override) {
1973 InheritableAttr *NewAttr = nullptr;
Michael Han99315932013-01-24 16:46:58 +00001974 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001975 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001976 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1977 AA->getIntroduced(), AA->getDeprecated(),
1978 AA->getObsoleted(), AA->getUnavailable(),
1979 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001980 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001981 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001982 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1983 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001984 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001985 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1986 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001987 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001988 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1989 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001990 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001991 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1992 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001993 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001994 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1995 FA->getFormatIdx(), FA->getFirstArg(),
1996 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001997 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001998 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1999 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002000 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00002001 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2002 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00002003 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00002004 else if (isa<AlignedAttr>(Attr))
2005 // AlignedAttrs are handled separately, because we need to handle all
2006 // such attributes on a declaration at the same time.
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002007 NewAttr = nullptr;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00002008 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002009 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00002010
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002011 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002012 NewAttr->setInherited(true);
2013 D->addAttr(NewAttr);
2014 return true;
2015 }
2016
2017 return false;
2018}
2019
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002020static const Decl *getDefinition(const Decl *D) {
2021 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002022 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2024 const VarDecl *Def = VD->getDefinition();
2025 if (Def)
2026 return Def;
2027 return VD->getActingDefinition();
2028 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002030 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002031 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002032 return Def;
2033 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002034 return nullptr;
Rafael Espindola36191042012-05-18 01:47:00 +00002035}
2036
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002037static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002038 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002039 if (Attribute->getKind() == Kind)
2040 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002041 return false;
2042}
2043
2044/// checkNewAttributesAfterDef - If we already have a definition, check that
2045/// there are no new attributes in this declaration.
2046static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2047 if (!New->hasAttrs())
2048 return;
2049
2050 const Decl *Def = getDefinition(Old);
2051 if (!Def || Def == New)
2052 return;
2053
2054 AttrVec &NewAttributes = New->getAttrs();
2055 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2056 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002057
2058 if (isa<AliasAttr>(NewAttribute)) {
2059 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2060 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2061 else {
2062 VarDecl *VD = cast<VarDecl>(New);
2063 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2064 VarDecl::TentativeDefinition
2065 ? diag::err_alias_after_tentative
2066 : diag::err_redefinition;
2067 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2068 S.Diag(Def->getLocation(), diag::note_previous_definition);
2069 VD->setInvalidDecl();
2070 }
2071 ++I;
2072 continue;
2073 }
2074
2075 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2076 // Tentative definitions are only interesting for the alias check above.
2077 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2078 ++I;
2079 continue;
2080 }
2081 }
2082
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002083 if (hasAttribute(Def, NewAttribute->getKind())) {
2084 ++I;
2085 continue; // regular attr merging will take care of validating this.
2086 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002087
Richard Smithdebc59d2013-01-30 05:45:05 +00002088 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002089 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002090 ++I;
2091 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002092 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2093 if (AA->isAlignas()) {
2094 // C++11 [dcl.align]p6:
2095 // if any declaration of an entity has an alignment-specifier,
2096 // every defining declaration of that entity shall specify an
2097 // equivalent alignment.
2098 // C11 6.7.5/7:
2099 // If the definition of an object does not have an alignment
2100 // specifier, any other declaration of that object shall also
2101 // have no alignment specifier.
2102 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002103 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002104 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002105 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002106 NewAttributes.erase(NewAttributes.begin() + I);
2107 --E;
2108 continue;
2109 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002110 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002111
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002112 S.Diag(NewAttribute->getLocation(),
2113 diag::warn_attribute_precede_definition);
2114 S.Diag(Def->getLocation(), diag::note_previous_definition);
2115 NewAttributes.erase(NewAttributes.begin() + I);
2116 --E;
2117 }
2118}
2119
John McCallf79e87d2011-03-02 04:00:57 +00002120/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002121void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002122 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002123 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2124 UsedAttr *NewAttr = OldAttr->clone(Context);
2125 NewAttr->setInherited(true);
2126 New->addAttr(NewAttr);
2127 }
2128
Richard Smithe233fbf2013-01-28 22:42:45 +00002129 if (!Old->hasAttrs() && !New->hasAttrs())
2130 return;
2131
Rafael Espindola36191042012-05-18 01:47:00 +00002132 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002133 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002134
Douglas Gregor32c17572012-01-01 20:30:41 +00002135 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002136 return;
John McCallf79e87d2011-03-02 04:00:57 +00002137
Douglas Gregor32c17572012-01-01 20:30:41 +00002138 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002139
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002140 // Ensure that any moving of objects within the allocated map is done before
2141 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002142 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002143
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002144 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002145 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002146 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002147 if (isa<DeprecatedAttr>(I) ||
2148 isa<UnavailableAttr>(I) ||
2149 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002150 switch (AMK) {
2151 case AMK_None:
2152 continue;
John McCalld2930c22011-07-22 02:45:48 +00002153
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002154 case AMK_Redeclaration:
2155 break;
2156
2157 case AMK_Override:
2158 Override = true;
2159 break;
2160 }
2161 }
2162
Rafael Espindolab0938852013-10-25 01:28:12 +00002163 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002164 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002165 continue;
2166
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002167 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002168 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002169 }
John McCallf79e87d2011-03-02 04:00:57 +00002170
Richard Smithbc8caaf2013-02-22 04:55:39 +00002171 if (mergeAlignedAttrs(*this, New, Old))
2172 foundAny = true;
2173
Douglas Gregor32c17572012-01-01 20:30:41 +00002174 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002175}
2176
2177/// mergeParamDeclAttributes - Copy attributes from the old parameter
2178/// to the new one.
2179static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2180 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002181 Sema &S) {
2182 // C++11 [dcl.attr.depend]p2:
2183 // The first declaration of a function shall specify the
2184 // carries_dependency attribute for its declarator-id if any declaration
2185 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002186 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2187 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2188 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002189 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2190 // Find the first declaration of the parameter.
2191 // FIXME: Should we build redeclaration chains for function parameters?
2192 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002193 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002194 const ParmVarDecl *FirstVD =
2195 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2196 S.Diag(FirstVD->getLocation(),
2197 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2198 }
2199
John McCallf79e87d2011-03-02 04:00:57 +00002200 if (!oldDecl->hasAttrs())
2201 return;
2202
2203 bool foundAny = newDecl->hasAttrs();
2204
2205 // Ensure that any moving of objects within the allocated map is
2206 // done before we process them.
2207 if (!foundAny) newDecl->setAttrs(AttrVec());
2208
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002209 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2210 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002211 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002212 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002213 newAttr->setInherited(true);
2214 newDecl->addAttr(newAttr);
2215 foundAny = true;
2216 }
2217 }
2218
2219 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002220}
2221
Dan Gohman28ade552010-07-26 21:25:24 +00002222namespace {
2223
Douglas Gregora74a2972009-03-06 22:43:54 +00002224/// Used in MergeFunctionDecl to keep track of function parameters in
2225/// C.
2226struct GNUCompatibleParamWarning {
2227 ParmVarDecl *OldParm;
2228 ParmVarDecl *NewParm;
2229 QualType PromotedType;
2230};
2231
Dan Gohman28ade552010-07-26 21:25:24 +00002232}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002233
2234/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002235Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002236 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002237 if (Ctor->isDefaultConstructor())
2238 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002239
2240 if (Ctor->isCopyConstructor())
2241 return Sema::CXXCopyConstructor;
2242
2243 if (Ctor->isMoveConstructor())
2244 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002245 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002246 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002247 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002248 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002249 } else if (MD->isMoveAssignmentOperator()) {
2250 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002251 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002252
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002253 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002254}
2255
Sebastian Redl243d9052010-06-09 21:17:41 +00002256/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002257/// only extern inline functions can be redefined, and even then only in
2258/// GNU89 mode.
2259static bool canRedefineFunction(const FunctionDecl *FD,
2260 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002261 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2262 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002263 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002264 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002265}
2266
Reid Kleckner78af0702013-08-27 23:08:25 +00002267const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2268 const AttributedType *AT = T->getAs<AttributedType>();
2269 while (AT && !AT->isCallingConv())
2270 AT = AT->getModifiedType()->getAs<AttributedType>();
2271 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002272}
2273
Benjamin Kramer3e350262013-02-15 12:30:38 +00002274template <typename T>
2275static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002276 const DeclContext *DC = Old->getDeclContext();
2277 if (DC->isRecord())
2278 return false;
2279
2280 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002281 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002282 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002283 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002284 return true;
2285 return false;
2286}
2287
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002288/// MergeFunctionDecl - We just parsed a function 'New' from
2289/// declarator D which has the same name and scope as a previous
2290/// declaration 'Old'. Figure out how to resolve this situation,
2291/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292///
2293/// In C++, New and Old must be declarations that are not
2294/// overloaded. Use IsOverload to determine whether New and Old are
2295/// overloaded, and to select the Old declaration that New should be
2296/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002297///
2298/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002299bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2300 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002301 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002302 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002303 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002304 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002305 if (New->getFriendObjectKind()) {
2306 Diag(New->getLocation(), diag::err_using_decl_friend);
2307 Diag(Shadow->getTargetDecl()->getLocation(),
2308 diag::note_using_decl_target);
2309 Diag(Shadow->getUsingDecl()->getLocation(),
2310 diag::note_using_decl) << 0;
2311 return true;
2312 }
2313
Richard Smith18819302014-02-06 01:31:33 +00002314 // C++11 [namespace.udecl]p14:
2315 // If a function declaration in namespace scope or block scope has the
2316 // same name and the same parameter-type-list as a function introduced
2317 // by a using-declaration, and the declarations do not declare the same
2318 // function, the program is ill-formed.
2319
2320 // Check whether the two declarations might declare the same function.
2321 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2322 if (Old &&
2323 !Old->getDeclContext()->getRedeclContext()->Equals(
2324 New->getDeclContext()->getRedeclContext()) &&
2325 !(Old->isExternC() && New->isExternC()))
Craig Topperc3ec1492014-05-26 06:22:03 +00002326 Old = nullptr;
Richard Smith18819302014-02-06 01:31:33 +00002327
2328 if (!Old) {
2329 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2330 Diag(Shadow->getTargetDecl()->getLocation(),
2331 diag::note_using_decl_target);
2332 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2333 return true;
2334 }
2335 OldD = Old;
2336 } else {
2337 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2338 << New->getDeclName();
2339 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002340 return true;
2341 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002342 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002343
David Majnemerea5092a2013-07-07 23:49:50 +00002344 // If the old declaration is invalid, just give up here.
2345 if (Old->isInvalidDecl())
2346 return true;
2347
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002348 // Determine whether the previous declaration was a definition,
2349 // implicit declaration, or a declaration.
2350 diag::kind PrevDiag;
Richard Smithbdd14642014-02-04 01:14:30 +00002351 SourceLocation OldLocation = Old->getLocation();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002352 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00002353 PrevDiag = diag::note_previous_definition;
Richard Smithbdd14642014-02-04 01:14:30 +00002354 else if (Old->isImplicit()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002355 PrevDiag = diag::note_previous_implicit_declaration;
Richard Smithbdd14642014-02-04 01:14:30 +00002356 if (OldLocation.isInvalid())
2357 OldLocation = New->getLocation();
2358 } else
Chris Lattner0369c572008-11-23 23:12:31 +00002359 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Charles Davisfea48452010-02-18 02:00:42 +00002361 // Don't complain about this if we're in GNU89 mode and the old function
2362 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002363 // Don't complain about specializations. They are not supposed to have
2364 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002365 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002366 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002367 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002368 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002369 !canRedefineFunction(Old, getLangOpts())) {
2370 if (getLangOpts().MicrosoftExt) {
Francois Pichet6841a122011-04-22 19:50:06 +00002371 Diag(New->getLocation(), diag::warn_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002372 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002373 } else {
2374 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002375 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002376 return true;
2377 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002378 }
2379
Reid Kleckner78af0702013-08-27 23:08:25 +00002380
2381 // If a function is first declared with a calling convention, but is later
2382 // declared or defined without one, all following decls assume the calling
2383 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002384 //
John McCalla5f46fb2012-08-25 02:00:03 +00002385 // It's OK if a function is first declared without a calling convention,
2386 // but is later declared or defined with the default calling convention.
2387 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002388 // To test if either decl has an explicit calling convention, we look for
2389 // AttributedType sugar nodes on the type as written. If they are missing or
2390 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002391 //
2392 // Note also that we DO NOT return at this point, because we still have
2393 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002394 QualType OldQType = Context.getCanonicalType(Old->getType());
2395 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002396 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002397 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002398 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2399 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2400 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002401
Reid Kleckner78af0702013-08-27 23:08:25 +00002402 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002403 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002404 const FunctionType *FT =
2405 First->getType().getCanonicalType()->castAs<FunctionType>();
2406 FunctionType::ExtInfo FI = FT->getExtInfo();
2407 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2408 if (!NewCCExplicit) {
2409 // Inherit the CC from the previous declaration if it was specified
2410 // there but not here.
2411 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2412 RequiresAdjustment = true;
2413 } else {
2414 // Calling conventions aren't compatible, so complain.
2415 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2416 Diag(New->getLocation(), diag::err_cconv_change)
2417 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2418 << !FirstCCExplicit
2419 << (!FirstCCExplicit ? "" :
2420 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002421
Reid Kleckner78af0702013-08-27 23:08:25 +00002422 // Put the note on the first decl, since it is the one that matters.
2423 Diag(First->getLocation(), diag::note_previous_declaration);
2424 return true;
2425 }
John McCallcddbad02010-02-04 05:44:44 +00002426 }
2427
John McCallab26cfa2010-02-05 21:31:56 +00002428 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002429 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2430 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2431 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002432 }
2433
Douglas Gregor77e274f2010-06-18 21:30:25 +00002434 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002435 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2436 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2437 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002438 Diag(New->getLocation(), diag::err_regparm_mismatch)
2439 << NewType->getRegParmType()
2440 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002441 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002442 return true;
2443 }
John McCall4f5019e2010-12-19 02:44:49 +00002444
2445 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2446 RequiresAdjustment = true;
2447 }
2448
Douglas Gregorf1404d72011-10-14 15:55:40 +00002449 // Merge ns_returns_retained attribute.
2450 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2451 if (NewTypeInfo.getProducesResult()) {
2452 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002453 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002454 return true;
2455 }
2456
2457 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2458 RequiresAdjustment = true;
2459 }
2460
John McCall4f5019e2010-12-19 02:44:49 +00002461 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002462 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2463 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2464 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002465 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002466 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002467 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002468
2469 // If this redeclaration makes the function inline, we may need to add it to
2470 // UndefinedButUsed.
2471 if (!Old->isInlined() && New->isInlined() &&
2472 !New->hasAttr<GNUInlineAttr>() &&
2473 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2474 Old->isUsed(false) &&
2475 !Old->isDefined() && !New->isThisDeclarationADefinition())
2476 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2477 SourceLocation()));
2478
2479 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2480 // about it.
2481 if (New->hasAttr<GNUInlineAttr>() &&
2482 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2483 UndefinedButUsed.erase(Old->getCanonicalDecl());
2484 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002485
David Blaikiebbafb8a2012-03-11 07:00:24 +00002486 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002487 // (C++98 13.1p2):
2488 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002489 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002490 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002491
2492 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002493 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002494 // Redeclarations or specializations of a function or function template
2495 // with a declared return type that uses a placeholder type shall also
2496 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002497 QualType OldDeclaredReturnType =
2498 (Old->getTypeSourceInfo()
2499 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2500 : OldType)->getReturnType();
2501 QualType NewDeclaredReturnType =
2502 (New->getTypeSourceInfo()
2503 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2504 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002505 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002506 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2507 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2508 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002509 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2510 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002511 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2512 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002513 if (New->isCXXClassMember() && New->isOutOfLine())
2514 Diag(New->getLocation(),
2515 diag::err_member_def_does_not_match_ret_type) << New;
2516 else
2517 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Richard Smithbdd14642014-02-04 01:14:30 +00002518 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002519 return true;
2520 }
2521 else
2522 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002523 }
2524
Alp Toker314cc812014-01-25 16:55:45 +00002525 QualType OldReturnType = OldType->getReturnType();
2526 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002527 if (OldReturnType != NewReturnType) {
2528 // If this function has a deduced return type and has already been
2529 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002530 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002531 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002532 New->setType(
2533 SubstAutoType(New->getType(),
2534 OldAT->isDependentType() ? Context.DependentTy
2535 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002536 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002537 SubstAutoType(NewQType,
2538 OldAT->isDependentType() ? Context.DependentTy
2539 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002540 }
2541 }
2542
2543 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2544 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002545 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002546 // Preserve triviality.
2547 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002548
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002549 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002550 // 2 CXXMethodDecls referring to the same function will be injected.
2551 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002552 bool IsClassScopeExplicitSpecialization =
2553 OldMethod->isFunctionTemplateSpecialization() &&
2554 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002555 bool isFriend = NewMethod->getFriendObjectKind();
2556
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002557 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2558 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002559 // -- Member function declarations with the same name and the
2560 // same parameter types cannot be overloaded if any of them
2561 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002562 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002563 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002564 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002565 return true;
2566 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002567
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002568 // C++ [class.mem]p1:
2569 // [...] A member shall not be declared twice in the
2570 // member-specification, except that a nested class or member
2571 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002572 if (ActiveTemplateInstantiations.empty()) {
2573 unsigned NewDiag;
2574 if (isa<CXXConstructorDecl>(OldMethod))
2575 NewDiag = diag::err_constructor_redeclared;
2576 else if (isa<CXXDestructorDecl>(NewMethod))
2577 NewDiag = diag::err_destructor_redeclared;
2578 else if (isa<CXXConversionDecl>(NewMethod))
2579 NewDiag = diag::err_conv_function_redeclared;
2580 else
2581 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002582
Richard Smith57e7ff92012-07-13 04:12:04 +00002583 Diag(New->getLocation(), NewDiag);
2584 } else {
2585 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2586 << New << New->getType();
2587 }
Richard Smithbdd14642014-02-04 01:14:30 +00002588 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002589
2590 // Complain if this is an explicit declaration of a special
2591 // member that was initially declared implicitly.
2592 //
2593 // As an exception, it's okay to befriend such methods in order
2594 // to permit the implicit constructor/destructor/operator calls.
2595 } else if (OldMethod->isImplicit()) {
2596 if (isFriend) {
2597 NewMethod->setImplicit();
2598 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002599 Diag(NewMethod->getLocation(),
2600 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002601 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002602 return true;
2603 }
Richard Smith337a5a12012-06-08 01:30:54 +00002604 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002605 Diag(NewMethod->getLocation(),
2606 diag::err_definition_of_explicitly_defaulted_member)
2607 << getSpecialMember(OldMethod);
2608 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002609 }
2610 }
2611
Richard Smith10876ef2013-01-17 01:30:42 +00002612 // C++11 [dcl.attr.noreturn]p1:
2613 // The first declaration of a function shall specify the noreturn
2614 // attribute if any declaration of that function specifies the noreturn
2615 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002616 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2617 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2618 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002619 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002620 diag::note_noreturn_missing_first_decl);
2621 }
2622
Richard Smithe233fbf2013-01-28 22:42:45 +00002623 // C++11 [dcl.attr.depend]p2:
2624 // The first declaration of a function shall specify the
2625 // carries_dependency attribute for its declarator-id if any declaration
2626 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002627 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2628 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2629 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002630 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002631 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002632 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2633 }
2634
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002635 // (C++98 8.3.5p3):
2636 // All declarations for a function shall agree exactly in both the
2637 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002638 // We also want to respect all the extended bits except noreturn.
2639
2640 // noreturn should now match unless the old type info didn't have it.
2641 QualType OldQTypeForComparison = OldQType;
2642 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2643 assert(OldQType == QualType(OldType, 0));
2644 const FunctionType *OldTypeForComparison
2645 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2646 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2647 assert(OldQTypeForComparison.isCanonical());
2648 }
2649
Rafael Espindolaf4187652013-02-14 01:18:37 +00002650 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002651 // As a special case, retain the language linkage from previous
2652 // declarations of a friend function as an extension.
2653 //
2654 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2655 // and is useful because there's otherwise no way to specify language
2656 // linkage within class scope.
2657 //
2658 // Check cautiously as the friend object kind isn't yet complete.
2659 if (New->getFriendObjectKind() != Decl::FOK_None) {
2660 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002661 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002662 } else {
2663 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002664 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002665 return true;
2666 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002667 }
2668
John McCall4f5019e2010-12-19 02:44:49 +00002669 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002670 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002671
Richard Smith541b38b2013-09-20 01:15:31 +00002672 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2673 New->isLocalExternDecl()) {
2674 // It's OK if we couldn't merge types for a local function declaraton
2675 // if either the old or new type is dependent. We'll merge the types
2676 // when we instantiate the function.
2677 return false;
2678 }
2679
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002680 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002681 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002682
2683 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002684 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002685 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002686 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002687 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2688 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00002689 const FunctionProtoType *OldProto = nullptr;
Richard Smith1c34fb72013-08-13 18:18:50 +00002690 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002691 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002692 // The old declaration provided a function prototype, but the
2693 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002694 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002695 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
Alp Toker314cc812014-01-25 16:55:45 +00002696 NewQType =
2697 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2698 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002699 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002700 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002701
Alp Toker4284c6e2014-05-11 16:05:55 +00002702 // Synthesize parameters with the same types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002703 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002704 for (const auto &ParamType : OldProto->param_types()) {
2705 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002706 SourceLocation(), nullptr,
2707 ParamType, /*TInfo=*/nullptr,
2708 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00002709 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002710 Param->setImplicit();
2711 Params.push_back(Param);
2712 }
2713
David Blaikie9c70e042011-09-21 18:16:56 +00002714 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002715 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002716
Richard Smith1c34fb72013-08-13 18:18:50 +00002717 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002718 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002719
Douglas Gregora74a2972009-03-06 22:43:54 +00002720 // GNU C permits a K&R definition to follow a prototype declaration
2721 // if the declared types of the parameters in the K&R definition
2722 // match the types in the prototype declaration, even when the
2723 // promoted types of the parameters from the K&R definition differ
2724 // from the types in the prototype. GCC then keeps the types from
2725 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002726 //
2727 // If a variadic prototype is followed by a non-variadic K&R definition,
2728 // the K&R definition becomes variadic. This is sort of an edge case, but
2729 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2730 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002731 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002732 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002733 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002734 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002735 SmallVector<QualType, 16> ArgTypes;
2736 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002737 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002738 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002739 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002740 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002743 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2744 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002745 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002746 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002747 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002748 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2749 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002750 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002751 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002752 ArgTypes.push_back(NewParm->getType());
2753 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002754 NewParm->getType(),
2755 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002756 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2757 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002758 Warnings.push_back(Warn);
2759 ArgTypes.push_back(NewParm->getType());
2760 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002761 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002762 }
2763
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002764 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002765 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2766 Diag(Warnings[Warn].NewParm->getLocation(),
2767 diag::ext_param_promoted_not_compatible_with_prototype)
2768 << Warnings[Warn].PromotedType
2769 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002770 if (Warnings[Warn].OldParm->getLocation().isValid())
2771 Diag(Warnings[Warn].OldParm->getLocation(),
2772 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002773 }
2774
Richard Smith1c34fb72013-08-13 18:18:50 +00002775 if (MergeTypeWithOld)
2776 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2777 OldProto->getExtProtoInfo()));
2778 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002779 }
2780
2781 // Fall through to diagnose conflicting types.
2782 }
2783
John McCallad327cd2013-04-14 08:50:55 +00002784 // A function that has already been declared has been redeclared or
2785 // defined with a different type; show an appropriate diagnostic.
2786
2787 // If the previous declaration was an implicitly-generated builtin
2788 // declaration, then at the very least we should use a specialized note.
2789 unsigned BuiltinID;
2790 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2791 // If it's actually a library-defined builtin function like 'malloc'
2792 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002793 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002794 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002795 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002796 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002797
2798 // If this is a global redeclaration, just forget hereafter
2799 // about the "builtin-ness" of the function.
2800 //
2801 // Doing this for local extern declarations is problematic. If
2802 // the builtin declaration remains visible, a second invalid
2803 // local declaration will produce a hard error; if it doesn't
2804 // remain visible, a single bogus local redeclaration (which is
2805 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002806 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002807 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2808
Douglas Gregor893c2c92009-03-23 17:47:24 +00002809 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002810 }
Steve Naroff17832a42008-01-16 15:01:34 +00002811
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002812 PrevDiag = diag::note_previous_builtin_declaration;
2813 }
2814
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002815 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002816 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002817 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002818}
2819
Douglas Gregore62c0a42009-02-24 01:23:02 +00002820/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002821/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002822///
2823/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002824/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002825/// the new declaration, once we know that New is in fact a
2826/// redeclaration of Old.
2827///
2828/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002829bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002830 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002831 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002832 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002833
Douglas Gregore62c0a42009-02-24 01:23:02 +00002834 // Merge "pure" flag.
2835 if (Old->isPure())
2836 New->setPure();
2837
Rafael Espindolabefe1302012-11-25 14:07:59 +00002838 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002839 if (Old->getMostRecentDecl()->isUsed(false))
2840 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002841
John McCallf79e87d2011-03-02 04:00:57 +00002842 // Merge attributes from the parameters. These can mismatch with K&R
2843 // declarations.
2844 if (New->getNumParams() == Old->getNumParams())
2845 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2846 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002847 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002848
David Blaikiebbafb8a2012-03-11 07:00:24 +00002849 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002850 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002851
Rafael Espindola8778c282012-11-29 16:09:03 +00002852 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002853 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2854 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002855 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002856 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002857 New->setType(Merged);
2858
Douglas Gregore62c0a42009-02-24 01:23:02 +00002859 return false;
2860}
2861
John McCall31168b02011-06-15 23:02:42 +00002862
John McCallf79e87d2011-03-02 04:00:57 +00002863void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002864 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002865
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002866 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002867 AvailabilityMergeKind MergeKind =
2868 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2869 : AMK_Override;
2870 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002871
2872 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002873 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2874 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002875 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002876 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002877 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002878 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002879
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002880 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002881}
2882
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002883/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2884/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002885/// emitting diagnostics as appropriate.
2886///
2887/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002888/// to here in AddInitializerToDecl. We can't check them before the initializer
2889/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002890void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2891 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002892 if (New->isInvalidDecl() || Old->isInvalidDecl())
2893 return;
2894
2895 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002896 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002897 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002898 // We don't know what the new type is until the initializer is attached.
2899 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002900 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2901 // These could still be something that needs exception specs checked.
2902 return MergeVarDeclExceptionSpecs(New, Old);
2903 }
Richard Smith30482bc2011-02-20 03:19:35 +00002904 // C++ [basic.link]p10:
2905 // [...] the types specified by all declarations referring to a given
2906 // object or function shall be identical, except that declarations for an
2907 // array object can specify array types that differ by the presence or
2908 // absence of a major array bound (8.3.4).
2909 else if (Old->getType()->isIncompleteArrayType() &&
2910 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002911 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2912 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2913 if (Context.hasSameType(OldArray->getElementType(),
2914 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002915 MergedT = New->getType();
2916 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002917 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002918 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2919 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2920 if (Context.hasSameType(OldArray->getElementType(),
2921 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002922 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002923 } else if (New->getType()->isObjCObjectPointerType() &&
2924 Old->getType()->isObjCObjectPointerType()) {
2925 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2926 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002927 }
2928 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002929 // C 6.2.7p2:
2930 // All declarations that refer to the same object or function shall have
2931 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002932 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2933 }
2934 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002935 // It's OK if we couldn't merge types if either type is dependent, for a
2936 // block-scope variable. In other cases (static data members of class
2937 // templates, variable templates, ...), we require the types to be
2938 // equivalent.
2939 // FIXME: The C++ standard doesn't say anything about this.
2940 if ((New->getType()->isDependentType() ||
2941 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2942 // If the old type was dependent, we can't merge with it, so the new type
2943 // becomes dependent for now. We'll reproduce the original type when we
2944 // instantiate the TypeSourceInfo for the variable.
2945 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2946 New->setType(Context.DependentTy);
2947 return;
2948 }
2949
2950 // FIXME: Even if this merging succeeds, some other non-visible declaration
2951 // of this variable might have an incompatible type. For instance:
2952 //
2953 // extern int arr[];
2954 // void f() { extern int arr[2]; }
2955 // void g() { extern int arr[3]; }
2956 //
2957 // Neither C nor C++ requires a diagnostic for this, but we should still try
2958 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002959 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002960 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002961 Diag(Old->getLocation(), diag::note_previous_definition);
2962 return New->setInvalidDecl();
2963 }
John McCallb65e8fe2013-04-01 18:34:28 +00002964
2965 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002966 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002967 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002968 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002969}
2970
Richard Smith3c785782013-09-03 21:00:58 +00002971static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2972 LookupResult &Previous) {
2973 // C11 6.2.7p4:
2974 // For an identifier with internal or external linkage declared
2975 // in a scope in which a prior declaration of that identifier is
2976 // visible, if the prior declaration specifies internal or
2977 // external linkage, the type of the identifier at the later
2978 // declaration becomes the composite type.
2979 //
2980 // If the variable isn't visible, we do not merge with its type.
2981 if (Previous.isShadowed())
2982 return false;
2983
2984 if (S.getLangOpts().CPlusPlus) {
2985 // C++11 [dcl.array]p3:
2986 // If there is a preceding declaration of the entity in the same
2987 // scope in which the bound was specified, an omitted array bound
2988 // is taken to be the same as in that earlier declaration.
2989 return NewVD->isPreviousDeclInSameBlockScope() ||
2990 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2991 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2992 } else {
2993 // If the old declaration was function-local, don't merge with its
2994 // type unless we're in the same function.
2995 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2996 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2997 }
2998}
2999
Chris Lattner01564d92007-01-27 19:27:06 +00003000/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3001/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3002/// situation, merging decls or emitting diagnostics as appropriate.
3003///
Mike Stump11289f42009-09-09 15:08:12 +00003004/// Tentative definition rules (C99 6.9.2p2) are checked by
3005/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00003006/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00003007///
Richard Smith3c785782013-09-03 21:00:58 +00003008void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00003009 // If the new decl is already invalid, don't do any other checking.
3010 if (New->isInvalidDecl())
3011 return;
Mike Stump11289f42009-09-09 15:08:12 +00003012
Richard Smithbeef3452014-01-16 23:39:20 +00003013 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3014
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003015 // Verify the old decl was also a variable or variable template.
Craig Topperc3ec1492014-05-26 06:22:03 +00003016 VarDecl *Old = nullptr;
3017 VarTemplateDecl *OldTemplate = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003018 if (Previous.isSingleResult()) {
3019 if (NewTemplate) {
3020 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003021 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003022 } else
3023 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003024 }
3025 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003026 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003027 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003028 Diag(Previous.getRepresentativeDecl()->getLocation(),
3029 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003030 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003031 }
Chris Lattner84966392008-03-03 03:28:21 +00003032
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003033 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3034 return;
3035
Richard Smithbeef3452014-01-16 23:39:20 +00003036 // Ensure the template parameters are compatible.
3037 if (NewTemplate &&
3038 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3039 OldTemplate->getTemplateParameters(),
3040 /*Complain=*/true, TPL_TemplateMatch))
3041 return;
3042
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003043 // C++ [class.mem]p1:
3044 // A member shall not be declared twice in the member-specification [...]
3045 //
3046 // Here, we need only consider static data members.
3047 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3048 Diag(New->getLocation(), diag::err_duplicate_member)
3049 << New->getIdentifier();
3050 Diag(Old->getLocation(), diag::note_previous_declaration);
3051 New->setInvalidDecl();
3052 }
3053
Douglas Gregor32c17572012-01-01 20:30:41 +00003054 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003055 // Warn if an already-declared variable is made a weak_import in a subsequent
3056 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003057 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003058 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003059 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003060 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3061 Diag(Old->getLocation(), diag::note_previous_definition);
3062 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003063 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003064 }
Chris Lattner84966392008-03-03 03:28:21 +00003065
Richard Smith30482bc2011-02-20 03:19:35 +00003066 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003067 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3068
Richard Smith30482bc2011-02-20 03:19:35 +00003069 if (New->isInvalidDecl())
3070 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003071
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003072 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003073 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003074 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003075 Old->hasExternalFormalLinkage()) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003076 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003077 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003078 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003079 }
Mike Stump11289f42009-09-09 15:08:12 +00003080 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003081 // For an identifier declared with the storage-class specifier
3082 // extern in a scope in which a prior declaration of that
3083 // identifier is visible,23) if the prior declaration specifies
3084 // internal or external linkage, the linkage of the identifier at
3085 // the later declaration is the same as the linkage specified at
3086 // the prior declaration. If no prior declaration is visible, or
3087 // if the prior declaration specifies no linkage, then the
3088 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003089 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003090 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003091 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003092 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003093 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003094 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003095 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003096 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003097 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003098
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003099 // Check if extern is followed by non-extern and vice-versa.
3100 if (New->hasExternalStorage() &&
3101 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3102 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3103 Diag(Old->getLocation(), diag::note_previous_definition);
3104 return New->setInvalidDecl();
3105 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003106 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3107 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003108 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3109 Diag(Old->getLocation(), diag::note_previous_definition);
3110 return New->setInvalidDecl();
3111 }
3112
Steve Naroffa5629372008-09-17 14:05:40 +00003113 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003114
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003115 // FIXME: The test for external storage here seems wrong? We still
3116 // need to check for mismatches.
3117 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003118 // Don't complain about out-of-line definitions of static members.
3119 !(Old->getLexicalDeclContext()->isRecord() &&
3120 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003121 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003122 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003123 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003124 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003125
Richard Smithfd3834f2013-04-13 02:43:54 +00003126 if (New->getTLSKind() != Old->getTLSKind()) {
3127 if (!Old->getTLSKind()) {
3128 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3129 Diag(Old->getLocation(), diag::note_previous_declaration);
3130 } else if (!New->getTLSKind()) {
3131 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3132 Diag(Old->getLocation(), diag::note_previous_declaration);
3133 } else {
3134 // Do not allow redeclaration to change the variable between requiring
3135 // static and dynamic initialization.
3136 // FIXME: GCC allows this, but uses the TLS keyword on the first
3137 // declaration to determine the kind. Do we need to be compatible here?
3138 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3139 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3140 Diag(Old->getLocation(), diag::note_previous_declaration);
3141 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003142 }
3143
Sebastian Redlf1842912010-02-02 18:35:11 +00003144 // C++ doesn't have tentative definitions, so go right ahead and check here.
3145 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003146 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003147 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003148 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003149 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003150 Diag(Def->getLocation(), diag::note_previous_definition);
3151 New->setInvalidDecl();
3152 return;
3153 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003154
Rafael Espindolaf4187652013-02-14 01:18:37 +00003155 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003156 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3157 Diag(Old->getLocation(), diag::note_previous_definition);
3158 New->setInvalidDecl();
3159 return;
3160 }
3161
Rafael Espindolabefe1302012-11-25 14:07:59 +00003162 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003163 if (Old->getMostRecentDecl()->isUsed(false))
3164 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003165
Douglas Gregor0760fa12009-03-10 23:43:53 +00003166 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003167 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003168 if (NewTemplate)
3169 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003170
3171 // Inherit access appropriately.
3172 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003173 if (NewTemplate)
3174 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003175}
3176
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003177/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3178/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003179Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003180 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003181 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003182}
3183
David Majnemer2206bf52014-03-05 08:57:59 +00003184static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003185 if (!S.Context.getLangOpts().CPlusPlus)
3186 return;
3187
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003188 if (isa<CXXRecordDecl>(Tag->getParent())) {
3189 // If this tag is the direct child of a class, number it if
3190 // it is anonymous.
3191 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3192 return;
3193 MangleNumberingContext &MCtx =
3194 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003195 S.Context.setManglingNumber(
3196 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003197 return;
3198 }
3199
3200 // If this tag isn't a direct child of a class, number it if it is local.
3201 Decl *ManglingContextDecl;
3202 if (MangleNumberingContext *MCtx =
3203 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3204 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003205 S.Context.setManglingNumber(
3206 Tag,
3207 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003208 }
3209}
3210
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003211/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003212/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003213/// parameters to cope with template friend declarations.
3214Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3215 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003216 MultiTemplateParamsArg TemplateParams,
3217 bool IsExplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 Decl *TagD = nullptr;
3219 TagDecl *Tag = nullptr;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003220 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3221 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003222 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003223 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003224 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003225 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003226
3227 if (!TagD) // We probably had an error
Craig Topperc3ec1492014-05-26 06:22:03 +00003228 return nullptr;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003229
John McCall07e91c02009-08-06 02:15:43 +00003230 // Note that the above type specs guarantee that the
3231 // type rep is a Decl, whereas in many of the others
3232 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003233 if (isa<TagDecl>(TagD))
3234 Tag = cast<TagDecl>(TagD);
3235 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3236 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003237 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003238
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003239 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003240 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003241 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003242 if (Tag->isInvalidDecl())
3243 return Tag;
3244 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003245
Nuno Lopese9823fa2009-12-17 11:35:26 +00003246 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3247 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3248 // or incomplete types shall not be restrict-qualified."
3249 if (TypeQuals & DeclSpec::TQ_restrict)
3250 Diag(DS.getRestrictSpecLoc(),
3251 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3252 << DS.getSourceRange();
3253 }
3254
Richard Smitha77a0a62011-08-15 21:04:07 +00003255 if (DS.isConstexprSpecified()) {
3256 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3257 // and definitions of functions and variables.
3258 if (Tag)
3259 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3260 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3261 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003262 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3263 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003264 else
3265 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3266 // Don't emit warnings after this error.
3267 return TagD;
3268 }
3269
Richard Smithb1402ae2013-03-18 22:52:47 +00003270 DiagnoseFunctionSpecifiers(DS);
3271
Douglas Gregor3dad8422009-09-26 06:47:28 +00003272 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003273 // If we're dealing with a decl but not a TagDecl, assume that
3274 // whatever routines created it handled the friendship aspect.
3275 if (TagD && !Tag)
Craig Topperc3ec1492014-05-26 06:22:03 +00003276 return nullptr;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003277 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003278 }
John McCallaa017372011-03-22 23:00:04 +00003279
Richard Smithb1402ae2013-03-18 22:52:47 +00003280 CXXScopeSpec &SS = DS.getTypeSpecScope();
3281 bool IsExplicitSpecialization =
3282 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3283 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3284 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3285 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3286 // nested-name-specifier unless it is an explicit instantiation
3287 // or an explicit specialization.
3288 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3289 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3290 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3291 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3292 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3293 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3294 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 return nullptr;
Richard Smithb1402ae2013-03-18 22:52:47 +00003296 }
3297
3298 // Track whether this decl-specifier declares anything.
3299 bool DeclaresAnything = true;
3300
3301 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003302 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003303 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003304 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003305 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003306 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003307 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003308
Richard Smithb1402ae2013-03-18 22:52:47 +00003309 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003310 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003311 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003312
Richard Smithb1402ae2013-03-18 22:52:47 +00003313 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003314 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003315 CurContext->isRecord() &&
3316 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3317 // Handle 2 kinds of anonymous struct:
3318 // struct STRUCT;
3319 // and
3320 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3321 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003322 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003323 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3324 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003325 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003326 << DS.getSourceRange();
3327 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3328 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003329 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003330
3331 // Skip all the checks below if we have a type error.
3332 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3333 (TagD && TagD->isInvalidDecl()))
3334 return TagD;
3335
3336 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003337 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3338 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3339 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003340 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3341 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003342
John McCallaa017372011-03-22 23:00:04 +00003343 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003344 // Customize diagnostic for a typedef missing a name.
3345 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003346 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003347 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003348 else
3349 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003350 }
Mike Stump11289f42009-09-09 15:08:12 +00003351
Richard Smithb1402ae2013-03-18 22:52:47 +00003352 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003353 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3354 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3355 << Tag->getTagKind()
3356 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3357
Richard Smithb1402ae2013-03-18 22:52:47 +00003358 ActOnDocumentableDecl(TagD);
3359
3360 // C 6.7/2:
3361 // A declaration [...] shall declare at least a declarator [...], a tag,
3362 // or the members of an enumeration.
3363 // C++ [dcl.dcl]p3:
3364 // [If there are no declarators], and except for the declaration of an
3365 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3366 // names into the program, or shall redeclare a name introduced by a
3367 // previous declaration.
3368 if (!DeclaresAnything) {
3369 // In C, we allow this as a (popular) extension / bug. Don't bother
3370 // producing further diagnostics for redundant qualifiers after this.
3371 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3372 return TagD;
3373 }
3374
3375 // C++ [dcl.stc]p1:
3376 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3377 // init-declarator-list of the declaration shall not be empty.
3378 // C++ [dcl.fct.spec]p1:
3379 // If a cv-qualifier appears in a decl-specifier-seq, the
3380 // init-declarator-list of the declaration shall not be empty.
3381 //
3382 // Spurious qualifiers here appear to be valid in C.
3383 unsigned DiagID = diag::warn_standalone_specifier;
3384 if (getLangOpts().CPlusPlus)
3385 DiagID = diag::ext_standalone_specifier;
3386
3387 // Note that a linkage-specification sets a storage class, but
3388 // 'extern "C" struct foo;' is actually valid and not theoretically
3389 // useless.
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003390 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3391 if (SCS == DeclSpec::SCS_mutable)
3392 // Since mutable is not a viable storage class specifier in C, there is
3393 // no reason to treat it as an extension. Instead, diagnose as an error.
3394 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3395 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
Richard Smithb1402ae2013-03-18 22:52:47 +00003396 Diag(DS.getStorageClassSpecLoc(), DiagID)
3397 << DeclSpec::getSpecifierName(SCS);
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003398 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003399
Richard Smithb4a9e862013-04-12 22:46:28 +00003400 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3401 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3402 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003403 if (DS.getTypeQualifiers()) {
3404 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3405 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3406 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3407 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3408 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003409 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3410 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003411 }
3412
Eli Friedmane3217952011-12-17 00:36:09 +00003413 // Warn about ignored type attributes, for example:
3414 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003415 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003416 if (!DS.getAttributes().empty()) {
3417 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3418 if (TypeSpecType == DeclSpec::TST_class ||
3419 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003420 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003421 TypeSpecType == DeclSpec::TST_union ||
3422 TypeSpecType == DeclSpec::TST_enum) {
3423 AttributeList* attrs = DS.getAttributes().getList();
3424 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003425 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003426 << attrs->getName()
3427 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3428 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003429 TypeSpecType == DeclSpec::TST_union ? 2 :
3430 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003431 attrs = attrs->getNext();
3432 }
3433 }
3434 }
John McCallaa017372011-03-22 23:00:04 +00003435
John McCall48871652010-08-21 09:40:31 +00003436 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003437}
3438
John McCallea305ed2009-12-18 10:40:03 +00003439/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003440/// check if there's an existing declaration that can't be overloaded.
3441///
3442/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003443static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3444 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003445 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003446 DeclarationName Name,
3447 SourceLocation NameLoc,
3448 unsigned diagnostic) {
3449 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3450 Sema::ForRedeclaration);
3451 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003452
John McCallea305ed2009-12-18 10:40:03 +00003453 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003454 return false;
3455
3456 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003457 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003458 assert(PrevDecl && "Expected a non-null Decl");
3459
3460 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3461 return false;
John McCall1f82f242009-11-18 22:49:29 +00003462
John McCallea305ed2009-12-18 10:40:03 +00003463 SemaRef.Diag(NameLoc, diagnostic) << Name;
3464 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003465
3466 return true;
3467}
3468
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003469/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3470/// anonymous struct or union AnonRecord into the owning context Owner
3471/// and scope S. This routine will be invoked just after we realize
3472/// that an unnamed union or struct is actually an anonymous union or
3473/// struct, e.g.,
3474///
3475/// @code
3476/// union {
3477/// int i;
3478/// float f;
3479/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3480/// // f into the surrounding scope.x
3481/// @endcode
3482///
3483/// This routine is recursive, injecting the names of nested anonymous
3484/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003485static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003486 DeclContext *Owner,
3487 RecordDecl *AnonRecord,
3488 AccessSpecifier AS,
3489 SmallVectorImpl<NamedDecl *> &Chaining,
3490 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003491 unsigned diagKind
3492 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3493 : diag::err_anonymous_struct_member_redecl;
3494
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003495 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003496
3497 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003498 for (auto *D : AnonRecord->decls()) {
3499 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3500 cast<NamedDecl>(D)->getDeclName()) {
3501 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003502 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3503 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003504 // C++ [class.union]p2:
3505 // The names of the members of an anonymous union shall be
3506 // distinct from the names of any other entity in the
3507 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003508 Invalid = true;
3509 } else {
3510 // C++ [class.union]p2:
3511 // For the purpose of name lookup, after the anonymous union
3512 // definition, the members of the anonymous union are
3513 // considered to have been defined in the scope in which the
3514 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003515 unsigned OldChainingSize = Chaining.size();
3516 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003517 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003518 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003519 else
3520 Chaining.push_back(VD);
3521
Francois Pichet783dd6e2010-11-21 06:08:52 +00003522 assert(Chaining.size() >= 2);
3523 NamedDecl **NamedChain =
3524 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3525 for (unsigned i = 0; i < Chaining.size(); i++)
3526 NamedChain[i] = Chaining[i];
3527
3528 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003529 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3530 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003531 NamedChain, Chaining.size());
3532
3533 IndirectField->setAccess(AS);
3534 IndirectField->setImplicit();
3535 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003536
3537 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003538 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003539
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003540 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003541 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003542 }
3543 }
3544
3545 return Invalid;
3546}
3547
Douglas Gregorc4df4072010-04-19 22:54:31 +00003548/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3549/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003550/// illegal input values are mapped to SC_None.
3551static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003552StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3553 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3554 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3555 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003556 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003557 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003558 case DeclSpec::SCS_extern:
3559 if (DS.isExternInLinkageSpec())
3560 return SC_None;
3561 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003562 case DeclSpec::SCS_static: return SC_Static;
3563 case DeclSpec::SCS_auto: return SC_Auto;
3564 case DeclSpec::SCS_register: return SC_Register;
3565 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003566 // Illegal SCSs map to None: error reporting is up to the caller.
3567 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003568 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003569 }
3570 llvm_unreachable("unknown storage class specifier");
3571}
3572
Richard Smithab44d5b2013-12-10 08:25:00 +00003573static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3574 assert(Record->hasInClassInitializer());
3575
Aaron Ballman629afae2014-03-07 19:56:05 +00003576 for (const auto *I : Record->decls()) {
3577 const auto *FD = dyn_cast<FieldDecl>(I);
3578 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003579 FD = IFD->getAnonField();
3580 if (FD && FD->hasInClassInitializer())
3581 return FD->getLocation();
3582 }
3583
3584 llvm_unreachable("couldn't find in-class initializer");
3585}
3586
3587static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3588 SourceLocation DefaultInitLoc) {
3589 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3590 return;
3591
3592 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3593 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3594}
3595
3596static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3597 CXXRecordDecl *AnonUnion) {
3598 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3599 return;
3600
3601 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3602}
3603
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003604/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003605/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003606/// (C++ [class.union]) and a C11 feature; anonymous structures
3607/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003608Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003609 AccessSpecifier AS,
3610 RecordDecl *Record,
3611 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003612 DeclContext *Owner = Record->getDeclContext();
3613
3614 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003615 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003616 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003617 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003618 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003619 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003620 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003621
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003622 // C and C++ require different kinds of checks for anonymous
3623 // structs/unions.
3624 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003625 if (getLangOpts().CPlusPlus) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003626 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003627 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003628 if (Record->isUnion()) {
3629 // C++ [class.union]p6:
3630 // Anonymous unions declared in a named namespace or in the
3631 // global namespace shall be declared static.
3632 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3633 (isa<TranslationUnitDecl>(Owner) ||
3634 (isa<NamespaceDecl>(Owner) &&
3635 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003636 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3637 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003638
3639 // Recover by adding 'static'.
3640 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003641 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003642 }
3643 // C++ [class.union]p6:
3644 // A storage class is not allowed in a declaration of an
3645 // anonymous union in a class scope.
3646 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3647 isa<RecordDecl>(Owner)) {
3648 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003649 diag::err_anonymous_union_with_storage_spec)
3650 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003651
3652 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003653 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3654 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003655 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003656 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003657 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003658
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003659 // Ignore const/volatile/restrict qualifiers.
3660 if (DS.getTypeQualifiers()) {
3661 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3662 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003663 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003664 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3665 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003666 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003667 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003668 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003669 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3670 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003671 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003672 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003673 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003674 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003675 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3676 Diag(DS.getAtomicSpecLoc(),
3677 diag::ext_anonymous_struct_union_qualified)
3678 << Record->isUnion() << "_Atomic"
3679 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003680
3681 DS.ClearTypeQualifiers();
3682 }
3683
Mike Stump11289f42009-09-09 15:08:12 +00003684 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003685 // The member-specification of an anonymous union shall only
3686 // define non-static data members. [Note: nested types and
3687 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003688 for (auto *Mem : Record->decls()) {
3689 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003690 // C++ [class.union]p3:
3691 // An anonymous union shall not have private or protected
3692 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003693 assert(FD->getAccess() != AS_none);
3694 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003695 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3696 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3697 Invalid = true;
3698 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003699
Alexis Hunt97ab5542011-05-16 22:41:40 +00003700 // C++ [class.union]p1
3701 // An object of a class with a non-trivial constructor, a non-trivial
3702 // copy constructor, a non-trivial destructor, or a non-trivial copy
3703 // assignment operator cannot be a member of a union, nor can an
3704 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003705 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003706 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003707 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003708 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003709 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003710 // This is a type that showed up in an
3711 // elaborated-type-specifier inside the anonymous struct or
3712 // union, but which actually declares a type outside of the
3713 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003714 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003715 if (!MemRecord->isAnonymousStructOrUnion() &&
3716 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003717 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003718 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003719 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3720 << (int)Record->isUnion();
3721 else {
3722 // This is a nested type declaration.
3723 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3724 << (int)Record->isUnion();
3725 Invalid = true;
3726 }
Richard Smith254d2662013-01-28 00:54:05 +00003727 } else {
3728 // This is an anonymous type definition within another anonymous type.
3729 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3730 // not part of standard C++.
3731 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003732 diag::ext_anonymous_record_with_anonymous_type)
3733 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003734 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003735 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003736 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003737 } else {
3738 // We have something that isn't a non-static data
3739 // member. Complain about it.
3740 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003741 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003742 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003743 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003744 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003745 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003746 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003747
3748 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003749 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003750 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003751 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003752 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003753 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003754 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003755 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003756 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003757 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003758 }
3759 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003760
3761 // C++11 [class.union]p8 (DR1460):
3762 // At most one variant member of a union may have a
3763 // brace-or-equal-initializer.
3764 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3765 Owner->isRecord())
3766 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3767 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003768 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003769
3770 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003771 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003772 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003773 Invalid = true;
3774 }
3775
John McCallfa2d6922009-10-22 23:31:08 +00003776 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003777 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003778 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003779 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003780
Mike Stump11289f42009-09-09 15:08:12 +00003781 // Create a declaration for this anonymous struct/union.
Craig Topperc3ec1492014-05-26 06:22:03 +00003782 NamedDecl *Anon = nullptr;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003783 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003784 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003785 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003786 Record->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003787 /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003788 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003789 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00003790 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003791 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003792 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003793 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003794 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003795 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003796 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003797 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003798 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003799 // mutable can only appear on non-static class members, so it's always
3800 // an error here
3801 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3802 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003803 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003804 }
3805
Abramo Bagnaradff19302011-03-08 08:55:46 +00003806 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003807 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003808 Record->getLocation(), /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003809 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003810 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003811
3812 // Default-initialize the implicit variable. This initialization will be
3813 // trivial in almost all cases, except if a union member has an in-class
3814 // initializer:
3815 // union { int n = 0; };
3816 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003817 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003818 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003819
Richard Smithab44d5b2013-12-10 08:25:00 +00003820 // Mark this as an anonymous struct/union type.
3821 Record->setAnonymousStructOrUnion(true);
3822
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003823 // Add the anonymous struct/union object to the current
3824 // context. We'll be referencing this object when we refer to one of
3825 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003826 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003827
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003828 // Inject the members of the anonymous struct/union into the owning
3829 // context and into the identifier resolver chain for name lookup
3830 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003831 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003832 Chain.push_back(Anon);
3833
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003834 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3835 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003836 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003837
David Majnemer2206bf52014-03-05 08:57:59 +00003838 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3839 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3840 Decl *ManglingContextDecl;
3841 if (MangleNumberingContext *MCtx =
3842 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3843 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003844 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003845 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3846 }
3847 }
3848 }
3849
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003850 if (Invalid)
3851 Anon->setInvalidDecl();
3852
John McCall48871652010-08-21 09:40:31 +00003853 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003854}
3855
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003856/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3857/// Microsoft C anonymous structure.
3858/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3859/// Example:
3860///
3861/// struct A { int a; };
3862/// struct B { struct A; int b; };
3863///
3864/// void foo() {
3865/// B var;
3866/// var.a = 3;
3867/// }
3868///
3869Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3870 RecordDecl *Record) {
3871
3872 // If there is no Record, get the record via the typedef.
3873 if (!Record)
3874 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3875
3876 // Mock up a declarator.
3877 Declarator Dc(DS, Declarator::TypeNameContext);
3878 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3879 assert(TInfo && "couldn't build declarator info for anonymous struct");
3880
3881 // Create a declaration for this anonymous struct.
Craig Topperc3ec1492014-05-26 06:22:03 +00003882 NamedDecl *Anon = FieldDecl::Create(Context,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003883 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003884 DS.getLocStart(),
3885 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003886 /*IdentifierInfo=*/nullptr,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003887 Context.getTypeDeclType(Record),
3888 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00003889 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003890 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003891 Anon->setImplicit();
3892
3893 // Add the anonymous struct object to the current context.
3894 CurContext->addDecl(Anon);
3895
3896 // Inject the members of the anonymous struct into the current
3897 // context and into the identifier resolver chain for name lookup
3898 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003899 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003900 Chain.push_back(Anon);
3901
Nico Weberf8bb3de2012-02-01 00:41:00 +00003902 RecordDecl *RecordDef = Record->getDefinition();
3903 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3904 RecordDef, AS_none,
3905 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003906 Anon->setInvalidDecl();
3907
3908 return Anon;
3909}
Steve Naroff2fea1392007-09-02 02:04:30 +00003910
Douglas Gregor92751d42008-11-17 22:58:34 +00003911/// GetNameForDeclarator - Determine the full declaration name for the
3912/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003913DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003914 return GetNameFromUnqualifiedId(D.getName());
3915}
3916
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003917/// \brief Retrieves the declaration name from a parsed unqualified-id.
3918DeclarationNameInfo
3919Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3920 DeclarationNameInfo NameInfo;
3921 NameInfo.setLoc(Name.StartLocation);
3922
Douglas Gregor7861a802009-11-03 01:35:08 +00003923 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003924
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003925 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003926 case UnqualifiedId::IK_Identifier:
3927 NameInfo.setName(Name.Identifier);
3928 NameInfo.setLoc(Name.StartLocation);
3929 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003930
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003931 case UnqualifiedId::IK_OperatorFunctionId:
3932 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3933 Name.OperatorFunctionId.Operator));
3934 NameInfo.setLoc(Name.StartLocation);
3935 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3936 = Name.OperatorFunctionId.SymbolLocations[0];
3937 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3938 = Name.EndLocation.getRawEncoding();
3939 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003940
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003941 case UnqualifiedId::IK_LiteralOperatorId:
3942 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3943 Name.Identifier));
3944 NameInfo.setLoc(Name.StartLocation);
3945 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3946 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003947
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003948 case UnqualifiedId::IK_ConversionFunctionId: {
3949 TypeSourceInfo *TInfo;
3950 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3951 if (Ty.isNull())
3952 return DeclarationNameInfo();
3953 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3954 Context.getCanonicalType(Ty)));
3955 NameInfo.setLoc(Name.StartLocation);
3956 NameInfo.setNamedTypeInfo(TInfo);
3957 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003958 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003959
3960 case UnqualifiedId::IK_ConstructorName: {
3961 TypeSourceInfo *TInfo;
3962 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3963 if (Ty.isNull())
3964 return DeclarationNameInfo();
3965 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3966 Context.getCanonicalType(Ty)));
3967 NameInfo.setLoc(Name.StartLocation);
3968 NameInfo.setNamedTypeInfo(TInfo);
3969 return NameInfo;
3970 }
3971
3972 case UnqualifiedId::IK_ConstructorTemplateId: {
3973 // In well-formed code, we can only have a constructor
3974 // template-id that refers to the current context, so go there
3975 // to find the actual type being constructed.
3976 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3977 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3978 return DeclarationNameInfo();
3979
3980 // Determine the type of the class being constructed.
3981 QualType CurClassType = Context.getTypeDeclType(CurClass);
3982
3983 // FIXME: Check two things: that the template-id names the same type as
3984 // CurClassType, and that the template-id does not occur when the name
3985 // was qualified.
3986
3987 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3988 Context.getCanonicalType(CurClassType)));
3989 NameInfo.setLoc(Name.StartLocation);
3990 // FIXME: should we retrieve TypeSourceInfo?
Craig Topperc3ec1492014-05-26 06:22:03 +00003991 NameInfo.setNamedTypeInfo(nullptr);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003992 return NameInfo;
3993 }
3994
3995 case UnqualifiedId::IK_DestructorName: {
3996 TypeSourceInfo *TInfo;
3997 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3998 if (Ty.isNull())
3999 return DeclarationNameInfo();
4000 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4001 Context.getCanonicalType(Ty)));
4002 NameInfo.setLoc(Name.StartLocation);
4003 NameInfo.setNamedTypeInfo(TInfo);
4004 return NameInfo;
4005 }
4006
4007 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00004008 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004009 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4010 return Context.getNameForTemplate(TName, TNameLoc);
4011 }
4012
4013 } // switch (Name.getKind())
4014
David Blaikie83d382b2011-09-23 05:06:16 +00004015 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00004016}
4017
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004018static QualType getCoreType(QualType Ty) {
4019 do {
4020 if (Ty->isPointerType() || Ty->isReferenceType())
4021 Ty = Ty->getPointeeType();
4022 else if (Ty->isArrayType())
4023 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4024 else
4025 return Ty.withoutLocalFastQualifiers();
4026 } while (true);
4027}
4028
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004029/// hasSimilarParameters - Determine whether the C++ functions Declaration
4030/// and Definition have "nearly" matching parameters. This heuristic is
4031/// used to improve diagnostics in the case where an out-of-line function
4032/// definition doesn't match any declaration within the class or namespace.
4033/// Also sets Params to the list of indices to the parameters that differ
4034/// between the declaration and the definition. If hasSimilarParameters
4035/// returns true and Params is empty, then all of the parameters match.
4036static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00004037 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004038 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004039 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004040 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004041 if (Declaration->param_size() != Definition->param_size())
4042 return false;
4043 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4044 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4045 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4046
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004047 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004048 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004049 continue;
4050
4051 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4052 QualType DefParamBaseTy = getCoreType(DefParamTy);
4053 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4054 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4055
4056 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4057 (DeclTyName && DeclTyName == DefTyName))
4058 Params.push_back(Idx);
4059 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004060 return false;
4061 }
4062
4063 return true;
4064}
4065
John McCall99b2fe52010-04-29 23:50:39 +00004066/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4067/// declarator needs to be rebuilt in the current instantiation.
4068/// Any bits of declarator which appear before the name are valid for
4069/// consideration here. That's specifically the type in the decl spec
4070/// and the base type in any member-pointer chunks.
4071static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4072 DeclarationName Name) {
4073 // The types we specifically need to rebuild are:
4074 // - typenames, typeofs, and decltypes
4075 // - types which will become injected class names
4076 // Of course, we also need to rebuild any type referencing such a
4077 // type. It's safest to just say "dependent", but we call out a
4078 // few cases here.
4079
4080 DeclSpec &DS = D.getMutableDeclSpec();
4081 switch (DS.getTypeSpecType()) {
4082 case DeclSpec::TST_typename:
4083 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004084 case DeclSpec::TST_underlyingType:
4085 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004086 // Grab the type from the parser.
Craig Topperc3ec1492014-05-26 06:22:03 +00004087 TypeSourceInfo *TSI = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00004088 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004089 if (T.isNull() || !T->isDependentType()) break;
4090
4091 // Make sure there's a type source info. This isn't really much
4092 // of a waste; most dependent types should have type source info
4093 // attached already.
4094 if (!TSI)
4095 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4096
4097 // Rebuild the type in the current instantiation.
4098 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4099 if (!TSI) return true;
4100
4101 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004102 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4103 DS.UpdateTypeRep(LocType);
4104 break;
4105 }
4106
Richard Smith1620ebd2012-10-01 20:35:07 +00004107 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004108 case DeclSpec::TST_typeofExpr: {
4109 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004110 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004111 if (Result.isInvalid()) return true;
4112 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004113 break;
4114 }
4115
4116 default:
4117 // Nothing to do for these decl specs.
4118 break;
4119 }
4120
4121 // It doesn't matter what order we do this in.
4122 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4123 DeclaratorChunk &Chunk = D.getTypeObject(I);
4124
4125 // The only type information in the declarator which can come
4126 // before the declaration name is the base type of a member
4127 // pointer.
4128 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4129 continue;
4130
4131 // Rebuild the scope specifier in-place.
4132 CXXScopeSpec &SS = Chunk.Mem.Scope();
4133 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4134 return true;
4135 }
4136
4137 return false;
4138}
4139
Anders Carlsson1052fd72011-07-04 16:28:17 +00004140Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004141 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004142 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004143
4144 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004145 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004146 Dcl->setTopLevelDeclInObjCContainer();
4147
4148 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004149}
4150
Richard Smithdda56e42011-04-15 14:24:37 +00004151/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4152/// If T is the name of a class, then each of the following shall have a
4153/// name different from T:
4154/// - every static data member of class T;
4155/// - every member function of class T
4156/// - every member of class T that is itself a type;
4157/// \returns true if the declaration name violates these rules.
4158bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4159 DeclarationNameInfo NameInfo) {
4160 DeclarationName Name = NameInfo.getName();
4161
4162 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4163 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4164 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4165 return true;
4166 }
4167
4168 return false;
4169}
Douglas Gregor31feb332012-03-17 23:06:31 +00004170
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004171/// \brief Diagnose a declaration whose declarator-id has the given
4172/// nested-name-specifier.
4173///
4174/// \param SS The nested-name-specifier of the declarator-id.
4175///
4176/// \param DC The declaration context to which the nested-name-specifier
4177/// resolves.
4178///
4179/// \param Name The name of the entity being declared.
4180///
4181/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004182///
4183/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004184bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004185 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004186 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004187 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004188 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004189 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004190
4191 // If the user provided a superfluous scope specifier that refers back to the
4192 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004193 //
4194 // class X {
4195 // void X::f();
4196 // };
Richard Smitha2302242013-12-05 07:51:02 +00004197 //
4198 // Note, it was once ill-formed to give redundant qualification in all
4199 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004200 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004201 if (Cur->isRecord()) {
4202 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4203 : diag::err_member_extra_qualification)
4204 << Name << FixItHint::CreateRemoval(SS.getRange());
4205 SS.clear();
4206 } else {
4207 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4208 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004209 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004210 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004211
4212 // Check whether the qualifying scope encloses the scope of the original
4213 // declaration.
4214 if (!Cur->Encloses(DC)) {
4215 if (Cur->isRecord())
4216 Diag(Loc, diag::err_member_qualification)
4217 << Name << SS.getRange();
4218 else if (isa<TranslationUnitDecl>(DC))
4219 Diag(Loc, diag::err_invalid_declarator_global_scope)
4220 << Name << SS.getRange();
4221 else if (isa<FunctionDecl>(Cur))
4222 Diag(Loc, diag::err_invalid_declarator_in_function)
4223 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004224 else if (isa<BlockDecl>(Cur))
4225 Diag(Loc, diag::err_invalid_declarator_in_block)
4226 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004227 else
4228 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004229 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004230
Douglas Gregor31feb332012-03-17 23:06:31 +00004231 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004232 }
4233
4234 if (Cur->isRecord()) {
4235 // Cannot qualify members within a class.
4236 Diag(Loc, diag::err_member_qualification)
4237 << Name << SS.getRange();
4238 SS.clear();
4239
4240 // C++ constructors and destructors with incorrect scopes can break
4241 // our AST invariants by having the wrong underlying types. If
4242 // that's the case, then drop this declaration entirely.
4243 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4244 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4245 !Context.hasSameType(Name.getCXXNameType(),
4246 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4247 return true;
4248
4249 return false;
4250 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004251
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004252 // C++11 [dcl.meaning]p1:
4253 // [...] "The nested-name-specifier of the qualified declarator-id shall
4254 // not begin with a decltype-specifer"
4255 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4256 while (SpecLoc.getPrefix())
4257 SpecLoc = SpecLoc.getPrefix();
4258 if (dyn_cast_or_null<DecltypeType>(
4259 SpecLoc.getNestedNameSpecifier()->getAsType()))
4260 Diag(Loc, diag::err_decltype_in_declarator)
4261 << SpecLoc.getTypeLoc().getSourceRange();
4262
Douglas Gregor31feb332012-03-17 23:06:31 +00004263 return false;
4264}
4265
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004266NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4267 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004268 // TODO: consider using NameInfo for diagnostic.
4269 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4270 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004271
Chris Lattner02c04392007-07-25 00:24:17 +00004272 // All of these full declarators require an identifier. If it doesn't have
4273 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004274 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004275 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004276 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004277 diag::err_declarator_need_ident)
4278 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004279 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00004280 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
Craig Topperc3ec1492014-05-26 06:22:03 +00004281 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004282
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004283 // The scope passed in may not be a decl scope. Zip up the scope tree until
4284 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004285 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004286 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004287 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004288
John McCall99b2fe52010-04-29 23:50:39 +00004289 DeclContext *DC = CurContext;
4290 if (D.getCXXScopeSpec().isInvalid())
4291 D.setInvalidType();
4292 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004293 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4294 UPPC_DeclarationQualifier))
Craig Topperc3ec1492014-05-26 06:22:03 +00004295 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +00004296
John McCall99b2fe52010-04-29 23:50:39 +00004297 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4298 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004299 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004300 // If we could not compute the declaration context, it's because the
4301 // declaration context is dependent but does not refer to a class,
4302 // class template, or class template partial specialization. Complain
4303 // and return early, to avoid the coming semantic disaster.
4304 Diag(D.getIdentifierLoc(),
4305 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004306 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004307 << D.getCXXScopeSpec().getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004308 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004309 }
John McCall99b2fe52010-04-29 23:50:39 +00004310 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004311
John McCall99b2fe52010-04-29 23:50:39 +00004312 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004313 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00004314 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004315
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004316 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4317 Diag(D.getIdentifierLoc(),
4318 diag::err_member_def_undefined_record)
4319 << Name << DC << D.getCXXScopeSpec().getRange();
4320 D.setInvalidType();
4321 } else if (!D.getDeclSpec().isFriendSpecified()) {
4322 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4323 Name, D.getIdentifierLoc())) {
4324 if (DC->isRecord())
Craig Topperc3ec1492014-05-26 06:22:03 +00004325 return nullptr;
4326
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004327 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004328 }
John McCall99b2fe52010-04-29 23:50:39 +00004329 }
4330
4331 // Check whether we need to rebuild the type of the given
4332 // declaration in the current instantiation.
4333 if (EnteringContext && IsDependentContext &&
4334 TemplateParamLists.size() != 0) {
4335 ContextRAII SavedContext(*this, DC);
4336 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4337 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004338 }
4339 }
Richard Smithdda56e42011-04-15 14:24:37 +00004340
4341 if (DiagnoseClassNameShadow(DC, NameInfo))
4342 // If this is a typedef, we'll end up spewing multiple diagnostics.
4343 // Just return early; it's safer.
4344 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Craig Topperc3ec1492014-05-26 06:22:03 +00004345 return nullptr;
4346
John McCall8cb7bdf2010-06-04 23:28:52 +00004347 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4348 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004349
Douglas Gregor506bd562010-12-13 22:49:22 +00004350 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4351 UPPC_DeclarationType))
4352 D.setInvalidType();
4353
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004354 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004355 ForRedeclaration);
4356
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004357 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004358 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004359 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004360 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004361
4362 // If the declaration we're planning to build will be a function
4363 // or object with linkage, then look for another declaration with
4364 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004365 //
4366 // If the declaration we're planning to build will be declared with
4367 // external linkage in the translation unit, create any builtin with
4368 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004369 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4370 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004371 else if (CurContext->isFunctionOrMethod() &&
4372 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4373 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004374 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004375 CreateBuiltins =
4376 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4377 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4378 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4379 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004380
4381 if (IsLinkageLookup)
4382 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004383
Richard Smith1c34fb72013-08-13 18:18:50 +00004384 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004385 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004386 LookupQualifiedName(Previous, DC);
4387
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004388 // C++ [dcl.meaning]p1:
4389 // When the declarator-id is qualified, the declaration shall refer to a
4390 // previously declared member of the class or namespace to which the
4391 // qualifier refers (or, in the case of a namespace, of an element of the
4392 // inline namespace set of that namespace (7.3.1)) or to a specialization
4393 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004394 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004395 // Note that we already checked the context above, and that we do not have
4396 // enough information to make sure that Previous contains the declaration
4397 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004398 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004399 // class X {
4400 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004401 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004402 // };
4403 //
Douglas Gregorad590502008-12-15 23:53:10 +00004404 // void X::f(int) { } // ill-formed
4405 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004406 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004407 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004408 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004409
4410 // C++ [dcl.meaning]p1:
4411 // [...] the member shall not merely have been introduced by a
4412 // using-declaration in the scope of the class or namespace nominated by
4413 // the nested-name-specifier of the declarator-id.
4414 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004415 }
4416
John McCall1f82f242009-11-18 22:49:29 +00004417 if (Previous.isSingleResult() &&
4418 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004419 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004420 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004421 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4422 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004423
Douglas Gregor5101c242008-12-05 18:15:24 +00004424 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004425 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004426 }
4427
Douglas Gregor83a586e2008-04-13 21:07:44 +00004428 // In C++, the previous declaration we find might be a tag type
4429 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004430 // tag type. Note that this does does not apply if we're declaring a
4431 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004432 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004434 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004435
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004436 // Check that there are no default arguments other than in the parameters
4437 // of a function declaration (C++ only).
4438 if (getLangOpts().CPlusPlus)
4439 CheckExtraCXXDefaultArguments(D);
4440
Nico Webercb4c7f42012-12-23 00:40:46 +00004441 NamedDecl *New;
4442
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004443 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004444 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004445 if (TemplateParamLists.size()) {
4446 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
Craig Topperc3ec1492014-05-26 06:22:03 +00004447 return nullptr;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004448 }
Mike Stump11289f42009-09-09 15:08:12 +00004449
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004450 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004451 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004452 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004453 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004454 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004455 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004456 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4457 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004458 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004459
Craig Topperc3ec1492014-05-26 06:22:03 +00004460 if (!New)
4461 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004462
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004463 // If this has an identifier and is not an invalid redeclaration or
4464 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004465 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004466 !(D.isRedeclaration() && New->isInvalidDecl())) {
4467 // Only make a locally-scoped extern declaration visible if it is the first
4468 // declaration of this entity. Qualified lookup for such an entity should
4469 // only find this declaration if there is no visible declaration of it.
4470 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4471 PushOnScopeChains(New, S, AddToContext);
4472 if (!AddToContext)
4473 CurContext->addHiddenDecl(New);
4474 }
Mike Stump11289f42009-09-09 15:08:12 +00004475
John McCall48871652010-08-21 09:40:31 +00004476 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004477}
4478
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004479/// Helper method to turn variable array types into constant array
4480/// types in certain situations which would otherwise be errors (for
4481/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004482static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4483 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004484 bool &SizeIsNegative,
4485 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004486 // This method tries to turn a variable array into a constant
4487 // array even when the size isn't an ICE. This is necessary
4488 // for compatibility with code that depends on gcc's buggy
4489 // constant expression folding, like struct {char x[(int)(char*)2];}
4490 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004491 Oversized = 0;
4492
4493 if (T->isDependentType())
4494 return QualType();
4495
John McCall8ccfcb52009-09-24 19:53:00 +00004496 QualifierCollector Qs;
4497 const Type *Ty = Qs.strip(T);
4498
4499 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004500 QualType Pointee = PTy->getPointeeType();
4501 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004502 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4503 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004504 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004505 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004506 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004507 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004508 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4509 QualType Inner = PTy->getInnerType();
4510 QualType FixedType =
4511 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4512 Oversized);
4513 if (FixedType.isNull()) return FixedType;
4514 FixedType = Context.getParenType(FixedType);
4515 return Qs.apply(Context, FixedType);
4516 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004517
4518 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004519 if (!VLATy)
4520 return QualType();
4521 // FIXME: We should probably handle this case
4522 if (VLATy->getElementType()->isVariablyModifiedType())
4523 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004524
Richard Smith42d3af92011-12-07 00:43:50 +00004525 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004526 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004527 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004528 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004529
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004530 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004531 if (Res.isSigned() && Res.isNegative()) {
4532 SizeIsNegative = true;
4533 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004534 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004535
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004536 // Check whether the array is too large to be addressed.
4537 unsigned ActiveSizeBits
4538 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4539 Res);
4540 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4541 Oversized = Res;
4542 return QualType();
4543 }
4544
4545 return Context.getConstantArrayType(VLATy->getElementType(),
4546 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004547}
4548
Abramo Bagnara341ab732012-11-08 14:44:42 +00004549static void
4550FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004551 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4552 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4553 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4554 DstPTL.getPointeeLoc());
4555 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004556 return;
4557 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004558 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4559 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4560 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4561 DstPTL.getInnerLoc());
4562 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4563 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004564 return;
4565 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004566 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4567 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4568 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4569 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004570 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004571 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4572 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4573 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004574}
4575
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004576/// Helper method to turn variable array types into constant array
4577/// types in certain situations which would otherwise be errors (for
4578/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004579static TypeSourceInfo*
4580TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4581 ASTContext &Context,
4582 bool &SizeIsNegative,
4583 llvm::APSInt &Oversized) {
4584 QualType FixedTy
4585 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4586 SizeIsNegative, Oversized);
4587 if (FixedTy.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00004588 return nullptr;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004589 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4590 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4591 FixedTInfo->getTypeLoc());
4592 return FixedTInfo;
4593}
4594
Richard Smith78165b52013-01-10 23:43:47 +00004595/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004596/// that it can be found later for redeclarations. We include any extern "C"
4597/// declaration that is not visible in the translation unit here, not just
4598/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004599void
Richard Smith39b79682013-06-18 20:15:12 +00004600Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004601 if (!getLangOpts().CPlusPlus &&
4602 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4603 // Don't need to track declarations in the TU in C.
4604 return;
4605
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004606 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004607 // FIXME: There can be multiple such declarations if they are functions marked
4608 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004609 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004610}
4611
Richard Smith39b79682013-06-18 20:15:12 +00004612NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004613 if (ExternalSource) {
4614 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004615 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004616 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004617 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004618 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4619 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004620 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4621 if (Pos == LocallyScopedExternCDecls.end())
4622 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004623 }
4624 }
Richard Smith39b79682013-06-18 20:15:12 +00004625
4626 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00004627 return D ? D->getMostRecentDecl() : nullptr;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004628}
4629
Eli Friedman574c7452009-04-07 19:37:57 +00004630/// \brief Diagnose function specifiers on a declaration of an identifier that
4631/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004632void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004633 // FIXME: We should probably indicate the identifier in question to avoid
4634 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004635 if (DS.isInlineSpecified())
4636 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004637 diag::err_inline_non_function);
4638
Richard Smithb1402ae2013-03-18 22:52:47 +00004639 if (DS.isVirtualSpecified())
4640 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004641 diag::err_virtual_non_function);
4642
Richard Smithb1402ae2013-03-18 22:52:47 +00004643 if (DS.isExplicitSpecified())
4644 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004645 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004646
Richard Smithb1402ae2013-03-18 22:52:47 +00004647 if (DS.isNoreturnSpecified())
4648 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004649 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004650}
4651
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004652NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004653Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004654 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004655 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4656 if (D.getCXXScopeSpec().isSet()) {
4657 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4658 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004659 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004660 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004661 DC = CurContext;
4662 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004663 }
4664
Richard Smithb1402ae2013-03-18 22:52:47 +00004665 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004666
Richard Smitha77a0a62011-08-15 21:04:07 +00004667 if (D.getDeclSpec().isConstexprSpecified())
4668 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4669 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004670
Douglas Gregord8f446f2010-07-13 06:37:01 +00004671 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4672 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4673 << D.getName().getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004674 return nullptr;
Douglas Gregord8f446f2010-07-13 06:37:01 +00004675 }
4676
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004677 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Craig Topperc3ec1492014-05-26 06:22:03 +00004678 if (!NewTD) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004679
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004680 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004681 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004682
Richard Smith3f1b5d02011-05-05 21:57:07 +00004683 CheckTypedefForVariablyModifiedType(S, NewTD);
4684
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004685 bool Redeclaration = D.isRedeclaration();
4686 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4687 D.setRedeclaration(Redeclaration);
4688 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004689}
4690
Richard Smith3f1b5d02011-05-05 21:57:07 +00004691void
4692Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004693 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4694 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004695 // Note that variably modified types must be fixed before merging the decl so
4696 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004697 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4698 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004699 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004700 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004701
Craig Topperc3ec1492014-05-26 06:22:03 +00004702 if (S->getFnParent() == nullptr) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004703 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004704 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004705 TypeSourceInfo *FixedTInfo =
4706 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4707 SizeIsNegative,
4708 Oversized);
4709 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004710 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004711 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004712 } else {
4713 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004714 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004715 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004716 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004717 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004718 Diag(NewTD->getLocation(), diag::err_array_too_large)
4719 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004720 else
Richard Smithdda56e42011-04-15 14:24:37 +00004721 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004722 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004723 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004724 }
4725 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004726}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004727
Richard Smith3f1b5d02011-05-05 21:57:07 +00004728
4729/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4730/// declares a typedef-name, either using the 'typedef' type specifier or via
4731/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4732NamedDecl*
4733Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4734 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004735 // Merge the decl with the existing one if appropriate. If the decl is
4736 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004737 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4738 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004739 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004740 if (!Previous.empty()) {
4741 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004742 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004743 }
4744
Douglas Gregor27821ce2009-07-07 16:35:42 +00004745 // If this is the C FILE type, notify the AST context.
4746 if (IdentifierInfo *II = NewTD->getIdentifier())
4747 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004748 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004749 if (II->isStr("FILE"))
4750 Context.setFILEDecl(NewTD);
4751 else if (II->isStr("jmp_buf"))
4752 Context.setjmp_bufDecl(NewTD);
4753 else if (II->isStr("sigjmp_buf"))
4754 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004755 else if (II->isStr("ucontext_t"))
4756 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004757 }
4758
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004759 return NewTD;
4760}
4761
Douglas Gregor5d68a202009-02-24 19:23:27 +00004762/// \brief Determines whether the given declaration is an out-of-scope
4763/// previous declaration.
4764///
4765/// This routine should be invoked when name lookup has found a
4766/// previous declaration (PrevDecl) that is not in the scope where a
4767/// new declaration by the same name is being introduced. If the new
4768/// declaration occurs in a local scope, previous declarations with
4769/// linkage may still be considered previous declarations (C99
4770/// 6.2.2p4-5, C++ [basic.link]p6).
4771///
4772/// \param PrevDecl the previous declaration found by name
4773/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004774///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004775/// \param DC the context in which the new declaration is being
4776/// declared.
4777///
4778/// \returns true if PrevDecl is an out-of-scope previous declaration
4779/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004780static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004781isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4782 ASTContext &Context) {
4783 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004784 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004785
Douglas Gregoreddf4332009-02-24 20:03:32 +00004786 if (!PrevDecl->hasLinkage())
4787 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004788
David Blaikiebbafb8a2012-03-11 07:00:24 +00004789 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004790 // C++ [basic.link]p6:
4791 // If there is a visible declaration of an entity with linkage
4792 // having the same name and type, ignoring entities declared
4793 // outside the innermost enclosing namespace scope, the block
4794 // scope declaration declares that same entity and receives the
4795 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004796 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004797 if (!OuterContext->isFunctionOrMethod())
4798 // This rule only applies to block-scope declarations.
4799 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004800
4801 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4802 if (PrevOuterContext->isRecord())
4803 // We found a member function: ignore it.
4804 return false;
4805
4806 // Find the innermost enclosing namespace for the new and
4807 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004808 OuterContext = OuterContext->getEnclosingNamespaceContext();
4809 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004810
Douglas Gregorfcee9462010-08-27 22:55:10 +00004811 // The previous declaration is in a different namespace, so it
4812 // isn't the same function.
4813 if (!OuterContext->Equals(PrevOuterContext))
4814 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004815 }
4816
Douglas Gregor5d68a202009-02-24 19:23:27 +00004817 return true;
4818}
4819
John McCall3e11ebe2010-03-15 10:12:16 +00004820static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4821 CXXScopeSpec &SS = D.getCXXScopeSpec();
4822 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004823 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004824}
4825
John McCall31168b02011-06-15 23:02:42 +00004826bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4827 QualType type = decl->getType();
4828 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4829 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4830 // Various kinds of declaration aren't allowed to be __autoreleasing.
4831 unsigned kind = -1U;
4832 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4833 if (var->hasAttr<BlocksAttr>())
4834 kind = 0; // __block
4835 else if (!var->hasLocalStorage())
4836 kind = 1; // global
4837 } else if (isa<ObjCIvarDecl>(decl)) {
4838 kind = 3; // ivar
4839 } else if (isa<FieldDecl>(decl)) {
4840 kind = 2; // field
4841 }
4842
4843 if (kind != -1U) {
4844 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4845 << kind;
4846 }
4847 } else if (lifetime == Qualifiers::OCL_None) {
4848 // Try to infer lifetime.
4849 if (!type->isObjCLifetimeType())
4850 return false;
4851
4852 lifetime = type->getObjCARCImplicitLifetime();
4853 type = Context.getLifetimeQualifiedType(type, lifetime);
4854 decl->setType(type);
4855 }
4856
4857 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4858 // Thread-local variables cannot have lifetime.
4859 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004860 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004861 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004862 << var->getType();
4863 return true;
4864 }
4865 }
4866
4867 return false;
4868}
4869
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004870static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004871 // Ensure that an auto decl is deduced otherwise the checks below might cache
4872 // the wrong linkage.
4873 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4874
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004875 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004876 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004877 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004878 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4879 ND.dropAttr<WeakAttr>();
4880 }
4881 }
4882 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004883 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004884 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4885 ND.dropAttr<WeakRefAttr>();
4886 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004887 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004888
4889 // 'selectany' only applies to externally visible varable declarations.
4890 // It does not apply to functions.
4891 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4892 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4893 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4894 ND.dropAttr<SelectAnyAttr>();
4895 }
4896 }
Nico Rieck8ca0bfc2014-03-31 14:56:58 +00004897
4898 // dll attributes require external linkage.
4899 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4900 if (!ND.isExternallyVisible()) {
4901 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4902 << &ND << Attr;
4903 ND.setInvalidDecl();
4904 }
4905 }
4906 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4907 if (!ND.isExternallyVisible()) {
4908 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4909 << &ND << Attr;
4910 ND.setInvalidDecl();
4911 }
4912 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004913}
4914
Nico Rieck82f0b062014-03-31 14:56:15 +00004915static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4916 NamedDecl *NewDecl,
4917 bool IsSpecialization) {
4918 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4919 OldDecl = OldTD->getTemplatedDecl();
4920 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4921 NewDecl = NewTD->getTemplatedDecl();
4922
4923 if (!OldDecl || !NewDecl)
4924 return;
4925
4926 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4927 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4928 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4929 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4930
4931 // dllimport and dllexport are inheritable attributes so we have to exclude
4932 // inherited attribute instances.
4933 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4934 (NewExportAttr && !NewExportAttr->isInherited());
4935
4936 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4937 // the only exception being explicit specializations.
4938 // Implicitly generated declarations are also excluded for now because there
4939 // is no other way to switch these to use dllimport or dllexport.
4940 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4941 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4942 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4943 << NewDecl
4944 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4945 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4946 NewDecl->setInvalidDecl();
4947 return;
4948 }
4949
4950 // A redeclaration is not allowed to drop a dllimport attribute, the only
4951 // exception being inline function definitions.
Nico Rieck82f0b062014-03-31 14:56:15 +00004952 // NB: MSVC converts such a declaration to dllexport.
Nico Rieck078d2f82014-05-29 16:50:20 +00004953 bool IsInline = false, IsStaticDataMember = false;
4954 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
4955 // Ignore static data because out-of-line definitions are diagnosed
4956 // separately.
4957 IsStaticDataMember = VD->isStaticDataMember();
4958 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl))
4959 IsInline = FD->isInlined();
Hans Wennborgf436b282014-05-22 15:46:15 +00004960
Nico Rieck078d2f82014-05-29 16:50:20 +00004961 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember) {
Nico Rieck82f0b062014-03-31 14:56:15 +00004962 S.Diag(NewDecl->getLocation(),
4963 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4964 << NewDecl << OldImportAttr;
4965 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4966 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4967 OldDecl->dropAttr<DLLImportAttr>();
4968 NewDecl->dropAttr<DLLImportAttr>();
4969 }
4970}
4971
John McCallc87d9722013-04-02 02:48:58 +00004972/// Given that we are within the definition of the given function,
4973/// will that definition behave like C99's 'inline', where the
4974/// definition is discarded except for optimization purposes?
4975static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4976 // Try to avoid calling GetGVALinkageForFunction.
4977
4978 // All cases of this require the 'inline' keyword.
4979 if (!FD->isInlined()) return false;
4980
4981 // This is only possible in C++ with the gnu_inline attribute.
4982 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4983 return false;
4984
4985 // Okay, go ahead and call the relatively-more-expensive function.
4986
4987#ifndef NDEBUG
4988 // AST quite reasonably asserts that it's working on a function
4989 // definition. We don't really have a way to tell it that we're
4990 // currently defining the function, so just lie to it in +Asserts
4991 // builds. This is an awful hack.
4992 FD->setLazyBody(1);
4993#endif
4994
David Majnemer27d69db2014-04-28 22:17:59 +00004995 bool isC99Inline =
4996 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
John McCallc87d9722013-04-02 02:48:58 +00004997
4998#ifndef NDEBUG
4999 FD->setLazyBody(0);
5000#endif
5001
5002 return isC99Inline;
5003}
5004
Richard Smithac974a32013-06-30 09:48:50 +00005005/// Determine whether a variable is extern "C" prior to attaching
5006/// an initializer. We can't just call isExternC() here, because that
5007/// will also compute and cache whether the declaration is externally
5008/// visible, which might change when we attach the initializer.
5009///
5010/// This can only be used if the declaration is known to not be a
5011/// redeclaration of an internal linkage declaration.
5012///
5013/// For instance:
5014///
5015/// auto x = []{};
5016///
5017/// Attaching the initializer here makes this declaration not externally
5018/// visible, because its type has internal linkage.
5019///
5020/// FIXME: This is a hack.
5021template<typename T>
5022static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5023 if (S.getLangOpts().CPlusPlus) {
5024 // In C++, the overloadable attribute negates the effects of extern "C".
5025 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5026 return false;
5027 }
5028 return D->isExternC();
5029}
5030
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005031static bool shouldConsiderLinkage(const VarDecl *VD) {
5032 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5033 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005034 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005035 if (DC->isFileContext())
5036 return true;
5037 if (DC->isRecord())
5038 return false;
5039 llvm_unreachable("Unexpected context");
5040}
5041
5042static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5043 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5044 if (DC->isFileContext() || DC->isFunctionOrMethod())
5045 return true;
5046 if (DC->isRecord())
5047 return false;
5048 llvm_unreachable("Unexpected context");
5049}
5050
Nico Riecke84f8db2014-03-23 21:24:01 +00005051static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5052 AttributeList::Kind Kind) {
5053 for (const AttributeList *L = AttrList; L; L = L->getNext())
5054 if (L->getKind() == Kind)
5055 return true;
5056 return false;
5057}
5058
5059static bool hasParsedAttr(Scope *S, const Declarator &PD,
5060 AttributeList::Kind Kind) {
5061 // Check decl attributes on the DeclSpec.
5062 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5063 return true;
5064
5065 // Walk the declarator structure, checking decl attributes that were in a type
5066 // position to the decl itself.
5067 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5068 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5069 return true;
5070 }
5071
5072 // Finally, check attributes on the decl itself.
5073 return hasParsedAttr(S, PD.getAttributes(), Kind);
5074}
5075
Richard Smith541b38b2013-09-20 01:15:31 +00005076/// Adjust the \c DeclContext for a function or variable that might be a
5077/// function-local external declaration.
5078bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5079 if (!DC->isFunctionOrMethod())
5080 return false;
5081
5082 // If this is a local extern function or variable declared within a function
5083 // template, don't add it into the enclosing namespace scope until it is
5084 // instantiated; it might have a dependent type right now.
5085 if (DC->isDependentContext())
5086 return true;
5087
5088 // C++11 [basic.link]p7:
5089 // When a block scope declaration of an entity with linkage is not found to
5090 // refer to some other declaration, then that entity is a member of the
5091 // innermost enclosing namespace.
5092 //
5093 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5094 // semantically-enclosing namespace, not a lexically-enclosing one.
5095 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5096 DC = DC->getParent();
5097 return true;
5098}
5099
Larisse Voufo39a1e502013-08-06 01:03:05 +00005100NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00005101Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005102 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005103 MultiTemplateParamsArg TemplateParamLists,
5104 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005105 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005106 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005107
Douglas Gregorc4df4072010-04-19 22:54:31 +00005108 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00005109 VarDecl::StorageClass SC =
5110 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00005111
Nico Riecke84f8db2014-03-23 21:24:01 +00005112 // dllimport globals without explicit storage class are treated as extern. We
5113 // have to change the storage class this early to get the right DeclContext.
5114 if (SC == SC_None && !DC->isRecord() &&
Nico Rieck755a36f2014-05-25 10:34:16 +00005115 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5116 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
Nico Riecke84f8db2014-03-23 21:24:01 +00005117 SC = SC_Extern;
5118
Richard Smith541b38b2013-09-20 01:15:31 +00005119 DeclContext *OriginalDC = DC;
5120 bool IsLocalExternDecl = SC == SC_Extern &&
5121 adjustContextForLocalExternDecl(DC);
5122
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005123 if (getLangOpts().OpenCL) {
5124 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5125 QualType NR = R;
5126 while (NR->isPointerType()) {
5127 if (NR->isFunctionPointerType()) {
5128 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5129 D.setInvalidType();
5130 break;
5131 }
5132 NR = NR->getPointeeType();
5133 }
5134
5135 if (!getOpenCLOptions().cl_khr_fp16) {
5136 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5137 // half array type (unless the cl_khr_fp16 extension is enabled).
5138 if (Context.getBaseElementType(R)->isHalfType()) {
5139 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5140 D.setInvalidType();
5141 }
Joey Goulydd7f4562013-01-23 11:56:20 +00005142 }
5143 }
5144
Douglas Gregorc4df4072010-04-19 22:54:31 +00005145 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005146 // mutable can only appear on non-static class members, so it's always
5147 // an error here
5148 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005149 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005150 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005151 }
John McCallc87d9722013-04-02 02:48:58 +00005152
Richard Smithf2c9afc2013-06-17 01:34:01 +00005153 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5154 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5155 D.getDeclSpec().getStorageClassSpecLoc())) {
5156 // In C++11, the 'register' storage class specifier is deprecated.
5157 // Suppress the warning in system macros, it's used in macros in some
5158 // popular C system headers, such as in glibc's htonl() macro.
5159 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5160 diag::warn_deprecated_register)
5161 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5162 }
5163
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005164 IdentifierInfo *II = Name.getAsIdentifierInfo();
5165 if (!II) {
5166 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005167 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00005168 return nullptr;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005169 }
5170
Richard Smithb1402ae2013-03-18 22:52:47 +00005171 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005172
Craig Topperc3ec1492014-05-26 06:22:03 +00005173 if (!DC->isRecord() && S->getFnParent() == nullptr) {
Douglas Gregor212cab32009-03-11 20:22:50 +00005174 // C99 6.9p2: The storage-class specifiers auto and register shall not
5175 // appear in the declaration specifiers in an external declaration.
Renato Golin230c5eb2014-05-19 18:15:42 +00005176 // Global Register+Asm is a GNU extension we support.
5177 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5178 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005179 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005180 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005181 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005182
David Blaikiebbafb8a2012-03-11 07:00:24 +00005183 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005184 // Set up the special work-group-local storage class for variables in the
5185 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005186 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005187 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005188 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005189
Guy Benyei61054192013-02-07 10:55:47 +00005190 // OpenCL v1.2 s6.9.b p4:
5191 // The sampler type cannot be used with the __local and __global address
5192 // space qualifiers.
5193 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5194 R.getAddressSpace() == LangAS::opencl_global)) {
5195 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5196 }
5197
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005198 // OpenCL 1.2 spec, p6.9 r:
5199 // The event type cannot be used to declare a program scope variable.
5200 // The event type cannot be used with the __local, __constant and __global
5201 // address space qualifiers.
5202 if (R->isEventT()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005203 if (S->getParent() == nullptr) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005204 Diag(D.getLocStart(), diag::err_event_t_global_var);
5205 D.setInvalidType();
5206 }
5207
5208 if (R.getAddressSpace()) {
5209 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5210 D.setInvalidType();
5211 }
5212 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005213 }
5214
Larisse Voufo39a1e502013-08-06 01:03:05 +00005215 bool IsExplicitSpecialization = false;
5216 bool IsVariableTemplateSpecialization = false;
5217 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005218 bool IsVariableTemplate = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00005219 VarDecl *NewVD = nullptr;
5220 VarTemplateDecl *NewTemplate = nullptr;
5221 TemplateParameterList *TemplateParams = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005222 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005223 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005224 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005225 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005226
5227 if (D.isInvalidType())
5228 NewVD->setInvalidDecl();
5229 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005230 bool Invalid = false;
5231
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005232 if (DC->isRecord() && !CurContext->isRecord()) {
5233 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005234 switch (SC) {
5235 case SC_None:
5236 break;
5237 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005238 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5239 diag::err_static_out_of_line)
5240 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005241 break;
5242 case SC_Auto:
5243 case SC_Register:
5244 case SC_Extern:
5245 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5246 // to names of variables declared in a block or to function parameters.
5247 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5248 // of class members
5249
5250 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5251 diag::err_storage_class_for_static_member)
5252 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5253 break;
5254 case SC_PrivateExtern:
5255 llvm_unreachable("C storage class in c++!");
5256 case SC_OpenCLWorkGroupLocal:
5257 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005258 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005259 }
5260
Richard Smith42973752012-02-16 20:41:22 +00005261 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005262 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5263 if (RD->isLocalClass())
5264 Diag(D.getIdentifierLoc(),
5265 diag::err_static_data_member_not_allowed_in_local_class)
5266 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005267
Richard Smith42973752012-02-16 20:41:22 +00005268 // C++98 [class.union]p1: If a union contains a static data member,
5269 // the program is ill-formed. C++11 drops this restriction.
5270 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005271 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005272 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005273 ? diag::warn_cxx98_compat_static_data_member_in_union
5274 : diag::ext_static_data_member_in_union) << Name;
5275 // We conservatively disallow static data members in anonymous structs.
5276 else if (!RD->getDeclName())
5277 Diag(D.getIdentifierLoc(),
5278 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005279 << Name << RD->isUnion();
5280 }
5281 }
5282
5283 // Match up the template parameter lists with the scope specifier, then
5284 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005285 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5286 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00005287 D.getCXXScopeSpec(),
5288 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5289 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00005290 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005291 TemplateParamLists,
Richard Smithbeef3452014-01-16 23:39:20 +00005292 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005293
Richard Smithbeef3452014-01-16 23:39:20 +00005294 if (TemplateParams) {
5295 if (!TemplateParams->size() &&
5296 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5297 // There is an extraneous 'template<>' for this variable. Complain
5298 // about it, but allow the declaration of the variable.
5299 Diag(TemplateParams->getTemplateLoc(),
5300 diag::err_template_variable_noparams)
5301 << II
5302 << SourceRange(TemplateParams->getTemplateLoc(),
5303 TemplateParams->getRAngleLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00005304 TemplateParams = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005305 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005306 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5307 // This is an explicit specialization or a partial specialization.
5308 // FIXME: Check that we can declare a specialization here.
5309 IsVariableTemplateSpecialization = true;
5310 IsPartialSpecialization = TemplateParams->size() > 0;
5311 } else { // if (TemplateParams->size() > 0)
5312 // This is a template declaration.
5313 IsVariableTemplate = true;
5314
5315 // Check that we can declare a template here.
5316 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00005317 return nullptr;
Richard Smith0d963d62014-04-17 02:56:49 +00005318
5319 // Only C++1y supports variable templates (N3651).
5320 Diag(D.getIdentifierLoc(),
5321 getLangOpts().CPlusPlus1y
5322 ? diag::warn_cxx11_compat_variable_template
5323 : diag::ext_variable_template);
Richard Smithbeef3452014-01-16 23:39:20 +00005324 }
5325 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00005326 } else {
5327 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5328 "should have a 'template<>' for this decl");
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
Larisse Voufo39a1e502013-08-06 01:03:05 +00005331 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005332 SourceLocation TemplateKWLoc =
5333 TemplateParamLists.size() > 0
5334 ? TemplateParamLists[0]->getTemplateLoc()
5335 : SourceLocation();
5336 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005337 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005338 IsPartialSpecialization);
5339 if (Res.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00005340 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005341 NewVD = cast<VarDecl>(Res.get());
5342 AddToScope = false;
5343 } else
5344 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5345 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005346
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005347 // If this is supposed to be a variable template, create it as such.
5348 if (IsVariableTemplate) {
5349 NewTemplate =
5350 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005351 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005352 NewVD->setDescribedVarTemplate(NewTemplate);
5353 }
5354
Richard Smithb2bc2e62011-02-21 20:05:19 +00005355 // If this decl has an auto type in need of deduction, make a note of the
5356 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005357 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005358 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005359
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005360 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005361 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005362 if (NewTemplate)
5363 NewTemplate->setInvalidDecl();
5364 }
Mike Stump11289f42009-09-09 15:08:12 +00005365
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005366 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005367
Richard Smith72db5632014-01-25 21:32:06 +00005368 // If we have any template parameter lists that don't directly belong to
5369 // the variable (matching the scope specifier), store them.
5370 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5371 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005372 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005373 Context, TemplateParamLists.size() - VDTemplateParamLists,
5374 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005375
Richard Smith6331c402012-02-13 22:16:19 +00005376 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005377 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005378 }
5379
Douglas Gregor41866812011-09-12 18:37:38 +00005380 // Set the lexical context. If the declarator has a C++ scope specifier, the
5381 // lexical context will be different from the semantic context.
5382 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005383 if (NewTemplate)
5384 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005385
Richard Smith541b38b2013-09-20 01:15:31 +00005386 if (IsLocalExternDecl)
5387 NewVD->setLocalExternDecl();
5388
Richard Smithb4a9e862013-04-12 22:46:28 +00005389 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005390 if (NewVD->hasLocalStorage()) {
5391 // C++11 [dcl.stc]p4:
5392 // When thread_local is applied to a variable of block scope the
5393 // storage-class-specifier static is implied if it does not appear
5394 // explicitly.
5395 // Core issue: 'static' is not implied if the variable is declared
5396 // 'extern'.
5397 if (SCSpec == DeclSpec::SCS_unspecified &&
5398 TSCS == DeclSpec::TSCS_thread_local &&
5399 DC->isFunctionOrMethod())
5400 NewVD->setTSCSpec(TSCS);
5401 else
5402 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5403 diag::err_thread_non_global)
5404 << DeclSpec::getSpecifierName(TSCS);
5405 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005406 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5407 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005408 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005409 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005410 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005411
John McCallc87d9722013-04-02 02:48:58 +00005412 // C99 6.7.4p3
5413 // An inline definition of a function with external linkage shall
5414 // not contain a definition of a modifiable object with static or
5415 // thread storage duration...
5416 // We only apply this when the function is required to be defined
5417 // elsewhere, i.e. when the function is not 'extern inline'. Note
5418 // that a local variable with thread storage duration still has to
5419 // be marked 'static'. Also note that it's possible to get these
5420 // semantics in C++ using __attribute__((gnu_inline)).
Craig Topperc3ec1492014-05-26 06:22:03 +00005421 if (SC == SC_Static && S->getFnParent() != nullptr &&
John McCallc87d9722013-04-02 02:48:58 +00005422 !NewVD->getType().isConstQualified()) {
5423 FunctionDecl *CurFD = getCurFunctionDecl();
5424 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5425 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5426 diag::warn_static_local_in_extern_inline);
5427 MaybeSuggestAddingStaticToDecl(CurFD);
5428 }
5429 }
5430
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005431 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005432 if (IsVariableTemplateSpecialization)
5433 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5434 << (IsPartialSpecialization ? 1 : 0)
5435 << FixItHint::CreateRemoval(
5436 D.getDeclSpec().getModulePrivateSpecLoc());
5437 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005438 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5439 << 2
5440 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005441 else if (NewVD->hasLocalStorage())
5442 Diag(NewVD->getLocation(), diag::err_module_private_local)
5443 << 0 << NewVD->getDeclName()
5444 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5445 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005446 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005447 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005448 if (NewTemplate)
5449 NewTemplate->setModulePrivate();
5450 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005451 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005452
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005453 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005454 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005455
Peter Collingbournec6b08572012-08-28 20:37:50 +00005456 if (getLangOpts().CUDA) {
5457 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5458 // storage [duration]."
Craig Topperc3ec1492014-05-26 06:22:03 +00005459 if (SC == SC_None && S->getFnParent() != nullptr &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005460 (NewVD->hasAttr<CUDASharedAttr>() ||
5461 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005462 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005463 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005464 }
5465
Nico Riecke84f8db2014-03-23 21:24:01 +00005466 // Ensure that dllimport globals without explicit storage class are treated as
5467 // extern. The storage class is set above using parsed attributes. Now we can
5468 // check the VarDecl itself.
5469 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5470 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5471 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5472
John McCall31168b02011-06-15 23:02:42 +00005473 // In auto-retain/release, infer strong retension for variables of
5474 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005475 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005476 NewVD->setInvalidDecl();
5477
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005478 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005479 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005480 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005481 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005482 StringRef Label = SE->getString();
Craig Topperc3ec1492014-05-26 06:22:03 +00005483 if (S->getFnParent() != nullptr) {
Abramo Bagnara13392232011-01-11 15:16:52 +00005484 switch (SC) {
5485 case SC_None:
5486 case SC_Auto:
5487 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5488 break;
5489 case SC_Register:
Renato Golin230c5eb2014-05-19 18:15:42 +00005490 // Local Named register
Douglas Gregore8bbc122011-09-02 00:18:52 +00005491 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005492 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5493 break;
5494 case SC_Static:
5495 case SC_Extern:
5496 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005497 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005498 break;
5499 }
Renato Golin230c5eb2014-05-19 18:15:42 +00005500 } else if (SC == SC_Register) {
5501 // Global Named register
5502 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5503 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
Renato Golin2e31e4e2014-06-05 16:45:22 +00005504 if (!R->isIntegralType(Context) && !R->isPointerType()) {
5505 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5506 NewVD->setInvalidDecl(true);
5507 }
Abramo Bagnara13392232011-01-11 15:16:52 +00005508 }
5509
5510 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005511 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005512 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5513 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5514 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5515 if (I != ExtnameUndeclaredIdentifiers.end()) {
5516 NewVD->addAttr(I->second);
5517 ExtnameUndeclaredIdentifiers.erase(I);
5518 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005519 }
5520
John McCalla2a3f7d2010-03-16 21:48:18 +00005521 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005522 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005523 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005524
John McCall1f82f242009-11-18 22:49:29 +00005525 // Don't consider existing declarations that are in a different
5526 // scope and are out-of-semantic-context declarations (if the new
5527 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005528 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5529 D.getCXXScopeSpec().isNotEmpty() ||
5530 IsExplicitSpecialization ||
5531 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005532
Richard Smith1c34fb72013-08-13 18:18:50 +00005533 // Check whether the previous declaration is in the same block scope. This
5534 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5535 if (getLangOpts().CPlusPlus &&
5536 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5537 NewVD->setPreviousDeclInSameBlockScope(
5538 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005539 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005540
David Blaikiebbafb8a2012-03-11 07:00:24 +00005541 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005542 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5543 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005544 // If this is an explicit specialization of a static data member, check it.
5545 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5546 CheckMemberSpecialization(NewVD, Previous))
5547 NewVD->setInvalidDecl();
5548
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005549 // Merge the decl with the existing one if appropriate.
5550 if (!Previous.empty()) {
5551 if (Previous.isSingleResult() &&
5552 isa<FieldDecl>(Previous.getFoundDecl()) &&
5553 D.getCXXScopeSpec().isSet()) {
5554 // The user tried to define a non-static data member
5555 // out-of-line (C++ [dcl.meaning]p1).
5556 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5557 << D.getCXXScopeSpec().getRange();
5558 Previous.clear();
5559 NewVD->setInvalidDecl();
5560 }
5561 } else if (D.getCXXScopeSpec().isSet()) {
5562 // No previous declaration in the qualifying scope.
5563 Diag(D.getIdentifierLoc(), diag::err_no_member)
5564 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005565 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005566 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005567 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005568
Richard Smithbeef3452014-01-16 23:39:20 +00005569 if (!IsVariableTemplateSpecialization)
5570 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005571
Richard Smithbeef3452014-01-16 23:39:20 +00005572 if (NewTemplate) {
5573 VarTemplateDecl *PrevVarTemplate =
5574 NewVD->getPreviousDecl()
5575 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
Craig Topperc3ec1492014-05-26 06:22:03 +00005576 : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005577
5578 // Check the template parameter list of this declaration, possibly
5579 // merging in the template parameter list from the previous variable
5580 // template declaration.
5581 if (CheckTemplateParameterList(
5582 TemplateParams,
5583 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
Craig Topperc3ec1492014-05-26 06:22:03 +00005584 : nullptr,
Richard Smithbeef3452014-01-16 23:39:20 +00005585 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5586 DC->isDependentContext())
5587 ? TPC_ClassTemplateMember
5588 : TPC_VarTemplate))
5589 NewVD->setInvalidDecl();
5590
5591 // If we are providing an explicit specialization of a static variable
5592 // template, make a note of that.
5593 if (PrevVarTemplate &&
5594 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5595 PrevVarTemplate->setMemberSpecialization();
5596 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005597 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005598
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005599 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005600
Richard Smithac974a32013-06-30 09:48:50 +00005601 // If this is the first declaration of an extern C variable, update
5602 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005603 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005604 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005605 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005606
Reid Klecknerd8110b62013-09-10 20:14:30 +00005607 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005608 Decl *ManglingContextDecl;
5609 if (MangleNumberingContext *MCtx =
5610 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5611 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005612 Context.setManglingNumber(
5613 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005614 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005615 }
5616 }
5617
Nico Rieck82f0b062014-03-31 14:56:15 +00005618 if (D.isRedeclaration() && !Previous.empty()) {
5619 checkDLLAttributeRedeclaration(
5620 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5621 IsExplicitSpecialization);
5622 }
5623
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005624 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005625 if (NewVD->isInvalidDecl())
5626 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005627 ActOnDocumentableDecl(NewTemplate);
5628 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005629 }
5630
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005631 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005632}
5633
John McCalldf8b37c2010-03-22 09:20:08 +00005634/// \brief Diagnose variable or built-in function shadowing. Implements
5635/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005636///
John McCalldf8b37c2010-03-22 09:20:08 +00005637/// This method is called whenever a VarDecl is added to a "useful"
5638/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005639///
John McCall2d8c7602010-03-20 04:12:52 +00005640/// \param S the scope in which the shadowing name is being declared
5641/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005642///
John McCalldf8b37c2010-03-22 09:20:08 +00005643void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005644 // Return if warning is ignored.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005645 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
John McCalla2a3f7d2010-03-16 21:48:18 +00005646 return;
5647
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005648 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005649 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005650 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005651
5652 DeclContext *NewDC = D->getDeclContext();
5653
John McCall2d8c7602010-03-20 04:12:52 +00005654 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005655 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005656 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005657
John McCalla2a3f7d2010-03-16 21:48:18 +00005658 NamedDecl* ShadowedDecl = R.getFoundDecl();
5659 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5660 return;
5661
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005662 // Fields are not shadowed by variables in C++ static methods.
5663 if (isa<FieldDecl>(ShadowedDecl))
5664 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5665 if (MD->isStatic())
5666 return;
5667
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005668 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5669 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005670 // For shadowing external vars, make sure that we point to the global
5671 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005672 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005673 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005674 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005675 break;
5676 }
5677 }
5678
5679 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5680
John McCall2d8c7602010-03-20 04:12:52 +00005681 // Only warn about certain kinds of shadowing for class members.
5682 if (NewDC && NewDC->isRecord()) {
5683 // In particular, don't warn about shadowing non-class members.
5684 if (!OldDC->isRecord())
5685 return;
5686
5687 // TODO: should we warn about static data members shadowing
5688 // static data members from base classes?
5689
5690 // TODO: don't diagnose for inaccessible shadowed members.
5691 // This is hard to do perfectly because we might friend the
5692 // shadowing context, but that's just a false negative.
5693 }
5694
5695 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005696 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005697 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005698 if (isa<FieldDecl>(ShadowedDecl))
5699 Kind = 3; // field
5700 else
5701 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005702 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005703 Kind = 1; // global
5704 else
5705 Kind = 0; // local
5706
John McCall2d8c7602010-03-20 04:12:52 +00005707 DeclarationName Name = R.getLookupName();
5708
John McCalla2a3f7d2010-03-16 21:48:18 +00005709 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005710 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5711 return;
John McCall2d8c7602010-03-20 04:12:52 +00005712 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005713 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5714}
5715
John McCalldf8b37c2010-03-22 09:20:08 +00005716/// \brief Check -Wshadow without the advantage of a previous lookup.
5717void Sema::CheckShadow(Scope *S, VarDecl *D) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005718 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005719 return;
5720
John McCalldf8b37c2010-03-22 09:20:08 +00005721 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5722 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5723 LookupName(R, S);
5724 CheckShadow(S, D, R);
5725}
5726
Richard Smithac974a32013-06-30 09:48:50 +00005727/// Check for conflict between this global or extern "C" declaration and
5728/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005729template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005730static bool checkGlobalOrExternCConflict(
5731 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5732 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5733 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005734
Richard Smithac974a32013-06-30 09:48:50 +00005735 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5736 // The common case: this global doesn't conflict with any extern "C"
5737 // declaration.
5738 return false;
5739 }
5740
5741 if (Prev) {
5742 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5743 // Both the old and new declarations have C language linkage. This is a
5744 // redeclaration.
5745 Previous.clear();
5746 Previous.addDecl(Prev);
5747 return true;
5748 }
5749
5750 // This is a global, non-extern "C" declaration, and there is a previous
5751 // non-global extern "C" declaration. Diagnose if this is a variable
5752 // declaration.
5753 if (!isa<VarDecl>(ND))
5754 return false;
5755 } else {
5756 // The declaration is extern "C". Check for any declaration in the
5757 // translation unit which might conflict.
5758 if (IsGlobal) {
5759 // We have already performed the lookup into the translation unit.
5760 IsGlobal = false;
5761 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5762 I != E; ++I) {
5763 if (isa<VarDecl>(*I)) {
5764 Prev = *I;
5765 break;
5766 }
5767 }
5768 } else {
5769 DeclContext::lookup_result R =
5770 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5771 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5772 I != E; ++I) {
5773 if (isa<VarDecl>(*I)) {
5774 Prev = *I;
5775 break;
5776 }
5777 // FIXME: If we have any other entity with this name in global scope,
5778 // the declaration is ill-formed, but that is a defect: it breaks the
5779 // 'stat' hack, for instance. Only variables can have mangled name
5780 // clashes with extern "C" declarations, so only they deserve a
5781 // diagnostic.
5782 }
5783 }
5784
5785 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005786 return false;
5787 }
5788
Richard Smithac974a32013-06-30 09:48:50 +00005789 // Use the first declaration's location to ensure we point at something which
5790 // is lexically inside an extern "C" linkage-spec.
5791 assert(Prev && "should have found a previous declaration to diagnose");
5792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005793 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005794 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005795 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005796
5797 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5798 << IsGlobal << ND;
5799 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5800 << IsGlobal;
5801 return false;
5802}
5803
5804/// Apply special rules for handling extern "C" declarations. Returns \c true
5805/// if we have found that this is a redeclaration of some prior entity.
5806///
5807/// Per C++ [dcl.link]p6:
5808/// Two declarations [for a function or variable] with C language linkage
5809/// with the same name that appear in different scopes refer to the same
5810/// [entity]. An entity with C language linkage shall not be declared with
5811/// the same name as an entity in global scope.
5812template<typename T>
5813static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5814 LookupResult &Previous) {
5815 if (!S.getLangOpts().CPlusPlus) {
5816 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005817 // variable declared in function scope. We don't need this in C++, because
5818 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005819 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5820 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5821 Previous.clear();
5822 Previous.addDecl(Prev);
5823 return true;
5824 }
5825 }
5826 return false;
5827 }
5828
5829 // A declaration in the translation unit can conflict with an extern "C"
5830 // declaration.
5831 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5832 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5833
5834 // An extern "C" declaration can conflict with a declaration in the
5835 // translation unit or can be a redeclaration of an extern "C" declaration
5836 // in another scope.
5837 if (isIncompleteDeclExternC(S,ND))
5838 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5839
5840 // Neither global nor extern "C": nothing to do.
5841 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005842}
5843
Richard Smith27d807c2013-04-30 13:56:41 +00005844void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005845 // If the decl is already known invalid, don't check it.
5846 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005847 return;
Mike Stump11289f42009-09-09 15:08:12 +00005848
Abramo Bagnara341ab732012-11-08 14:44:42 +00005849 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5850 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005851
Richard Smith27d807c2013-04-30 13:56:41 +00005852 // Defer checking an 'auto' type until its initializer is attached.
5853 if (T->isUndeducedType())
5854 return;
5855
Richard Smithdc4ccaa2014-03-27 01:22:48 +00005856 if (NewVD->hasAttrs())
5857 CheckAlignasUnderalignment(NewVD);
5858
John McCall8b07ec22010-05-15 11:32:37 +00005859 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005860 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5861 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005862 T = Context.getObjCObjectPointerType(T);
5863 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005864 }
Mike Stump11289f42009-09-09 15:08:12 +00005865
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005866 // Emit an error if an address space was applied to decl with local storage.
5867 // This includes arrays of objects with address space qualifiers, but not
5868 // automatic variables that point to other address spaces.
5869 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005870 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005871 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005872 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005873 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005874 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005875
Tanya Lattner713eef42013-04-05 20:14:50 +00005876 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5877 // __constant address space.
5878 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5879 && T.getAddressSpace() != LangAS::opencl_constant
5880 && !T->isSamplerT()){
5881 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5882 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005883 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005884 }
5885
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005886 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5887 // scope.
5888 if ((getLangOpts().OpenCLVersion >= 120)
5889 && NewVD->isStaticLocal()) {
5890 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5891 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005892 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005893 }
5894
Mike Stumpca5ae662009-04-14 00:57:29 +00005895 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005896 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005897 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005898 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005899 else {
5900 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005901 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005902 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005903 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005904
Chris Lattner9fecd742009-04-19 05:21:20 +00005905 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005906 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005907 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005908 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005909
Chris Lattner9fecd742009-04-19 05:21:20 +00005910 if ((isVM && NewVD->hasLinkage()) ||
5911 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005912 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005913 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005914 TypeSourceInfo *FixedTInfo =
5915 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5916 SizeIsNegative, Oversized);
Craig Topperc3ec1492014-05-26 06:22:03 +00005917 if (!FixedTInfo && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005918 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005919 // FIXME: This won't give the correct result for
5920 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005921 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005922
Anders Carlsson6c885802009-02-28 21:56:50 +00005923 if (NewVD->isFileVarDecl())
5924 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005925 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005926 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005927 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005928 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005929 else
5930 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005931 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005932 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005933 return;
Mike Stump11289f42009-09-09 15:08:12 +00005934 }
5935
Craig Topperc3ec1492014-05-26 06:22:03 +00005936 if (!FixedTInfo) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005937 if (NewVD->isFileVarDecl())
5938 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5939 else
5940 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005941 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005942 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005943 }
Mike Stump11289f42009-09-09 15:08:12 +00005944
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005945 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005946 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005947 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005948 }
5949
David Majnemer0ffa3312013-05-29 00:56:45 +00005950 if (T->isVoidType()) {
5951 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5952 // of objects and functions.
5953 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5954 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5955 << T;
5956 NewVD->setInvalidDecl();
5957 return;
5958 }
Richard Smith27d807c2013-04-30 13:56:41 +00005959 }
5960
5961 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5962 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5963 NewVD->setInvalidDecl();
5964 return;
5965 }
5966
5967 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5968 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5969 NewVD->setInvalidDecl();
5970 return;
5971 }
5972
5973 if (NewVD->isConstexpr() && !T->isDependentType() &&
5974 RequireLiteralType(NewVD->getLocation(), T,
5975 diag::err_constexpr_var_non_literal)) {
Richard Smith27d807c2013-04-30 13:56:41 +00005976 NewVD->setInvalidDecl();
5977 return;
5978 }
5979}
5980
5981/// \brief Perform semantic checking on a newly-created variable
5982/// declaration.
5983///
5984/// This routine performs all of the type-checking required for a
5985/// variable declaration once it has been built. It is used both to
5986/// check variables after they have been parsed and their declarators
5987/// have been translated into a declaration, and to check variables
5988/// that have been instantiated from a template.
5989///
5990/// Sets NewVD->isInvalidDecl() if an error was encountered.
5991///
5992/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005993bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00005994 CheckVariableDeclarationType(NewVD);
5995
5996 // If the decl is already known invalid, don't check it.
5997 if (NewVD->isInvalidDecl())
5998 return false;
5999
John McCallb65e8fe2013-04-01 18:34:28 +00006000 // If we did not find anything by this name, look for a non-visible
6001 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00006002 if (Previous.empty() &&
6003 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00006004 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006005
Douglas Gregor3552dab2013-01-09 00:47:56 +00006006 // Filter out any non-conflicting previous declarations.
6007 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6008
John McCall1f82f242009-11-18 22:49:29 +00006009 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00006010 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006011 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006012 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006013 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006014}
6015
Douglas Gregor36d1b142009-10-06 17:59:45 +00006016/// \brief Data used with FindOverriddenMethod
6017struct FindOverriddenMethodData {
6018 Sema *S;
6019 CXXMethodDecl *Method;
6020};
6021
6022/// \brief Member lookup function that determines whether a given C++
6023/// method overrides a method in a base class, to be used with
6024/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00006025static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00006026 CXXBasePath &Path,
6027 void *UserData) {
6028 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00006029
Douglas Gregor36d1b142009-10-06 17:59:45 +00006030 FindOverriddenMethodData *Data
6031 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00006032
6033 DeclarationName Name = Data->Method->getDeclName();
6034
6035 // FIXME: Do we care about other names here too?
6036 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00006037 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00006038 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6039 CanQualType CT = Data->S->Context.getCanonicalType(T);
6040
Anders Carlsson5a4f7722009-11-27 01:26:58 +00006041 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00006042 }
6043
6044 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006045 !Path.Decls.empty();
6046 Path.Decls = Path.Decls.slice(1)) {
6047 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00006048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6049 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00006050 return true;
6051 }
6052 }
6053
6054 return false;
6055}
6056
David Blaikie7e414262012-10-17 00:47:58 +00006057namespace {
6058 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6059}
6060/// \brief Report an error regarding overriding, along with any relevant
6061/// overriden methods.
6062///
6063/// \param DiagID the primary error to report.
6064/// \param MD the overriding method.
6065/// \param OEK which overrides to include as notes.
6066static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6067 OverrideErrorKind OEK = OEK_All) {
6068 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6069 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6070 E = MD->end_overridden_methods();
6071 I != E; ++I) {
6072 // This check (& the OEK parameter) could be replaced by a predicate, but
6073 // without lambdas that would be overkill. This is still nicer than writing
6074 // out the diag loop 3 times.
6075 if ((OEK == OEK_All) ||
6076 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6077 (OEK == OEK_Deleted && (*I)->isDeleted()))
6078 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6079 }
6080}
6081
Sebastian Redld5b24532009-11-18 21:51:29 +00006082/// AddOverriddenMethods - See if a method overrides any in the base classes,
6083/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006084bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00006085 // Look for virtual methods in base classes that this method might override.
6086 CXXBasePaths Paths;
6087 FindOverriddenMethodData Data;
6088 Data.Method = MD;
6089 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00006090 bool hasDeletedOverridenMethods = false;
6091 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006092 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00006093 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
Aaron Ballmane6f465e2014-03-14 21:38:48 +00006094 for (auto *I : Paths.found_decls()) {
6095 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00006096 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00006097 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00006098 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00006099 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00006100 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00006101 hasDeletedOverridenMethods |= OldMD->isDeleted();
6102 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006103 AddedAny = true;
6104 }
Sebastian Redld5b24532009-11-18 21:51:29 +00006105 }
6106 }
6107 }
David Blaikie7e414262012-10-17 00:47:58 +00006108
6109 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6110 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6111 }
6112 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6113 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6114 }
6115
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006116 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006117}
6118
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006119namespace {
6120 // Struct for holding all of the extra arguments needed by
6121 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6122 struct ActOnFDArgs {
6123 Scope *S;
6124 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006125 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006126 bool AddToScope;
6127 };
6128}
6129
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006130namespace {
6131
6132// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006133// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006134class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6135 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006136 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6137 CXXRecordDecl *Parent)
6138 : Context(Context), OriginalFD(TypoFD),
Craig Topperc3ec1492014-05-26 06:22:03 +00006139 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006140
Craig Toppere14c0f82014-03-12 04:55:44 +00006141 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006142 if (candidate.getEditDistance() == 0)
6143 return false;
6144
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006145 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006146 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6147 CDeclEnd = candidate.end();
6148 CDecl != CDeclEnd; ++CDecl) {
6149 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6150
6151 if (FD && !FD->hasBody() &&
6152 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6153 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6154 CXXRecordDecl *Parent = MD->getParent();
6155 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6156 return true;
6157 } else if (!ExpectedParent) {
6158 return true;
6159 }
6160 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006161 }
6162
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006163 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006164 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006165
6166 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006167 ASTContext &Context;
6168 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006169 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006170};
6171
6172}
6173
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006174/// \brief Generate diagnostics for an invalid function redeclaration.
6175///
6176/// This routine handles generating the diagnostic messages for an invalid
6177/// function redeclaration, including finding possible similar declarations
6178/// or performing typo correction if there are no previous declarations with
6179/// the same name.
6180///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006181/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006182/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006183static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006184 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006185 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006186 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006187 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006188 SmallVector<unsigned, 1> MismatchedParams;
6189 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006190 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006191 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006192 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6193 : diag::err_member_decl_does_not_match;
6194 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6195 IsLocalFriend ? Sema::LookupLocalFriendName
6196 : Sema::LookupOrdinaryName,
6197 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006198
6199 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006200 if (IsLocalFriend)
6201 SemaRef.LookupName(Prev, S);
6202 else
6203 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006204 assert(!Prev.isAmbiguous() &&
6205 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006206 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006207 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00006208 MD ? MD->getParent() : nullptr);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006209 if (!Prev.empty()) {
6210 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6211 Func != FuncEnd; ++Func) {
6212 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006213 if (FD &&
6214 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006215 // Add 1 to the index so that 0 can mean the mismatch didn't
6216 // involve a parameter
6217 unsigned ParamNum =
6218 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6219 NearMatches.push_back(std::make_pair(FD, ParamNum));
6220 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006221 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006222 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006223 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006224 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6225 &ExtraArgs.D.getCXXScopeSpec(), Validator,
Craig Topperc3ec1492014-05-26 06:22:03 +00006226 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006227 // Set up everything for the call to ActOnFunctionDeclarator
6228 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6229 ExtraArgs.D.getIdentifierLoc());
6230 Previous.clear();
6231 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006232 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6233 CDeclEnd = Correction.end();
6234 CDecl != CDeclEnd; ++CDecl) {
6235 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006236 if (FD && !FD->hasBody() &&
6237 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006238 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006239 }
6240 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006241 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006242
6243 NamedDecl *Result;
6244 // Retry building the function declaration with the new previous
6245 // declarations, and with errors suppressed.
6246 {
6247 // Trap errors.
6248 Sema::SFINAETrap Trap(SemaRef);
6249
6250 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6251 // pieces need to verify the typo-corrected C++ declaration and hopefully
6252 // eliminate the need for the parameter pack ExtraArgs.
6253 Result = SemaRef.ActOnFunctionDeclarator(
6254 ExtraArgs.S, ExtraArgs.D,
6255 Correction.getCorrectionDecl()->getDeclContext(),
6256 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6257 ExtraArgs.AddToScope);
6258
6259 if (Trap.hasErrorOccurred())
Craig Topperc3ec1492014-05-26 06:22:03 +00006260 Result = nullptr;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006261 }
Richard Smithf9b15102013-08-17 00:46:16 +00006262
6263 if (Result) {
6264 // Determine which correction we picked.
6265 Decl *Canonical = Result->getCanonicalDecl();
6266 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6267 I != E; ++I)
6268 if ((*I)->getCanonicalDecl() == Canonical)
6269 Correction.setCorrectionDecl(*I);
6270
6271 SemaRef.diagnoseTypo(
6272 Correction,
6273 SemaRef.PDiag(IsLocalFriend
6274 ? diag::err_no_matching_local_friend_suggest
6275 : diag::err_member_decl_does_not_match_suggest)
6276 << Name << NewDC << IsDefinition);
6277 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006278 }
Richard Smithf9b15102013-08-17 00:46:16 +00006279
6280 // Pretend the typo correction never occurred
6281 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6282 ExtraArgs.D.getIdentifierLoc());
6283 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6284 Previous.clear();
6285 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006286 }
6287
Richard Smithf9b15102013-08-17 00:46:16 +00006288 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6289 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006290
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006291 bool NewFDisConst = false;
6292 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006293 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006294
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006295 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006296 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6297 NearMatch != NearMatchEnd; ++NearMatch) {
6298 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006299 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6300 bool FDisConst = MD && MD->isConst();
6301 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006302
Richard Smith541b38b2013-09-20 01:15:31 +00006303 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006304 if (unsigned Idx = NearMatch->second) {
6305 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006306 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6307 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006308 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6309 : diag::note_local_decl_close_param_match)
6310 << Idx << FDParam->getType()
6311 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006312 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006313 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006314 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006315 } else
Richard Smith114394f2013-08-09 04:35:01 +00006316 SemaRef.Diag(FD->getLocation(),
6317 IsMember ? diag::note_member_def_close_match
6318 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006319 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006320 return nullptr;
John McCallf7cfb222010-10-13 05:45:15 +00006321}
6322
David Blaikie30d15442011-10-19 22:56:21 +00006323static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6324 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006325 switch (D.getDeclSpec().getStorageClassSpec()) {
6326 default: llvm_unreachable("Unknown storage class!");
6327 case DeclSpec::SCS_auto:
6328 case DeclSpec::SCS_register:
6329 case DeclSpec::SCS_mutable:
6330 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6331 diag::err_typecheck_sclass_func);
6332 D.setInvalidType();
6333 break;
6334 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006335 case DeclSpec::SCS_extern:
6336 if (D.getDeclSpec().isExternInLinkageSpec())
6337 return SC_None;
6338 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006339 case DeclSpec::SCS_static: {
6340 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6341 // C99 6.7.1p5:
6342 // The declaration of an identifier for a function that has
6343 // block scope shall have no explicit storage-class specifier
6344 // other than extern
6345 // See also (C++ [dcl.stc]p4).
6346 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6347 diag::err_static_block_func);
6348 break;
6349 } else
6350 return SC_Static;
6351 }
6352 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6353 }
6354
6355 // No explicit storage class has already been returned
6356 return SC_None;
6357}
6358
6359static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6360 DeclContext *DC, QualType &R,
6361 TypeSourceInfo *TInfo,
6362 FunctionDecl::StorageClass SC,
6363 bool &IsVirtualOkay) {
6364 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6365 DeclarationName Name = NameInfo.getName();
6366
Craig Topperc3ec1492014-05-26 06:22:03 +00006367 FunctionDecl *NewFD = nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006368 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006369
David Blaikiebbafb8a2012-03-11 07:00:24 +00006370 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006371 // Determine whether the function was written with a
6372 // prototype. This true when:
6373 // - there is a prototype in the declarator, or
6374 // - the type R of the function is some kind of typedef or other reference
6375 // to a type name (which eventually refers to a function type).
6376 bool HasPrototype =
6377 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6378 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6379
David Blaikie30d15442011-10-19 22:56:21 +00006380 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006381 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006382 TInfo, SC, isInline,
6383 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006384 if (D.isInvalidType())
6385 NewFD->setInvalidDecl();
6386
6387 // Set the lexical context.
6388 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6389
6390 return NewFD;
6391 }
6392
6393 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6394 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6395
6396 // Check that the return type is not an abstract class type.
6397 // For record types, this is done by the AbstractClassUsageDiagnoser once
6398 // the class has been completely parsed.
6399 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006400 SemaRef.RequireNonAbstractType(
6401 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6402 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006403 D.setInvalidType();
6404
6405 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6406 // This is a C++ constructor declaration.
6407 assert(DC->isRecord() &&
6408 "Constructors can only be declared in a member context");
6409
6410 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6411 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006412 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006413 R, TInfo, isExplicit, isInline,
6414 /*isImplicitlyDeclared=*/false,
6415 isConstexpr);
6416
6417 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6418 // This is a C++ destructor declaration.
6419 if (DC->isRecord()) {
6420 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6421 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6422 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6423 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006424 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006425 NameInfo, R, TInfo, isInline,
6426 /*isImplicitlyDeclared=*/false);
6427
6428 // If the class is complete, then we now create the implicit exception
6429 // specification. If the class is incomplete or dependent, we can't do
6430 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006431 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006432 Record->getDefinition() && !Record->isBeingDefined() &&
6433 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6434 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6435 }
6436
6437 IsVirtualOkay = true;
6438 return NewDD;
6439
6440 } else {
6441 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6442 D.setInvalidType();
6443
6444 // Create a FunctionDecl to satisfy the function definition parsing
6445 // code path.
6446 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006447 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006448 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006449 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006450 /*hasPrototype=*/true, isConstexpr);
6451 }
6452
6453 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6454 if (!DC->isRecord()) {
6455 SemaRef.Diag(D.getIdentifierLoc(),
6456 diag::err_conv_function_not_member);
Craig Topperc3ec1492014-05-26 06:22:03 +00006457 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006458 }
6459
6460 SemaRef.CheckConversionDeclarator(D, R, SC);
6461 IsVirtualOkay = true;
6462 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006463 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006464 R, TInfo, isInline, isExplicit,
6465 isConstexpr, SourceLocation());
6466
6467 } else if (DC->isRecord()) {
6468 // If the name of the function is the same as the name of the record,
6469 // then this must be an invalid constructor that has a return type.
6470 // (The parser checks for a return type and makes the declarator a
6471 // constructor if it has no return type).
6472 if (Name.getAsIdentifierInfo() &&
6473 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6474 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6475 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6476 << SourceRange(D.getIdentifierLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00006477 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006478 }
6479
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006480 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006481 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6482 cast<CXXRecordDecl>(DC),
6483 D.getLocStart(), NameInfo, R,
6484 TInfo, SC, isInline,
6485 isConstexpr, SourceLocation());
6486 IsVirtualOkay = !Ret->isStatic();
6487 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006488 } else {
6489 // Determine whether the function was written with a
6490 // prototype. This true when:
6491 // - we're in C++ (where every function has a prototype),
6492 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006493 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006494 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006495 true/*HasPrototype*/, isConstexpr);
6496 }
6497}
6498
Matt Arsenaultefb38192013-07-23 01:23:36 +00006499enum OpenCLParamType {
6500 ValidKernelParam,
6501 PtrPtrKernelParam,
6502 PtrKernelParam,
David Tweedababa8f2014-03-27 16:34:11 +00006503 PrivatePtrKernelParam,
Matt Arsenaultefb38192013-07-23 01:23:36 +00006504 InvalidKernelParam,
6505 RecordKernelParam
6506};
6507
6508static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6509 if (PT->isPointerType()) {
6510 QualType PointeeType = PT->getPointeeType();
David Tweedababa8f2014-03-27 16:34:11 +00006511 if (PointeeType->isPointerType())
6512 return PtrPtrKernelParam;
6513 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6514 : PtrKernelParam;
Matt Arsenaultefb38192013-07-23 01:23:36 +00006515 }
6516
6517 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6518 // be used as builtin types.
6519
6520 if (PT->isImageType())
6521 return PtrKernelParam;
6522
6523 if (PT->isBooleanType())
6524 return InvalidKernelParam;
6525
6526 if (PT->isEventT())
6527 return InvalidKernelParam;
6528
6529 if (PT->isHalfType())
6530 return InvalidKernelParam;
6531
6532 if (PT->isRecordType())
6533 return RecordKernelParam;
6534
6535 return ValidKernelParam;
6536}
6537
6538static void checkIsValidOpenCLKernelParameter(
6539 Sema &S,
6540 Declarator &D,
6541 ParmVarDecl *Param,
6542 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6543 QualType PT = Param->getType();
6544
6545 // Cache the valid types we encounter to avoid rechecking structs that are
6546 // used again
6547 if (ValidTypes.count(PT.getTypePtr()))
6548 return;
6549
6550 switch (getOpenCLKernelParameterType(PT)) {
6551 case PtrPtrKernelParam:
6552 // OpenCL v1.2 s6.9.a:
6553 // A kernel function argument cannot be declared as a
6554 // pointer to a pointer type.
6555 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6556 D.setInvalidType();
6557 return;
6558
David Tweedababa8f2014-03-27 16:34:11 +00006559 case PrivatePtrKernelParam:
6560 // OpenCL v1.2 s6.9.a:
6561 // A kernel function argument cannot be declared as a
6562 // pointer to the private address space.
6563 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6564 D.setInvalidType();
6565 return;
6566
Matt Arsenaultefb38192013-07-23 01:23:36 +00006567 // OpenCL v1.2 s6.9.k:
6568 // Arguments to kernel functions in a program cannot be declared with the
6569 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6570 // uintptr_t or a struct and/or union that contain fields declared to be
6571 // one of these built-in scalar types.
6572
6573 case InvalidKernelParam:
6574 // OpenCL v1.2 s6.8 n:
6575 // A kernel function argument cannot be declared
6576 // of event_t type.
6577 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6578 D.setInvalidType();
6579 return;
6580
6581 case PtrKernelParam:
6582 case ValidKernelParam:
6583 ValidTypes.insert(PT.getTypePtr());
6584 return;
6585
6586 case RecordKernelParam:
6587 break;
6588 }
6589
6590 // Track nested structs we will inspect
6591 SmallVector<const Decl *, 4> VisitStack;
6592
6593 // Track where we are in the nested structs. Items will migrate from
6594 // VisitStack to HistoryStack as we do the DFS for bad field.
6595 SmallVector<const FieldDecl *, 4> HistoryStack;
Craig Topperc3ec1492014-05-26 06:22:03 +00006596 HistoryStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006597
6598 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6599 VisitStack.push_back(PD);
6600
6601 assert(VisitStack.back() && "First decl null?");
6602
6603 do {
6604 const Decl *Next = VisitStack.pop_back_val();
6605 if (!Next) {
6606 assert(!HistoryStack.empty());
6607 // Found a marker, we have gone up a level
6608 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6609 ValidTypes.insert(Hist->getType().getTypePtr());
6610
6611 continue;
6612 }
6613
6614 // Adds everything except the original parameter declaration (which is not a
6615 // field itself) to the history stack.
6616 const RecordDecl *RD;
6617 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6618 HistoryStack.push_back(Field);
6619 RD = Field->getType()->castAs<RecordType>()->getDecl();
6620 } else {
6621 RD = cast<RecordDecl>(Next);
6622 }
6623
6624 // Add a null marker so we know when we've gone back up a level
Craig Topperc3ec1492014-05-26 06:22:03 +00006625 VisitStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006626
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006627 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006628 QualType QT = FD->getType();
6629
6630 if (ValidTypes.count(QT.getTypePtr()))
6631 continue;
6632
6633 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6634 if (ParamType == ValidKernelParam)
6635 continue;
6636
6637 if (ParamType == RecordKernelParam) {
6638 VisitStack.push_back(FD);
6639 continue;
6640 }
6641
6642 // OpenCL v1.2 s6.9.p:
6643 // Arguments to kernel functions that are declared to be a struct or union
6644 // do not allow OpenCL objects to be passed as elements of the struct or
6645 // union.
David Tweedababa8f2014-03-27 16:34:11 +00006646 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6647 ParamType == PrivatePtrKernelParam) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006648 S.Diag(Param->getLocation(),
6649 diag::err_record_with_pointers_kernel_param)
6650 << PT->isUnionType()
6651 << PT;
6652 } else {
6653 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6654 }
6655
6656 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6657 << PD->getDeclName();
6658
6659 // We have an error, now let's go back up through history and show where
6660 // the offending field came from
6661 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6662 E = HistoryStack.end(); I != E; ++I) {
6663 const FieldDecl *OuterField = *I;
6664 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6665 << OuterField->getType();
6666 }
6667
6668 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6669 << QT->isPointerType()
6670 << QT;
6671 D.setInvalidType();
6672 return;
6673 }
6674 } while (!VisitStack.empty());
6675}
6676
Mike Stump11289f42009-09-09 15:08:12 +00006677NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006678Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006679 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006680 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006681 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006682 QualType R = TInfo->getType();
6683
Zhongxing Xubece5d62009-01-16 01:13:29 +00006684 assert(R.getTypePtr()->isFunctionType());
6685
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006686 // TODO: consider using NameInfo for diagnostic.
6687 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6688 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006689 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006690
Richard Smithb4a9e862013-04-12 22:46:28 +00006691 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6692 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6693 diag::err_invalid_thread)
6694 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006695
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006696 if (D.isFirstDeclarationOfMember())
6697 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006698
Douglas Gregor513e63c2010-12-10 19:28:19 +00006699 bool isFriend = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00006700 FunctionTemplateDecl *FunctionTemplate = nullptr;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006701 bool isExplicitSpecialization = false;
6702 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006703
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006704 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006705 bool HasExplicitTemplateArgs = false;
6706 TemplateArgumentListInfo TemplateArgs;
6707
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006708 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006709
Richard Smith541b38b2013-09-20 01:15:31 +00006710 DeclContext *OriginalDC = DC;
6711 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6712
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006713 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6714 isVirtualOkay);
Craig Topperc3ec1492014-05-26 06:22:03 +00006715 if (!NewFD) return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006716
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006717 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6718 NewFD->setTopLevelDeclInObjCContainer();
6719
Richard Smith541b38b2013-09-20 01:15:31 +00006720 // Set the lexical context. If this is a function-scope declaration, or has a
6721 // C++ scope specifier, or is the object of a friend declaration, the lexical
6722 // context will be different from the semantic context.
6723 NewFD->setLexicalDeclContext(CurContext);
6724
6725 if (IsLocalExternDecl)
6726 NewFD->setLocalExternDecl();
6727
David Blaikiebbafb8a2012-03-11 07:00:24 +00006728 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006729 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006730 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6731 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006732 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006733 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006734 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006735 // C++ [class.friend]p5
6736 // A function can be defined in a friend declaration of a
6737 // class . . . . Such a function is implicitly inline.
6738 NewFD->setImplicitlyInline();
6739 }
6740
John McCalldb632ac2012-09-25 07:32:39 +00006741 // If this is a method defined in an __interface, and is not a constructor
6742 // or an overloaded operator, then set the pure flag (isVirtual will already
6743 // return true).
6744 if (const CXXRecordDecl *Parent =
6745 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6746 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006747 NewFD->setPure(true);
6748 }
6749
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006750 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006751 isExplicitSpecialization = false;
6752 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006753 if (D.isInvalidType())
6754 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006755
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006756 // Match up the template parameter lists with the scope specifier, then
6757 // determine whether we have a template or a template specialization.
6758 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006759 if (TemplateParameterList *TemplateParams =
6760 MatchTemplateParametersToScopeSpecifier(
6761 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00006762 D.getCXXScopeSpec(),
6763 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6764 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00006765 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006766 TemplateParamLists, isFriend, isExplicitSpecialization,
6767 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006768 if (TemplateParams->size() > 0) {
6769 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006770
Abramo Bagnara60804e12011-03-18 15:16:37 +00006771 // Check that we can declare a template here.
6772 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00006773 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006774
Abramo Bagnara60804e12011-03-18 15:16:37 +00006775 // A destructor cannot be a template.
6776 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6777 Diag(NewFD->getLocation(), diag::err_destructor_template);
Craig Topperc3ec1492014-05-26 06:22:03 +00006778 return nullptr;
John McCall1f0479e2010-03-24 08:27:58 +00006779 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006780
6781 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006782 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006783 // now that we know what the current instantiation is.
6784 if (DC->isDependentContext()) {
6785 ContextRAII SavedContext(*this, DC);
6786 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6787 Invalid = true;
6788 }
6789
John McCall1f0479e2010-03-24 08:27:58 +00006790
Abramo Bagnara60804e12011-03-18 15:16:37 +00006791 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6792 NewFD->getLocation(),
6793 Name, TemplateParams,
6794 NewFD);
6795 FunctionTemplate->setLexicalDeclContext(CurContext);
6796 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6797
6798 // For source fidelity, store the other template param lists.
6799 if (TemplateParamLists.size() > 1) {
6800 NewFD->setTemplateParameterListsInfo(Context,
6801 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006802 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006803 }
6804 } else {
6805 // This is a function template specialization.
6806 isFunctionTemplateSpecialization = true;
6807 // For source fidelity, store all the template param lists.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006808 if (TemplateParamLists.size() > 0)
6809 NewFD->setTemplateParameterListsInfo(Context,
6810 TemplateParamLists.size(),
6811 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006812
6813 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6814 if (isFriend) {
6815 // We want to remove the "template<>", found here.
6816 SourceRange RemoveRange = TemplateParams->getSourceRange();
6817
6818 // If we remove the template<> and the name is not a
6819 // template-id, we're actually silently creating a problem:
6820 // the friend declaration will refer to an untemplated decl,
6821 // and clearly the user wants a template specialization. So
6822 // we need to insert '<>' after the name.
6823 SourceLocation InsertLoc;
6824 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6825 InsertLoc = D.getName().getSourceRange().getEnd();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006826 InsertLoc = getLocForEndOfToken(InsertLoc);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006827 }
6828
6829 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6830 << Name << RemoveRange
6831 << FixItHint::CreateRemoval(RemoveRange)
6832 << FixItHint::CreateInsertion(InsertLoc, "<>");
6833 }
6834 }
6835 }
6836 else {
6837 // All template param lists were matched against the scope specifier:
6838 // this is NOT (an explicit specialization of) a template.
6839 if (TemplateParamLists.size() > 0)
6840 // For source fidelity, store all the template param lists.
6841 NewFD->setTemplateParameterListsInfo(Context,
6842 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006843 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006844 }
6845
6846 if (Invalid) {
6847 NewFD->setInvalidDecl();
6848 if (FunctionTemplate)
6849 FunctionTemplate->setInvalidDecl();
6850 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006851
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006852 // C++ [dcl.fct.spec]p5:
6853 // The virtual specifier shall only be used in declarations of
6854 // nonstatic class member functions that appear within a
6855 // member-specification of a class declaration; see 10.3.
6856 //
6857 if (isVirtual && !NewFD->isInvalidDecl()) {
6858 if (!isVirtualOkay) {
6859 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6860 diag::err_virtual_non_function);
6861 } else if (!CurContext->isRecord()) {
6862 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006863 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6864 diag::err_virtual_out_of_class)
6865 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6866 } else if (NewFD->getDescribedFunctionTemplate()) {
6867 // C++ [temp.mem]p3:
6868 // A member function template shall not be virtual.
6869 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6870 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006871 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6872 } else {
6873 // Okay: Add virtual to the method.
6874 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006875 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006876
6877 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006878 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006879 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006880 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006881
Richard Smithc1564702013-11-15 02:58:23 +00006882 if (getLangOpts().CPlusPlus1y &&
6883 (NewFD->isDependentContext() ||
6884 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006885 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006886 // If the function template is referenced directly (for instance, as a
6887 // member of the current instantiation), pretend it has a dependent type.
6888 // This is not really justified by the standard, but is the only sane
6889 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006890 // FIXME: For a friend function, we have not marked the function as being
6891 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006892 const FunctionProtoType *FPT =
6893 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006894 QualType Result =
6895 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006896 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006897 FPT->getExtProtoInfo()));
6898 }
6899
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006900 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006901 // The inline specifier shall not appear on a block scope function
6902 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006903 if (isInline && !NewFD->isInvalidDecl()) {
6904 if (CurContext->isFunctionOrMethod()) {
6905 // 'inline' is not allowed on block scope function declaration.
6906 Diag(D.getDeclSpec().getInlineSpecLoc(),
6907 diag::err_inline_declaration_block_scope) << Name
6908 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6909 }
6910 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006911
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006912 // C++ [dcl.fct.spec]p6:
6913 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006914 // constructor or conversion function within its class definition;
6915 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006916 if (isExplicit && !NewFD->isInvalidDecl()) {
6917 if (!CurContext->isRecord()) {
6918 // 'explicit' was specified outside of the class.
6919 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6920 diag::err_explicit_out_of_class)
6921 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6922 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6923 !isa<CXXConversionDecl>(NewFD)) {
6924 // 'explicit' was specified on a function that wasn't a constructor
6925 // or conversion function.
6926 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6927 diag::err_explicit_non_ctor_or_conv_function)
6928 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6929 }
6930 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006931
Richard Smitha77a0a62011-08-15 21:04:07 +00006932 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006933 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006934 // are implicitly inline.
6935 NewFD->setImplicitlyInline();
6936
Richard Smith574f4f62013-01-14 05:37:29 +00006937 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006938 // be either constructors or to return a literal type. Therefore,
6939 // destructors cannot be declared constexpr.
6940 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006941 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006942 }
6943
Douglas Gregor26701a42011-09-09 02:06:17 +00006944 // If __module_private__ was specified, mark the function accordingly.
6945 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006946 if (isFunctionTemplateSpecialization) {
6947 SourceLocation ModulePrivateLoc
6948 = D.getDeclSpec().getModulePrivateSpecLoc();
6949 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6950 << 0
6951 << FixItHint::CreateRemoval(ModulePrivateLoc);
6952 } else {
6953 NewFD->setModulePrivate();
6954 if (FunctionTemplate)
6955 FunctionTemplate->setModulePrivate();
6956 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006957 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006958
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006959 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006960 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006961 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006962 FunctionTemplate->setAccess(AS_public);
6963 }
Richard Smith64017682013-07-17 23:53:16 +00006964 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006965 NewFD->setAccess(AS_public);
6966 }
6967
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006968 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006969 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6970 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006971 switch (D.getFunctionDefinitionKind()) {
6972 case FDK_Declaration:
6973 case FDK_Definition:
6974 break;
6975
6976 case FDK_Defaulted:
6977 NewFD->setDefaulted();
6978 break;
6979
6980 case FDK_Deleted:
6981 NewFD->setDeletedAsWritten();
6982 break;
6983 }
6984
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006985 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6986 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006987 // C++ [class.mfct]p2:
6988 // A member function may be defined (8.4) in its class definition, in
6989 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00006990 NewFD->setImplicitlyInline();
6991 }
6992
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006993 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6994 !CurContext->isRecord()) {
6995 // C++ [class.static]p1:
6996 // A data or function member of a class may be declared static
6997 // in a class definition, in which case it is a static member of
6998 // the class.
6999
7000 // Complain about the 'static' specifier if it's on an out-of-line
7001 // member function definition.
7002 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7003 diag::err_static_out_of_line)
7004 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7005 }
Richard Smith66f3ac92012-10-20 08:26:51 +00007006
7007 // C++11 [except.spec]p15:
7008 // A deallocation function with no exception-specification is treated
7009 // as if it were specified with noexcept(true).
7010 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7011 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7012 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007013 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00007014 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7015 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00007016 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007017 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00007018 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007019 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007020
7021 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00007022 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00007023 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007024 isExplicitSpecialization ||
7025 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00007026
Zhongxing Xubece5d62009-01-16 01:13:29 +00007027 // Handle GNU asm-label extension (encoded as an attribute).
7028 if (Expr *E = (Expr*) D.getAsmLabel()) {
7029 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00007030 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007031 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00007032 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00007033 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7034 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7035 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7036 if (I != ExtnameUndeclaredIdentifiers.end()) {
7037 NewFD->addAttr(I->second);
7038 ExtnameUndeclaredIdentifiers.erase(I);
7039 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007040 }
7041
Chris Lattner9af40c12009-04-25 06:12:16 +00007042 // Copy the parameter declarations from the declarator D to the function
7043 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007044 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00007045 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00007047
Zhongxing Xubece5d62009-01-16 01:13:29 +00007048 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7049 // function that takes no arguments, not a function that takes a
7050 // single void argument.
7051 // We let through "const void" here because Sema::GetTypeForDeclarator
7052 // already checks for that case.
Alp Toker4284c6e2014-05-11 16:05:55 +00007053 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
Alp Tokerc5350722014-02-26 22:27:52 +00007054 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7055 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007056 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7057 Param->setDeclContext(NewFD);
7058 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00007059
7060 if (Param->isInvalidDecl())
7061 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007062 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007063 }
Mike Stump11289f42009-09-09 15:08:12 +00007064
John McCall9dd450b2009-09-21 23:43:11 +00007065 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00007066 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00007067 // following example, we'll need to synthesize (unnamed)
7068 // parameters for use in the declaration.
7069 //
7070 // @code
7071 // typedef void fn(int);
7072 // fn f;
7073 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00007074
Chris Lattner47c0d002009-04-25 06:03:53 +00007075 // Synthesize a parameter for each argument type.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007076 for (const auto &AI : FT->param_types()) {
John McCalla3ccba02010-06-04 11:21:44 +00007077 ParmVarDecl *Param =
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007078 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00007079 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00007080 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00007081 }
Chris Lattner49303b22009-04-25 18:38:18 +00007082 } else {
7083 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7084 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00007085 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00007086
Chris Lattner9af40c12009-04-25 06:12:16 +00007087 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00007088 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00007089
James Molloy6f8780b2012-02-29 10:24:19 +00007090 // Find all anonymous symbols defined during the declaration of this function
7091 // and add to NewFD. This lets us track decls such 'enum Y' in:
7092 //
7093 // void f(enum Y {AA} x) {}
7094 //
7095 // which would otherwise incorrectly end up in the translation unit scope.
7096 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7097 DeclsInPrototypeScope.clear();
7098
Richard Smithdebc59d2013-01-30 05:45:05 +00007099 if (D.getDeclSpec().isNoreturnSpecified())
7100 NewFD->addAttr(
7101 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00007102 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00007103
Richard Smith84208dc2012-03-13 05:56:40 +00007104 // Functions returning a variably modified type violate C99 6.7.5.2p2
7105 // because all functions have linkage.
7106 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00007107 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00007108 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7109 NewFD->setInvalidDecl();
7110 }
7111
Warren Huntc3b18962014-04-08 22:30:47 +00007112 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7113 !NewFD->hasAttr<SectionAttr>()) {
7114 NewFD->addAttr(
7115 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7116 CodeSegStack.CurrentValue->getString(),
7117 CodeSegStack.CurrentPragmaLocation));
7118 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7119 PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7120 NewFD->dropAttr<SectionAttr>();
7121 }
7122
Rafael Espindolac67f2232012-05-10 02:50:16 +00007123 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007124 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007125
Alp Toker314cc812014-01-25 16:55:45 +00007126 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007127 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7128 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7129 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7130 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007131 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00007132 // Attach WarnUnusedResult to functions returning types with that attribute.
7133 // Don't apply the attribute to that type's own non-static member functions
7134 // (to avoid warning on things like assignment operators)
7135 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00007136 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007137 }
7138
Joey Gouly16cb99d2014-01-06 11:26:18 +00007139 if (getLangOpts().OpenCL) {
7140 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7141 // type declaration will generate a compilation error.
7142 unsigned AddressSpace = RetType.getAddressSpace();
7143 if (AddressSpace == LangAS::opencl_local ||
7144 AddressSpace == LangAS::opencl_global ||
7145 AddressSpace == LangAS::opencl_constant) {
7146 Diag(NewFD->getLocation(),
7147 diag::err_opencl_return_value_with_address_space);
7148 NewFD->setInvalidDecl();
7149 }
7150 }
7151
David Blaikiebbafb8a2012-03-11 07:00:24 +00007152 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007153 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007154 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007155 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7156 CheckMain(NewFD, D.getDeclSpec());
7157
David Majnemerc729b0b2013-09-16 22:44:20 +00007158 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7159 CheckMSVCRTEntryPoint(NewFD);
7160
David Majnemer027f9c42013-07-06 02:13:46 +00007161 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007162 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7163 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007164 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007165 // Make graceful recovery from an invalid redeclaration.
7166 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007167 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007168 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7169 "previous declaration set still overloaded");
7170 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007171 // C++11 [replacement.functions]p3:
7172 // The program's definitions shall not be specified as inline.
7173 //
7174 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7175 //
7176 // Suppress the diagnostic if the function is __attribute__((used)), since
7177 // that forces an external definition to be emitted.
7178 if (D.getDeclSpec().isInlineSpecified() &&
7179 NewFD->isReplaceableGlobalAllocationFunction() &&
7180 !NewFD->hasAttr<UsedAttr>())
7181 Diag(D.getDeclSpec().getInlineSpecLoc(),
7182 diag::ext_operator_new_delete_declared_inline)
7183 << NewFD->getDeclName();
7184
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007185 // If the declarator is a template-id, translate the parser's template
7186 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007187 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7188 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7189 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7190 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007191 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007192 TemplateId->NumArgs);
7193 translateTemplateArguments(TemplateArgsPtr,
7194 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007195
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007196 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007197
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007198 if (NewFD->isInvalidDecl()) {
7199 HasExplicitTemplateArgs = false;
7200 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007201 // Function template with explicit template arguments.
7202 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7203 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7204
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007205 HasExplicitTemplateArgs = false;
John McCallf7cfb222010-10-13 05:45:15 +00007206 } else {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007207 assert((isFunctionTemplateSpecialization ||
7208 D.getDeclSpec().isFriendSpecified()) &&
7209 "should have a 'template<>' for this decl");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007210 // "friend void foo<>(int);" is an implicit specialization decl.
7211 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007212 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007213 } else if (isFriend && isFunctionTemplateSpecialization) {
7214 // This combination is only possible in a recovery case; the user
7215 // wrote something like:
7216 // template <> friend void foo(int);
7217 // which we're recovering from as if the user had written:
7218 // friend void foo<>(int);
7219 // Go ahead and fake up a template id.
7220 HasExplicitTemplateArgs = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00007221 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007222 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007223 }
John McCallf7cfb222010-10-13 05:45:15 +00007224
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007225 // If it's a friend (and only if it's a friend), it's possible
7226 // that either the specialized function type or the specialized
7227 // template is dependent, and therefore matching will fail. In
7228 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007229 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007230 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007231 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7232 TemplateSpecializationType::anyDependentTemplateArguments(
7233 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7234 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007235 assert(HasExplicitTemplateArgs &&
7236 "friend function specialization without template args");
7237 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7238 Previous))
7239 NewFD->setInvalidDecl();
7240 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007241 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007242 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007243 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007244 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007245 diag::ext_function_specialization_in_class :
7246 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007247 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007248 } else if (CheckFunctionTemplateSpecialization(NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00007249 (HasExplicitTemplateArgs ? &TemplateArgs
7250 : nullptr),
Douglas Gregor63fab342011-03-16 19:27:09 +00007251 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007252 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007253
7254 // C++ [dcl.stc]p1:
7255 // A storage-class-specifier shall not be specified in an explicit
7256 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007257 FunctionTemplateSpecializationInfo *Info =
7258 NewFD->getTemplateSpecializationInfo();
7259 if (Info && SC != SC_None) {
7260 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007261 Diag(NewFD->getLocation(),
7262 diag::err_explicit_specialization_inconsistent_storage_class)
7263 << SC
7264 << FixItHint::CreateRemoval(
7265 D.getDeclSpec().getStorageClassSpecLoc());
7266
7267 else
7268 Diag(NewFD->getLocation(),
7269 diag::ext_explicit_specialization_storage_class)
7270 << FixItHint::CreateRemoval(
7271 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007272 }
7273
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007274 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7275 if (CheckMemberSpecialization(NewFD, Previous))
7276 NewFD->setInvalidDecl();
7277 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007278
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007279 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007280 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007281 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7282 CheckMain(NewFD, D.getDeclSpec());
7283
David Majnemerc729b0b2013-09-16 22:44:20 +00007284 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7285 CheckMSVCRTEntryPoint(NewFD);
7286
Nico Weber7607fce2013-12-21 00:49:51 +00007287 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007288 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7289 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007290 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007291
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007292 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007293 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7294 "previous declaration set still overloaded");
7295
7296 NamedDecl *PrincipalDecl = (FunctionTemplate
7297 ? cast<NamedDecl>(FunctionTemplate)
7298 : NewFD);
7299
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007300 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007301 AccessSpecifier Access = AS_public;
7302 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007303 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007304
7305 NewFD->setAccess(Access);
7306 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007307 }
7308
7309 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7310 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7311 PrincipalDecl->setNonMemberOperator();
7312
7313 // If we have a function template, check the template parameter
7314 // list. This will check and merge default template arguments.
7315 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007316 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007317 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007318 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007319 PrevTemplate ? PrevTemplate->getTemplateParameters()
7320 : nullptr,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007321 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007322 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007323 ? TPC_FriendFunctionTemplateDefinition
7324 : TPC_FriendFunctionTemplate)
7325 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007326 DC && DC->isRecord() &&
7327 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007328 ? TPC_ClassTemplateMember
7329 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007330 }
7331
7332 if (NewFD->isInvalidDecl()) {
7333 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007334 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007335 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007336 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007337 // Fake up an access specifier if it's supposed to be a class member.
7338 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7339 NewFD->setAccess(AS_public);
7340
7341 // Qualified decls generally require a previous declaration.
7342 if (D.getCXXScopeSpec().isSet()) {
7343 // ...with the major exception of templated-scope or
7344 // dependent-scope friend declarations.
7345
7346 // TODO: we currently also suppress this check in dependent
7347 // contexts because (1) the parameter depth will be off when
7348 // matching friend templates and (2) we might actually be
7349 // selecting a friend based on a dependent factor. But there
7350 // are situations where these conditions don't apply and we
7351 // can actually do this check immediately.
7352 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007353 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007354 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7355 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007356 // ignore these
7357 } else {
7358 // The user tried to provide an out-of-line definition for a
7359 // function that is a member of a class or namespace, but there
7360 // was no such member function declared (C++ [class.mfct]p2,
7361 // C++ [namespace.memdef]p2). For example:
7362 //
7363 // class X {
7364 // void f() const;
7365 // };
7366 //
7367 // void X::f() { } // ill-formed
7368 //
7369 // Complain about this problem, and attempt to suggest close
7370 // matches (e.g., those that differ only in cv-qualifiers and
7371 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007372
Richard Smith114394f2013-08-09 04:35:01 +00007373 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
Craig Topperc3ec1492014-05-26 06:22:03 +00007374 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007375 AddToScope = ExtraArgs.AddToScope;
7376 return Result;
7377 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007378 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007379
7380 // Unqualified local friend declarations are required to resolve
7381 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007382 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007383 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7384 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007385 AddToScope = ExtraArgs.AddToScope;
7386 return Result;
7387 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007388 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007389
Richard Smitha2302242013-12-05 07:51:02 +00007390 } else if (!D.isFunctionDefinition() &&
7391 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007392 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007393 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007394 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007395 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007396 // Note that this is not the case for explicit specializations of
7397 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007398 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7399 // extension for compatibility with old SWIG code which likes to
7400 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007401 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7402 << D.getCXXScopeSpec().getRange();
7403 }
7404 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007405
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007406 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007407 checkAttributesAfterMerging(*this, *NewFD);
7408
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007409 AddKnownFunctionAttributes(NewFD);
7410
Douglas Gregor72609052010-08-06 13:50:58 +00007411 if (NewFD->hasAttr<OverloadableAttr>() &&
7412 !NewFD->getType()->getAs<FunctionProtoType>()) {
7413 Diag(NewFD->getLocation(),
7414 diag::err_attribute_overloadable_no_prototype)
7415 << NewFD;
7416
7417 // Turn this into a variadic function with no parameters.
7418 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007419 FunctionProtoType::ExtProtoInfo EPI(
7420 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007421 EPI.Variadic = true;
7422 EPI.ExtInfo = FT->getExtInfo();
7423
Alp Toker314cc812014-01-25 16:55:45 +00007424 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007425 NewFD->setType(R);
7426 }
7427
Eli Friedman570024a2010-08-05 06:57:20 +00007428 // If there's a #pragma GCC visibility in scope, and this isn't a class
7429 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007430 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007431 AddPushedVisibilityAttribute(NewFD);
7432
John McCall32f5fe12011-09-30 05:12:12 +00007433 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7434 // marking the function.
7435 AddCFAuditedAttribute(NewFD);
7436
Dario Domizioli13a0a382014-05-23 12:13:25 +00007437 // If this is a function definition, check if we have to apply optnone due to
7438 // a pragma.
7439 if(D.isFunctionDefinition())
7440 AddRangeBasedOptnone(NewFD);
7441
Richard Smithac974a32013-06-30 09:48:50 +00007442 // If this is the first declaration of an extern C variable, update
7443 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007444 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007445 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007446 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007447
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007448 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007449 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007450
Nico Rieck82f0b062014-03-31 14:56:15 +00007451 if (D.isRedeclaration() && !Previous.empty()) {
7452 checkDLLAttributeRedeclaration(
7453 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7454 isExplicitSpecialization || isFunctionTemplateSpecialization);
7455 }
7456
David Blaikiebbafb8a2012-03-11 07:00:24 +00007457 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007458 if (FunctionTemplate) {
7459 if (NewFD->isInvalidDecl())
7460 FunctionTemplate->setInvalidDecl();
7461 return FunctionTemplate;
7462 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007463 }
Mike Stump11289f42009-09-09 15:08:12 +00007464
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007465 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007466 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7467 if ((getLangOpts().OpenCLVersion >= 120)
7468 && (SC == SC_Static)) {
7469 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7470 D.setInvalidType();
7471 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007472
7473 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007474 if (!NewFD->getReturnType()->isVoidType()) {
Tanya Lattner0f864332013-01-30 19:48:52 +00007475 Diag(D.getIdentifierLoc(),
7476 diag::err_expected_kernel_void_return_type);
7477 D.setInvalidType();
7478 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007479
7480 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007481 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007482 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007483 }
7484
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007485 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007486
David Blaikiebbafb8a2012-03-11 07:00:24 +00007487 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007488 if (IdentifierInfo *II = NewFD->getIdentifier())
7489 if (!NewFD->isInvalidDecl() &&
7490 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7491 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007492 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007493 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7494
7495 Context.setcudaConfigureCallDecl(NewFD);
7496 }
7497 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007498
7499 // Here we have an function template explicit specialization at class scope.
7500 // The actually specialization will be postponed to template instatiation
7501 // time via the ClassScopeFunctionSpecializationDecl node.
7502 if (isDependentClassScopeExplicitSpecialization) {
7503 ClassScopeFunctionSpecializationDecl *NewSpec =
7504 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007505 Context, CurContext, SourceLocation(),
7506 cast<CXXMethodDecl>(NewFD),
7507 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007508 CurContext->addDecl(NewSpec);
7509 AddToScope = false;
7510 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007511
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007512 return NewFD;
7513}
7514
7515/// \brief Perform semantic checking of a new function declaration.
7516///
7517/// Performs semantic analysis of the new function declaration
7518/// NewFD. This routine performs all semantic checking that does not
7519/// require the actual declarator involved in the declaration, and is
7520/// used both for the declaration of functions as they are parsed
7521/// (called via ActOnDeclarator) and for the declaration of functions
7522/// that have been instantiated via C++ template instantiation (called
7523/// via InstantiateDecl).
7524///
James Dennettffad8b72012-06-22 08:10:18 +00007525/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007526/// an explicit specialization of the previous declaration.
7527///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007528/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007529///
James Dennettffad8b72012-06-22 08:10:18 +00007530/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007531bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007532 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007533 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007534 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7535 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007536
Richard Smith1c34fb72013-08-13 18:18:50 +00007537 // Determine whether the type of this function should be merged with
7538 // a previous visible declaration. This never happens for functions in C++,
7539 // and always happens in C if the previous declaration was visible.
7540 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7541 !Previous.isShadowed();
7542
Douglas Gregor3552dab2013-01-09 00:47:56 +00007543 // Filter out any non-conflicting previous declarations.
7544 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7545
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007546 bool Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007547 NamedDecl *OldDecl = nullptr;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007548
Douglas Gregore62c0a42009-02-24 01:23:02 +00007549 // Merge or overload the declaration with an existing declaration of
7550 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007551 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007552 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007553 // a declaration that requires merging. If it's an overload,
7554 // there's no more work to do here; we'll just add the new
7555 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007556 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007557 NamedDecl *Candidate = Previous.getFoundDecl();
7558 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7559 Redeclaration = true;
7560 OldDecl = Candidate;
7561 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007562 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007563 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7564 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007565 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007566 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007567 break;
7568
7569 case Ovl_NonFunction:
7570 Redeclaration = true;
7571 break;
7572
7573 case Ovl_Overload:
7574 Redeclaration = false;
7575 break;
John McCall1f82f242009-11-18 22:49:29 +00007576 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007577
David Blaikiebbafb8a2012-03-11 07:00:24 +00007578 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007579 // If a function name is overloadable in C, then every function
7580 // with that name must be marked "overloadable".
7581 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7582 << Redeclaration << NewFD;
Craig Topperc3ec1492014-05-26 06:22:03 +00007583 NamedDecl *OverloadedDecl = nullptr;
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007584 if (Redeclaration)
7585 OverloadedDecl = OldDecl;
7586 else if (!Previous.empty())
7587 OverloadedDecl = Previous.getRepresentativeDecl();
7588 if (OverloadedDecl)
7589 Diag(OverloadedDecl->getLocation(),
7590 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007591 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007592 }
John McCall1f82f242009-11-18 22:49:29 +00007593 }
Richard Smith574f4f62013-01-14 05:37:29 +00007594 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007595
Richard Smithac974a32013-06-30 09:48:50 +00007596 // Check for a previous extern "C" declaration with this name.
7597 if (!Redeclaration &&
7598 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7599 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7600 if (!Previous.empty()) {
7601 // This is an extern "C" declaration with the same name as a previous
7602 // declaration, and thus redeclares that entity...
7603 Redeclaration = true;
7604 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007605 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007606
7607 // ... except in the presence of __attribute__((overloadable)).
7608 if (OldDecl->hasAttr<OverloadableAttr>()) {
7609 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7610 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7611 << Redeclaration << NewFD;
7612 Diag(Previous.getFoundDecl()->getLocation(),
7613 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007614 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007615 }
7616 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7617 Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007618 OldDecl = nullptr;
Richard Smithac974a32013-06-30 09:48:50 +00007619 }
7620 }
7621 }
7622 }
7623
Richard Smith574f4f62013-01-14 05:37:29 +00007624 // C++11 [dcl.constexpr]p8:
7625 // A constexpr specifier for a non-static member function that is not
7626 // a constructor declares that member function to be const.
7627 //
7628 // This needs to be delayed until we know whether this is an out-of-line
7629 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007630 //
7631 // This rule is not present in C++1y, so we produce a backwards
7632 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007633 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007634 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7635 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007636 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007637 CXXMethodDecl *OldMD = nullptr;
Alp Tokera2794f92014-01-22 07:29:52 +00007638 if (OldDecl)
7639 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007640 if (!OldMD || !OldMD->isStatic()) {
7641 const FunctionProtoType *FPT =
7642 MD->getType()->castAs<FunctionProtoType>();
7643 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7644 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007645 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007646 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007647
7648 // Warn that we did this, if we're not performing template instantiation.
7649 // In that case, we'll have warned already when the template was defined.
7650 if (ActiveTemplateInstantiations.empty()) {
7651 SourceLocation AddConstLoc;
7652 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7653 .IgnoreParens().getAs<FunctionTypeLoc>())
Alp Tokerb6cc5922014-05-03 03:45:55 +00007654 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
Richard Smith034185c2013-04-21 01:08:50 +00007655
7656 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7657 << FixItHint::CreateInsertion(AddConstLoc, " const");
7658 }
Richard Smith574f4f62013-01-14 05:37:29 +00007659 }
7660 }
7661
7662 if (Redeclaration) {
7663 // NewFD and OldDecl represent declarations that need to be
7664 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007665 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007666 NewFD->setInvalidDecl();
7667 return Redeclaration;
7668 }
7669
7670 Previous.clear();
7671 Previous.addDecl(OldDecl);
7672
7673 if (FunctionTemplateDecl *OldTemplateDecl
7674 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7675 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7676 FunctionTemplateDecl *NewTemplateDecl
7677 = NewFD->getDescribedFunctionTemplate();
7678 assert(NewTemplateDecl && "Template/non-template mismatch");
7679 if (CXXMethodDecl *Method
7680 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7681 Method->setAccess(OldTemplateDecl->getAccess());
7682 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007683 }
Richard Smith574f4f62013-01-14 05:37:29 +00007684
7685 // If this is an explicit specialization of a member that is a function
7686 // template, mark it as a member specialization.
7687 if (IsExplicitSpecialization &&
7688 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7689 NewTemplateDecl->setMemberSpecialization();
7690 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007691 }
Richard Smith574f4f62013-01-14 05:37:29 +00007692
7693 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007694 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007695 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007696
7697 if (isa<CXXMethodDecl>(NewFD)) {
7698 // A valid redeclaration of a C++ method must be out-of-line,
7699 // but (unfortunately) it's not necessarily a definition
7700 // because of templates, which means that the previous
7701 // declaration is not necessarily from the class definition.
7702
7703 // For just setting the access, that doesn't matter.
7704 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7705 NewFD->setAccess(oldMethod->getAccess());
7706
7707 // Update the key-function state if necessary for this ABI.
7708 if (NewFD->isInlined() &&
7709 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7710 // setNonKeyFunction needs to work with the original
7711 // declaration from the class definition, and isVirtual() is
7712 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007713 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007714 if (oldMethod->isVirtual()) {
7715 Context.setNonKeyFunction(oldMethod);
7716 }
7717 }
7718 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007719 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007720 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007721
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007722 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007723 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007724 // C++-specific checks.
7725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7726 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007727 } else if (CXXDestructorDecl *Destructor =
7728 dyn_cast<CXXDestructorDecl>(NewFD)) {
7729 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007730 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007731
Douglas Gregor7454c562010-07-02 20:37:36 +00007732 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007733 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007734 if (!ClassType->isDependentType()) {
7735 DeclarationName Name
7736 = Context.DeclarationNames.getCXXDestructorName(
7737 Context.getCanonicalType(ClassType));
7738 if (NewFD->getDeclName() != Name) {
7739 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007740 NewFD->setInvalidDecl();
7741 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007742 }
7743 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007744 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007745 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007746 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007747 }
7748
7749 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7751 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007752 !Method->getDescribedFunctionTemplate() &&
7753 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007754 if (AddOverriddenMethods(Method->getParent(), Method)) {
7755 // If the function was marked as "static", we have a problem.
7756 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007757 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007758 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007759 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007760 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007761
7762 if (Method->isStatic())
7763 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007764 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007765
7766 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7767 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007768 CheckOverloadedOperatorDeclaration(NewFD)) {
7769 NewFD->setInvalidDecl();
7770 return Redeclaration;
7771 }
Alexis Huntc88db062010-01-13 09:01:02 +00007772
7773 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7774 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007775 CheckLiteralOperatorDeclaration(NewFD)) {
7776 NewFD->setInvalidDecl();
7777 return Redeclaration;
7778 }
Alexis Huntc88db062010-01-13 09:01:02 +00007779
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007780 // In C++, check default arguments now that we have merged decls. Unless
7781 // the lexical context is the class, because in this case this is done
7782 // during delayed parsing anyway.
7783 if (!CurContext->isRecord())
7784 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007785
Douglas Gregor9246b682010-12-21 19:47:46 +00007786 // If this function declares a builtin function, check the type of this
7787 // declaration against the expected type for the builtin.
7788 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7789 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007790 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007791 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7792 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7793 // The type of this function differs from the type of the builtin,
7794 // so forget about the builtin entirely.
7795 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7796 }
7797 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007798
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007799 // If this function is declared as being extern "C", then check to see if
7800 // the function returns a UDT (class, struct, or union type) that is not C
7801 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007802 // But, issue any diagnostic on the first declaration only.
7803 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007804 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007805 if (R->isIncompleteType() && !R->isVoidType())
7806 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7807 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007808 else if (!R.isPODType(Context) && !R->isVoidType() &&
7809 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007810 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007811 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007812 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007813 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007814}
7815
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007816static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7817 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7818 if (!TSI)
7819 return SourceRange();
7820
7821 TypeLoc TL = TSI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007822 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007823 if (!FunctionTL)
7824 return SourceRange();
7825
Alp Toker42a16a62014-01-25 23:51:36 +00007826 TypeLoc ResultTL = FunctionTL.getReturnLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007827 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007828 return ResultTL.getSourceRange();
7829
7830 return SourceRange();
7831}
7832
David Blaikied937bf12011-09-08 06:33:04 +00007833void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007834 // C++11 [basic.start.main]p3:
7835 // A program that [...] declares main to be inline, static or
7836 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007837 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7838 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007839 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007840 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007841 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007842 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007843 ? diag::err_static_main : diag::warn_static_main)
7844 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7845 if (FD->isInlineSpecified())
7846 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7847 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007848 if (DS.isNoreturnSpecified()) {
7849 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007850 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007851 Diag(NoreturnLoc, diag::ext_noreturn_main);
7852 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7853 << FixItHint::CreateRemoval(NoreturnRange);
7854 }
Richard Smith3f333f22012-02-04 06:10:17 +00007855 if (FD->isConstexpr()) {
7856 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7857 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7858 FD->setConstexpr(false);
7859 }
John McCall02dee0a2009-07-25 04:36:53 +00007860
Joey Goulya7310a82013-11-05 12:30:39 +00007861 if (getLangOpts().OpenCL) {
7862 Diag(FD->getLocation(), diag::err_opencl_no_main)
7863 << FD->hasAttr<OpenCLKernelAttr>();
7864 FD->setInvalidDecl();
7865 return;
7866 }
7867
John McCall02dee0a2009-07-25 04:36:53 +00007868 QualType T = FD->getType();
7869 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007870 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007871
John McCall5ed3caf2012-02-14 19:50:52 +00007872 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007873 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007874 // In C and C++, main magically returns 0 if you fall off the end;
7875 // set the flag which tells us that.
7876 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7877 FD->setHasImplicitReturnZero(true);
7878
7879 // In C with GNU extensions we allow main() to have non-integer return
7880 // type, but we should warn about the extension, and we disable the
7881 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007882 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007883 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7884
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007885 SourceRange ResultRange = getResultSourceRange(FD);
7886 if (ResultRange.isValid())
7887 Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7888 << FixItHint::CreateReplacement(ResultRange, "int");
7889
John McCall5ed3caf2012-02-14 19:50:52 +00007890 // Otherwise, this is just a flat-out error.
7891 } else {
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007892 SourceRange ResultRange = getResultSourceRange(FD);
7893 if (ResultRange.isValid())
7894 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7895 << FixItHint::CreateReplacement(ResultRange, "int");
7896 else
7897 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7898
John McCall02dee0a2009-07-25 04:36:53 +00007899 FD->setInvalidDecl(true);
7900 }
7901
7902 // Treat protoless main() as nullary.
7903 if (isa<FunctionNoProtoType>(FT)) return;
7904
7905 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007906 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007907 assert(FD->getNumParams() == nparams);
7908
John McCall0e21fcc2009-12-24 09:58:38 +00007909 bool HasExtraParameters = (nparams > 3);
7910
7911 // Darwin passes an undocumented fourth argument of type char**. If
7912 // other platforms start sprouting these, the logic below will start
7913 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007914 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007915 HasExtraParameters = false;
7916
7917 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007918 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7919 FD->setInvalidDecl(true);
7920 nparams = 3;
7921 }
7922
7923 // FIXME: a lot of the following diagnostics would be improved
7924 // if we had some location information about types.
7925
7926 QualType CharPP =
7927 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007928 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007929
7930 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007931 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007932
7933 bool mismatch = true;
7934
7935 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7936 mismatch = false;
7937 else if (Expected[i] == CharPP) {
7938 // As an extension, the following forms are okay:
7939 // char const **
7940 // char const * const *
7941 // char * const *
7942
John McCall8ccfcb52009-09-24 19:53:00 +00007943 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007944 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007945 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7946 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007947 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7948 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007949 qs.removeConst();
7950 mismatch = !qs.empty();
7951 }
7952 }
7953
7954 if (mismatch) {
7955 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7956 // TODO: suggest replacing given type with expected type
7957 FD->setInvalidDecl(true);
7958 }
7959 }
7960
7961 if (nparams == 1 && !FD->isInvalidDecl()) {
7962 Diag(FD->getLocation(), diag::warn_main_one_arg);
7963 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007964
7965 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007966 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007967 FD->setInvalidDecl();
7968 }
7969}
7970
7971void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7972 QualType T = FD->getType();
7973 assert(T->isFunctionType() && "function decl is not of function type");
7974 const FunctionType *FT = T->castAs<FunctionType>();
7975
7976 // Set an implicit return of 'zero' if the function can return some integral,
7977 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007978 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7979 FT->getReturnType()->isAnyPointerType() ||
7980 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007981 // DllMain is exempt because a return value of zero means it failed.
7982 if (FD->getName() != "DllMain")
7983 FD->setHasImplicitReturnZero(true);
7984
7985 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007986 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007987 FD->setInvalidDecl();
7988 }
John McCalld9baf6a2009-07-24 03:03:21 +00007989}
7990
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007991bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007992 // FIXME: Need strict checking. In C89, we need to check for
7993 // any assignment, increment, decrement, function-calls, or
7994 // commas outside of a sizeof. In C99, it's the same list,
7995 // except that the aforementioned are allowed in unevaluated
7996 // expressions. Everything else falls under the
7997 // "may accept other forms of constant expressions" exception.
7998 // (We never end up here for C++, so the constant expression
7999 // rules there don't matter.)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008000 const Expr *Culprit;
8001 if (Init->isConstantInitializer(Context, false, &Culprit))
Eli Friedman7bfab362009-02-22 06:45:27 +00008002 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00008003 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8004 << Culprit->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00008005 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00008006}
8007
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008008namespace {
8009 // Visits an initialization expression to see if OrigDecl is evaluated in
8010 // its own initialization and throws a warning if it does.
8011 class SelfReferenceChecker
8012 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8013 Sema &S;
8014 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008015 bool isRecordType;
8016 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008017 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008018
8019 public:
8020 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8021
8022 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00008023 S(S), OrigDecl(OrigDecl) {
8024 isPODType = false;
8025 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008026 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008027 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8028 isPODType = VD->getType().isPODType(S.Context);
8029 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00008030 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00008031 }
8032 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008033
Richard Trieu64c51ab2012-05-09 00:21:34 +00008034 // For most expressions, the cast is directly above the DeclRefExpr.
8035 // For conditional operators, the cast can be outside the conditional
8036 // operator if both expressions are DeclRefExpr's.
8037 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00008038 if (isReferenceType)
8039 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008040 E = E->IgnoreParenImpCasts();
8041 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8042 HandleDeclRefExpr(DRE);
8043 return;
8044 }
8045
8046 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8047 HandleValue(CO->getTrueExpr());
8048 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00008049 return;
8050 }
8051
8052 if (isa<MemberExpr>(E)) {
8053 Expr *Base = E->IgnoreParenImpCasts();
8054 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8055 // Check for static member variables and don't warn on them.
8056 if (!isa<FieldDecl>(ME->getMemberDecl()))
8057 return;
8058 Base = ME->getBase()->IgnoreParenImpCasts();
8059 }
8060 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8061 HandleDeclRefExpr(DRE);
8062 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008063 }
8064 }
8065
Richard Trieu32673472012-10-01 17:39:51 +00008066 // Reference types are handled here since all uses of references are
8067 // bad, not just r-value uses.
8068 void VisitDeclRefExpr(DeclRefExpr *E) {
8069 if (isReferenceType)
8070 HandleDeclRefExpr(E);
8071 }
8072
Richard Trieu64c51ab2012-05-09 00:21:34 +00008073 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00008074 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00008075 (isRecordType && E->getCastKind() == CK_NoOp))
8076 HandleValue(E->getSubExpr());
8077
8078 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008079 }
8080
Richard Trieua04ad1a2011-09-01 21:44:13 +00008081 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00008082 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00008083 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008084
Richard Trieu742c6ed2012-10-03 00:41:36 +00008085 // Warn when a non-static method call is followed by non-static member
8086 // field accesses, which is followed by a DeclRefExpr.
8087 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8088 bool Warn = (MD && !MD->isStatic());
8089 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8090 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8091 if (!isa<FieldDecl>(ME->getMemberDecl()))
8092 Warn = false;
8093 Base = ME->getBase()->IgnoreParenImpCasts();
8094 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008095
Richard Trieu742c6ed2012-10-03 00:41:36 +00008096 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8097 if (Warn)
8098 HandleDeclRefExpr(DRE);
8099 return;
8100 }
8101
8102 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8103 // Visit that expression.
8104 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008105 }
8106
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008107 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8108 if (E->getNumArgs() > 0)
8109 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8110 HandleDeclRefExpr(DRE);
8111
8112 Inherited::VisitCXXOperatorCallExpr(E);
8113 }
8114
Richard Trieua04ad1a2011-09-01 21:44:13 +00008115 void VisitUnaryOperator(UnaryOperator *E) {
8116 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008117 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8118 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8119 if (!isPODType)
8120 HandleValue(E->getSubExpr());
8121 return;
8122 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008123 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008124 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008125
8126 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8127
Richard Trieua04ad1a2011-09-01 21:44:13 +00008128 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008129 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008130 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008131 unsigned diag;
8132 if (isReferenceType) {
8133 diag = diag::warn_uninit_self_reference_in_reference_init;
8134 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8135 diag = diag::warn_static_self_reference_in_init;
8136 } else {
8137 diag = diag::warn_uninit_self_reference_in_init;
8138 }
8139
Richard Trieua04ad1a2011-09-01 21:44:13 +00008140 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008141 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008142 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008143 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008144 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008145 }
8146 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008147
Richard Trieu32673472012-10-01 17:39:51 +00008148 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8149 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8150 bool DirectInit) {
8151 // Parameters arguments are occassionially constructed with itself,
8152 // for instance, in recursive functions. Skip them.
8153 if (isa<ParmVarDecl>(OrigDecl))
8154 return;
8155
8156 E = E->IgnoreParens();
8157
8158 // Skip checking T a = a where T is not a record or reference type.
8159 // Doing so is a way to silence uninitialized warnings.
8160 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8161 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8162 if (ICE->getCastKind() == CK_LValueToRValue)
8163 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8164 if (DRE->getDecl() == OrigDecl)
8165 return;
8166
8167 SelfReferenceChecker(S, OrigDecl).Visit(E);
8168 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008169}
8170
Douglas Gregor5fb53972009-01-14 15:45:31 +00008171/// AddInitializerToDecl - Adds the initializer Init to the
8172/// declaration dcl. If DirectInit is true, this is C++ direct
8173/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008174void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8175 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008176 // If there is no declaration, there was an error parsing it. Just ignore
8177 // the initializer.
Craig Topperc3ec1492014-05-26 06:22:03 +00008178 if (!RealDecl || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008179 return;
Mike Stump11289f42009-09-09 15:08:12 +00008180
Douglas Gregor0c880302009-03-11 23:00:04 +00008181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8182 // With declarators parsed the way they are, the parser cannot
8183 // distinguish between a normal initializer and a pure-specifier.
8184 // Thus this grotesque test.
8185 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008186 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008187 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8188 CheckPureMethod(Method, Init->getSourceRange());
8189 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008190 Diag(Method->getLocation(), diag::err_member_function_initialization)
8191 << Method->getDeclName() << Init->getSourceRange();
8192 Method->setInvalidDecl();
8193 }
8194 return;
8195 }
8196
Steve Naroff437b4d82007-09-12 20:13:48 +00008197 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8198 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008199 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8200 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008201 RealDecl->setInvalidDecl();
8202 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008203 }
Sebastian Redla9351792012-02-11 23:51:47 +00008204 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8205
Richard Smith0cc85782011-12-15 19:20:59 +00008206 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008207 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008208 Expr *DeduceInit = Init;
8209 // Initializer could be a C++ direct-initializer. Deduction only works if it
8210 // contains exactly one expression.
8211 if (CXXDirectInit) {
8212 if (CXXDirectInit->getNumExprs() == 0) {
8213 // It isn't possible to write this directly, but it is possible to
8214 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008215 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008216 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8217 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008218 << VDecl->getDeclName() << VDecl->getType()
8219 << VDecl->getSourceRange();
8220 RealDecl->setInvalidDecl();
8221 return;
8222 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008223 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008224 VDecl->isInitCapture()
8225 ? diag::err_init_capture_multiple_expressions
8226 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008227 << VDecl->getDeclName() << VDecl->getType()
8228 << VDecl->getSourceRange();
8229 RealDecl->setInvalidDecl();
8230 return;
8231 } else {
8232 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008233 if (isa<InitListExpr>(DeduceInit))
8234 Diag(CXXDirectInit->getLocStart(),
8235 diag::err_auto_var_init_paren_braces)
8236 << VDecl->getDeclName() << VDecl->getType()
8237 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008238 }
8239 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008240
8241 // Expressions default to 'id' when we're in a debugger.
8242 bool DefaultedToAuto = false;
8243 if (getLangOpts().DebuggerCastResultToId &&
8244 Init->getType() == Context.UnknownAnyTy) {
8245 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8246 if (Result.isInvalid()) {
8247 VDecl->setInvalidDecl();
8248 return;
8249 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008250 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008251 DefaultedToAuto = true;
8252 }
Richard Smith061f1e22013-04-30 21:23:01 +00008253
8254 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008255 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008256 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008257 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008258 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008259 RealDecl->setInvalidDecl();
8260 return;
8261 }
Richard Smith061f1e22013-04-30 21:23:01 +00008262 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008263 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008264
John McCall31168b02011-06-15 23:02:42 +00008265 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008266 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008267 VDecl->setInvalidDecl();
8268
Jordan Rosed8d56692012-06-08 22:46:07 +00008269 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8270 // 'id' instead of a specific object type prevents most of our usual checks.
8271 // We only want to warn outside of template instantiations, though:
8272 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008273 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008274 DeducedType->isObjCIdType()) {
8275 SourceLocation Loc =
8276 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008277 Diag(Loc, diag::warn_auto_var_is_id)
8278 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8279 }
8280
Richard Smith30482bc2011-02-20 03:19:35 +00008281 // If this is a redeclaration, check that the type we just deduced matches
8282 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008283 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8284 // We never need to merge the type, because we cannot form an incomplete
8285 // array of auto, nor deduce such a type.
8286 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8287 }
Richard Smith27d807c2013-04-30 13:56:41 +00008288
8289 // Check the deduced type is valid for a variable declaration.
8290 CheckVariableDeclarationType(VDecl);
8291 if (VDecl->isInvalidDecl())
8292 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008293 }
Richard Smith0cc85782011-12-15 19:20:59 +00008294
Nico Rieck8e9791f2014-02-26 21:27:13 +00008295 // dllimport cannot be used on variable definitions.
8296 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8297 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8298 VDecl->setInvalidDecl();
8299 return;
8300 }
8301
Richard Smith0cc85782011-12-15 19:20:59 +00008302 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8303 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8304 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8305 VDecl->setInvalidDecl();
8306 return;
8307 }
8308
Sebastian Redla9351792012-02-11 23:51:47 +00008309 if (!VDecl->getType()->isDependentType()) {
8310 // A definition must end up with a complete type, which means it must be
8311 // complete with the restriction that an array type might be completed by
8312 // the initializer; note that later code assumes this restriction.
8313 QualType BaseDeclType = VDecl->getType();
8314 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8315 BaseDeclType = Array->getElementType();
8316 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8317 diag::err_typecheck_decl_incomplete_type)) {
8318 RealDecl->setInvalidDecl();
8319 return;
8320 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008321
Sebastian Redla9351792012-02-11 23:51:47 +00008322 // The variable can not have an abstract class type.
8323 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8324 diag::err_abstract_type_in_decl,
8325 AbstractVariableType))
8326 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008327 }
8328
Sebastian Redl5ca79842010-02-01 20:16:42 +00008329 const VarDecl *Def;
8330 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008331 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008332 << VDecl->getDeclName();
8333 Diag(Def->getLocation(), diag::note_previous_definition);
8334 VDecl->setInvalidDecl();
8335 return;
8336 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008337
8338 const VarDecl *PrevInit = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008339 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008340 // C++ [class.static.data]p4
8341 // If a static data member is of const integral or const
8342 // enumeration type, its declaration in the class definition can
8343 // specify a constant-initializer which shall be an integral
8344 // constant expression (5.19). In that case, the member can appear
8345 // in integral constant expressions. The member shall still be
8346 // defined in a namespace scope if it is used in the program and the
8347 // namespace scope definition shall not contain an initializer.
8348 //
8349 // We already performed a redefinition check above, but for static
8350 // data members we also need to check whether there was an in-class
8351 // declaration with an initializer.
8352 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008353 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8354 << VDecl->getDeclName();
8355 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008356 return;
8357 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008358
Douglas Gregor71f39c92010-12-16 01:31:22 +00008359 if (VDecl->hasLocalStorage())
8360 getCurFunction()->setHasBranchProtectedScope();
8361
8362 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8363 VDecl->setInvalidDecl();
8364 return;
8365 }
8366 }
John McCalld4e1b762010-08-01 01:24:59 +00008367
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008368 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8369 // a kernel function cannot be initialized."
8370 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8371 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8372 VDecl->setInvalidDecl();
8373 return;
8374 }
8375
Steve Naroff61091402007-09-12 14:07:44 +00008376 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008377 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008378 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008379
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008380 // Expressions default to 'id' when we're in a debugger
8381 // and we are assigning it to a variable of Objective-C pointer type.
8382 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8383 Init->getType() == Context.UnknownAnyTy) {
8384 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8385 if (Result.isInvalid()) {
8386 VDecl->setInvalidDecl();
8387 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008388 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008389 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008390 }
Richard Smith0cc85782011-12-15 19:20:59 +00008391
8392 // Perform the initialization.
8393 if (!VDecl->isInvalidDecl()) {
8394 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8395 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008396 = DirectInit ?
8397 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8398 Init->getLocStart(),
8399 Init->getLocEnd())
8400 : InitializationKind::CreateDirectList(
8401 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008402 : InitializationKind::CreateCopy(VDecl->getLocation(),
8403 Init->getLocStart());
8404
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008405 MultiExprArg Args = Init;
8406 if (CXXDirectInit)
8407 Args = MultiExprArg(CXXDirectInit->getExprs(),
8408 CXXDirectInit->getNumExprs());
8409
8410 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8411 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008412 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008413 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008414 return;
Steve Naroff61091402007-09-12 14:07:44 +00008415 }
Richard Smith0cc85782011-12-15 19:20:59 +00008416
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008417 Init = Result.getAs<Expr>();
Richard Smith0cc85782011-12-15 19:20:59 +00008418 }
8419
Richard Trieu32673472012-10-01 17:39:51 +00008420 // Check for self-references within variable initializers.
8421 // Variables declared within a function/method body (except for references)
8422 // are handled by a dataflow analysis.
8423 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8424 VDecl->getType()->isReferenceType()) {
8425 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8426 }
8427
Richard Smith0cc85782011-12-15 19:20:59 +00008428 // If the type changed, it means we had an incomplete type that was
8429 // completed by the initializer. For example:
8430 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008431 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008432 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008433 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008434
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008435 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008436 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8437
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008438 if (VDecl->hasAttr<BlocksAttr>())
8439 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008440
8441 // It is safe to assign a weak reference into a strong variable.
8442 // Although this code can still have problems:
8443 // id x = self.weakProp;
8444 // id y = self.weakProp;
8445 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8446 // paths through the function. This should be revisited if
8447 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008448 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8449 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8450 Init->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +00008451 getCurFunction()->markSafeWeakUse(Init);
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008452 }
8453
Richard Smith945f8d32013-01-14 22:39:08 +00008454 // The initialization is usually a full-expression.
8455 //
8456 // FIXME: If this is a braced initialization of an aggregate, it is not
8457 // an expression, and each individual field initializer is a separate
8458 // full-expression. For instance, in:
8459 //
8460 // struct Temp { ~Temp(); };
8461 // struct S { S(Temp); };
8462 // struct T { S a, b; } t = { Temp(), Temp() }
8463 //
8464 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008465 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8466 false,
8467 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008468 if (Result.isInvalid()) {
8469 VDecl->setInvalidDecl();
8470 return;
8471 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008472 Init = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00008473
Richard Smith0cc85782011-12-15 19:20:59 +00008474 // Attach the initializer to the decl.
8475 VDecl->setInit(Init);
8476
8477 if (VDecl->isLocalVarDecl()) {
8478 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8479 // static storage duration shall be constant expressions or string literals.
8480 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008481 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00008482 const Expr *Culprit;
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008483 if (VDecl->getStorageClass() == SC_Static)
8484 CheckForConstantInitializer(Init, DclT);
8485 // C89 is stricter than C99 for non-static aggregate types.
8486 // C89 6.5.7p3: All the expressions [...] in an initializer list
8487 // for an object that has aggregate or union type shall be
8488 // constant expressions.
8489 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008490 isa<InitListExpr>(Init) &&
Abramo Bagnara847c6602014-05-22 19:20:46 +00008491 !Init->isConstantInitializer(Context, false, &Culprit))
8492 Diag(Culprit->getExprLoc(),
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008493 diag::ext_aggregate_init_not_constant)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008494 << Culprit->getSourceRange();
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008495 }
Mike Stump11289f42009-09-09 15:08:12 +00008496 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008497 VDecl->getLexicalDeclContext()->isRecord()) {
8498 // This is an in-class initialization for a static data member, e.g.,
8499 //
8500 // struct S {
8501 // static const int value = 17;
8502 // };
8503
Douglas Gregor0c880302009-03-11 23:00:04 +00008504 // C++ [class.mem]p4:
8505 // A member-declarator can contain a constant-initializer only
8506 // if it declares a static member (9.4) of const integral or
8507 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008508 //
Richard Smith0cc85782011-12-15 19:20:59 +00008509 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008510 // If a non-volatile const static data member is of integral or
8511 // enumeration type, its declaration in the class definition can
8512 // specify a brace-or-equal-initializer in which every initalizer-clause
8513 // that is an assignment-expression is a constant expression. A static
8514 // data member of literal type can be declared in the class definition
8515 // with the constexpr specifier; if so, its declaration shall specify a
8516 // brace-or-equal-initializer in which every initializer-clause that is
8517 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008518
8519 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008520 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008521
Richard Smith2316cd82011-09-29 19:11:37 +00008522 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008523 // type. We separately check that every constexpr variable is of literal
8524 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008525 } else if (VDecl->isConstexpr()) {
8526
John McCalldb768922010-09-10 23:21:22 +00008527 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008528 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008529 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8530 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008531 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008532
8533 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008534 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008535 // Check whether the expression is a constant expression.
8536 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008537 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008538 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008539 // in-class initializer cannot be volatile.
8540 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8541 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008542 ; // Nothing to check.
8543 else if (Init->isIntegerConstantExpr(Context, &Loc))
8544 ; // Ok, it's an ICE!
8545 else if (Init->isEvaluatable(Context)) {
8546 // If we can constant fold the initializer through heroics, accept it,
8547 // but report this as a use of an extension for -pedantic.
8548 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8549 << Init->getSourceRange();
8550 } else {
8551 // Otherwise, this is some crazy unknown case. Report the issue at the
8552 // location provided by the isIntegerConstantExpr failed check.
8553 Diag(Loc, diag::err_in_class_initializer_non_constant)
8554 << Init->getSourceRange();
8555 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008556 }
8557
Richard Smith0cc85782011-12-15 19:20:59 +00008558 // We allow foldable floating-point constants as an extension.
8559 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008560 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8561 // it anyway and provide a fixit to add the 'constexpr'.
8562 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008563 Diag(VDecl->getLocation(),
8564 diag::ext_in_class_initializer_float_type_cxx11)
8565 << DclT << Init->getSourceRange();
8566 Diag(VDecl->getLocStart(),
8567 diag::note_in_class_initializer_float_type_cxx11)
8568 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008569 } else {
8570 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8571 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008572
Richard Smithcf656382013-01-25 04:22:16 +00008573 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8574 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8575 << Init->getSourceRange();
8576 VDecl->setInvalidDecl();
8577 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008578 }
Richard Smith256336d2011-09-29 23:18:34 +00008579
Richard Smith0cc85782011-12-15 19:20:59 +00008580 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008581 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008582 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008583 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008584 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8585 VDecl->setConstexpr(true);
8586
Richard Smith2316cd82011-09-29 19:11:37 +00008587 } else {
8588 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008589 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008590 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008591 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008592 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008593 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008594 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008595 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008596 VDecl->isExternC())) &&
8597 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008598 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008599
Richard Smith0cc85782011-12-15 19:20:59 +00008600 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008601 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008602 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00008603 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008604
Sebastian Redla9351792012-02-11 23:51:47 +00008605 // We will represent direct-initialization similarly to copy-initialization:
8606 // int x(1); -as-> int x = 1;
8607 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8608 //
8609 // Clients that want to distinguish between the two forms, can check for
8610 // direct initializer using VarDecl::getInitStyle().
8611 // A major benefit is that clients that don't particularly care about which
8612 // exactly form was it (like the CodeGen) can handle both cases without
8613 // special case code.
8614
8615 // C++ 8.5p11:
8616 // The form of initialization (using parentheses or '=') is generally
8617 // insignificant, but does matter when the entity being initialized has a
8618 // class type.
8619 if (CXXDirectInit) {
8620 assert(DirectInit && "Call-style initializer must be direct init.");
8621 VDecl->setInitStyle(VarDecl::CallInit);
8622 } else if (DirectInit) {
8623 // This must be list-initialization. No other way is direct-initialization.
8624 VDecl->setInitStyle(VarDecl::ListInit);
8625 }
8626
John McCall8b7fd8f12011-01-19 11:48:09 +00008627 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008628}
8629
John McCalleae5acb2010-03-31 02:13:20 +00008630/// ActOnInitializerError - Given that there was an error parsing an
8631/// initializer for the given declaration, try to return to some form
8632/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008633void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008634 // Our main concern here is re-establishing invariants like "a
8635 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008636 if (!D || D->isInvalidDecl()) return;
8637
8638 VarDecl *VD = dyn_cast<VarDecl>(D);
8639 if (!VD) return;
8640
Richard Smith30482bc2011-02-20 03:19:35 +00008641 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008642 if (ParsingInitForAutoVars.count(D)) {
8643 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008644 return;
8645 }
8646
John McCalleae5acb2010-03-31 02:13:20 +00008647 QualType Ty = VD->getType();
8648 if (Ty->isDependentType()) return;
8649
8650 // Require a complete type.
8651 if (RequireCompleteType(VD->getLocation(),
8652 Context.getBaseElementType(Ty),
8653 diag::err_typecheck_decl_incomplete_type)) {
8654 VD->setInvalidDecl();
8655 return;
8656 }
8657
Alp Toker48c7e172014-04-15 16:24:50 +00008658 // Require a non-abstract type.
John McCalleae5acb2010-03-31 02:13:20 +00008659 if (RequireNonAbstractType(VD->getLocation(), Ty,
8660 diag::err_abstract_type_in_decl,
8661 AbstractVariableType)) {
8662 VD->setInvalidDecl();
8663 return;
8664 }
8665
8666 // Don't bother complaining about constructors or destructors,
8667 // though.
8668}
8669
John McCall48871652010-08-21 09:40:31 +00008670void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008671 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008672 // If there is no declaration, there was an error parsing it. Just ignore it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008673 if (!RealDecl)
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008674 return;
8675
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008676 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8677 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008678
Richard Smithf0215fe2011-12-25 21:17:58 +00008679 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008680 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008681 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8682 << Var->getDeclName() << Type;
8683 Var->setInvalidDecl();
8684 return;
8685 }
Mike Stump11289f42009-09-09 15:08:12 +00008686
Richard Smithf0215fe2011-12-25 21:17:58 +00008687 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008688 // the constexpr specifier; if so, its declaration shall specify
8689 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008690 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8691 // the definition of a variable [...] or the declaration of a static data
8692 // member.
8693 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8694 if (Var->isStaticDataMember())
8695 Diag(Var->getLocation(),
8696 diag::err_constexpr_static_mem_var_requires_init)
8697 << Var->getDeclName();
8698 else
8699 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008700 Var->setInvalidDecl();
8701 return;
8702 }
8703
Joey Gouly96b94e62014-01-03 14:16:55 +00008704 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8705 // be initialized.
8706 if (!Var->isInvalidDecl() &&
8707 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008708 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008709 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8710 Var->setInvalidDecl();
8711 return;
8712 }
8713
Douglas Gregore6565622010-02-09 07:26:29 +00008714 switch (Var->isThisDeclarationADefinition()) {
8715 case VarDecl::Definition:
8716 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8717 break;
8718
8719 // We have an out-of-line definition of a static data member
8720 // that has an in-class initializer, so we type-check this like
8721 // a declaration.
8722 //
8723 // Fall through
8724
8725 case VarDecl::DeclarationOnly:
8726 // It's only a declaration.
8727
8728 // Block scope. C99 6.7p7: If an identifier for an object is
8729 // declared with no linkage (C99 6.2.2p6), the type for the
8730 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008731 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008732 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008733 RequireCompleteType(Var->getLocation(), Type,
8734 diag::err_typecheck_decl_incomplete_type))
8735 Var->setInvalidDecl();
8736
8737 // Make sure that the type is not abstract.
8738 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8739 RequireNonAbstractType(Var->getLocation(), Type,
8740 diag::err_abstract_type_in_decl,
8741 AbstractVariableType))
8742 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008743 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008744 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008745 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008746 Diag(Var->getLocation(), diag::note_private_extern);
8747 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008748
Douglas Gregore6565622010-02-09 07:26:29 +00008749 return;
8750
8751 case VarDecl::TentativeDefinition:
8752 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8753 // object that has file scope without an initializer, and without a
8754 // storage-class specifier or with the storage-class specifier "static",
8755 // constitutes a tentative definition. Note: A tentative definition with
8756 // external linkage is valid (C99 6.2.2p5).
8757 if (!Var->isInvalidDecl()) {
8758 if (const IncompleteArrayType *ArrayT
8759 = Context.getAsIncompleteArrayType(Type)) {
8760 if (RequireCompleteType(Var->getLocation(),
8761 ArrayT->getElementType(),
8762 diag::err_illegal_decl_array_incomplete_type))
8763 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008764 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008765 // C99 6.9.2p3: If the declaration of an identifier for an object is
8766 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8767 // declared type shall not be an incomplete type.
8768 // NOTE: code such as the following
8769 // static struct s;
8770 // struct s { int a; };
8771 // is accepted by gcc. Hence here we issue a warning instead of
8772 // an error and we do not invalidate the static declaration.
8773 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008774 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008775 RequireCompleteType(Var->getLocation(), Type,
8776 diag::ext_typecheck_decl_incomplete_type);
8777 }
8778 }
8779
8780 // Record the tentative definition; we're done.
8781 if (!Var->isInvalidDecl())
8782 TentativeDefinitions.push_back(Var);
8783 return;
8784 }
8785
8786 // Provide a specific diagnostic for uninitialized variable
8787 // definitions with incomplete array type.
8788 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008789 Diag(Var->getLocation(),
8790 diag::err_typecheck_incomplete_array_needs_initializer);
8791 Var->setInvalidDecl();
8792 return;
8793 }
8794
John McCalla755f0f2010-08-01 01:25:24 +00008795 // Provide a specific diagnostic for uninitialized variable
8796 // definitions with reference type.
8797 if (Type->isReferenceType()) {
8798 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8799 << Var->getDeclName()
8800 << SourceRange(Var->getLocation(), Var->getLocation());
8801 Var->setInvalidDecl();
8802 return;
8803 }
Douglas Gregore6565622010-02-09 07:26:29 +00008804
8805 // Do not attempt to type-check the default initializer for a
8806 // variable with dependent type.
8807 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008808 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008809
Douglas Gregore6565622010-02-09 07:26:29 +00008810 if (Var->isInvalidDecl())
8811 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008812
Douglas Gregore6565622010-02-09 07:26:29 +00008813 if (RequireCompleteType(Var->getLocation(),
8814 Context.getBaseElementType(Type),
8815 diag::err_typecheck_decl_incomplete_type)) {
8816 Var->setInvalidDecl();
8817 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008818 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008819
Douglas Gregore6565622010-02-09 07:26:29 +00008820 // The variable can not have an abstract class type.
8821 if (RequireNonAbstractType(Var->getLocation(), Type,
8822 diag::err_abstract_type_in_decl,
8823 AbstractVariableType)) {
8824 Var->setInvalidDecl();
8825 return;
8826 }
8827
Douglas Gregor9574af62011-05-21 17:52:48 +00008828 // Check for jumps past the implicit initializer. C++0x
8829 // clarifies that this applies to a "variable with automatic
8830 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008831 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008832 // A program that jumps from a point where a variable with automatic
8833 // storage duration is not in scope to a point where it is in scope is
8834 // ill-formed unless the variable has scalar type, class type with a
8835 // trivial default constructor and a trivial destructor, a cv-qualified
8836 // version of one of these types, or an array of one of the preceding
8837 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008838 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008839 if (const RecordType *Record
8840 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008841 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008842 // Mark the function for further checking even if the looser rules of
8843 // C++11 do not require such checks, so that we can diagnose
8844 // incompatibilities with C++98.
8845 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008846 getCurFunction()->setHasBranchProtectedScope();
8847 }
Douglas Gregore6565622010-02-09 07:26:29 +00008848 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008849
8850 // C++03 [dcl.init]p9:
8851 // If no initializer is specified for an object, and the
8852 // object is of (possibly cv-qualified) non-POD class type (or
8853 // array thereof), the object shall be default-initialized; if
8854 // the object is of const-qualified type, the underlying class
8855 // type shall have a user-declared default
8856 // constructor. Otherwise, if no initializer is specified for
8857 // a non- static object, the object and its subobjects, if
8858 // any, have an indeterminate initial value); if the object
8859 // or any of its subobjects are of const-qualified type, the
8860 // program is ill-formed.
8861 // C++0x [dcl.init]p11:
8862 // If no initializer is specified for an object, the object is
8863 // default-initialized; [...].
8864 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8865 InitializationKind Kind
8866 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008867
8868 InitializationSequence InitSeq(*this, Entity, Kind, None);
8869 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008870 if (Init.isInvalid())
8871 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008872 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008873 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008874 // This is important for template substitution.
8875 Var->setInitStyle(VarDecl::CallInit);
8876 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008877
John McCall8b7fd8f12011-01-19 11:48:09 +00008878 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008879 }
8880}
8881
Richard Smith02e85f32011-04-14 22:09:26 +00008882void Sema::ActOnCXXForRangeDecl(Decl *D) {
8883 VarDecl *VD = dyn_cast<VarDecl>(D);
8884 if (!VD) {
8885 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8886 D->setInvalidDecl();
8887 return;
8888 }
8889
8890 VD->setCXXForRangeDecl(true);
8891
8892 // for-range-declaration cannot be given a storage class specifier.
8893 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008894 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008895 case SC_None:
8896 break;
8897 case SC_Extern:
8898 Error = 0;
8899 break;
8900 case SC_Static:
8901 Error = 1;
8902 break;
8903 case SC_PrivateExtern:
8904 Error = 2;
8905 break;
8906 case SC_Auto:
8907 Error = 3;
8908 break;
8909 case SC_Register:
8910 Error = 4;
8911 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008912 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008913 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008914 }
Richard Smith2316cd82011-09-29 19:11:37 +00008915 if (VD->isConstexpr())
8916 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008917 if (Error != -1) {
8918 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8919 << VD->getDeclName() << Error;
8920 D->setInvalidDecl();
8921 }
8922}
8923
John McCall8b7fd8f12011-01-19 11:48:09 +00008924void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8925 if (var->isInvalidDecl()) return;
8926
John McCall31168b02011-06-15 23:02:42 +00008927 // In ARC, don't allow jumps past the implicit initialization of a
8928 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008929 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008930 var->hasLocalStorage()) {
8931 switch (var->getType().getObjCLifetime()) {
8932 case Qualifiers::OCL_None:
8933 case Qualifiers::OCL_ExplicitNone:
8934 case Qualifiers::OCL_Autoreleasing:
8935 break;
8936
8937 case Qualifiers::OCL_Weak:
8938 case Qualifiers::OCL_Strong:
8939 getCurFunction()->setHasBranchProtectedScope();
8940 break;
8941 }
8942 }
8943
John McCall8a4e2e42014-01-29 08:33:09 +00008944 // Warn about externally-visible variables being defined without a
8945 // prior declaration. We only want to do this for global
8946 // declarations, but we also specifically need to avoid doing it for
8947 // class members because the linkage of an anonymous class can
8948 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008949 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008950 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008951 var->isExternallyVisible() && var->hasLinkage() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008952 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
8953 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008954 // Find a previous declaration that's not a definition.
8955 VarDecl *prev = var->getPreviousDecl();
8956 while (prev && prev->isThisDeclarationADefinition())
8957 prev = prev->getPreviousDecl();
8958
8959 if (!prev)
8960 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8961 }
8962
Reid Kleckner92fc0172014-04-30 17:10:18 +00008963 if (var->getTLSKind() == VarDecl::TLS_Static) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00008964 const Expr *Culprit;
Reid Kleckner92fc0172014-04-30 17:10:18 +00008965 if (var->getType().isDestructedType()) {
8966 // GNU C++98 edits for __thread, [basic.start.term]p3:
8967 // The type of an object with thread storage duration shall not
8968 // have a non-trivial destructor.
8969 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8970 if (getLangOpts().CPlusPlus11)
8971 Diag(var->getLocation(), diag::note_use_thread_local);
8972 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
8973 !var->getInit()->isConstantInitializer(
Abramo Bagnara847c6602014-05-22 19:20:46 +00008974 Context, var->getType()->isReferenceType(), &Culprit)) {
Reid Kleckner92fc0172014-04-30 17:10:18 +00008975 // GNU C++98 edits for __thread, [basic.start.init]p4:
8976 // An object of thread storage duration shall not require dynamic
8977 // initialization.
8978 // FIXME: Need strict checking here.
Abramo Bagnara847c6602014-05-22 19:20:46 +00008979 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
8980 << Culprit->getSourceRange();
Reid Kleckner92fc0172014-04-30 17:10:18 +00008981 if (getLangOpts().CPlusPlus11)
8982 Diag(var->getLocation(), diag::note_use_thread_local);
8983 }
8984
Richard Smith6ea1a4d2013-04-14 20:11:31 +00008985 }
8986
Warren Huntc3b18962014-04-08 22:30:47 +00008987 if (var->isThisDeclarationADefinition() &&
8988 ActiveTemplateInstantiations.empty()) {
8989 PragmaStack<StringLiteral *> *Stack = nullptr;
8990 int SectionFlags = PSF_Implicit | PSF_Read;
8991 if (var->getType().isConstQualified())
8992 Stack = &ConstSegStack;
8993 else if (!var->getInit()) {
8994 Stack = &BSSSegStack;
8995 SectionFlags |= PSF_Write;
8996 } else {
8997 Stack = &DataSegStack;
8998 SectionFlags |= PSF_Write;
8999 }
9000 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9001 var->addAttr(
9002 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9003 Stack->CurrentValue->getString(),
9004 Stack->CurrentPragmaLocation));
9005 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9006 if (UnifySection(SA->getName(), SectionFlags, var))
9007 var->dropAttr<SectionAttr>();
9008 }
9009
John McCall8b7fd8f12011-01-19 11:48:09 +00009010 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009011 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009012
Richard Smithde63d362012-11-09 23:03:14 +00009013 QualType type = var->getType();
9014 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009015
9016 // __block variables might require us to capture a copy-initializer.
9017 if (var->hasAttr<BlocksAttr>()) {
9018 // It's currently invalid to ever have a __block variable with an
9019 // array type; should we diagnose that here?
9020
9021 // Regardless, we don't want to ignore array nesting when
9022 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00009023 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00009024 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00009025 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00009026 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00009027 ExprResult result
9028 = PerformMoveOrCopyInitialization(
9029 InitializedEntity::InitializeBlock(poi, type, false),
9030 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00009031 if (!result.isInvalid()) {
9032 result = MaybeCreateExprWithCleanups(result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009033 Expr *init = result.getAs<Expr>();
John McCall8b7fd8f12011-01-19 11:48:09 +00009034 Context.setBlockVarCopyInits(var, init);
9035 }
9036 }
9037 }
9038
Richard Smitheda3c842011-11-07 22:16:17 +00009039 Expr *Init = var->getInit();
9040 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00009041 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00009042
Richard Smithbf830092012-10-29 18:26:47 +00009043 if (!var->getDeclContext()->isDependentContext() &&
9044 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009045 if (IsGlobal && !var->isConstexpr() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009046 !getDiagnostics().isIgnored(diag::warn_global_constructor,
9047 var->getLocation())) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00009048 // Warn about globals which don't have a constant initializer. Don't
9049 // warn about globals with a non-trivial destructor because we already
9050 // warned about them.
9051 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9052 if (!(RD && !RD->hasTrivialDestructor()) &&
9053 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9054 Diag(var->getLocation(), diag::warn_global_constructor)
9055 << Init->getSourceRange();
9056 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00009057
Richard Smithd0b4dd62011-12-19 06:19:21 +00009058 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009059 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00009060 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9061 SourceLocation DiagLoc = var->getLocation();
9062 // If the note doesn't add any useful information other than a source
9063 // location, fold it into the primary diagnostic.
9064 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9065 diag::note_invalid_subexpr_in_const_expr) {
9066 DiagLoc = Notes[0].first;
9067 Notes.clear();
9068 }
9069 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9070 << var << Init->getSourceRange();
9071 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9072 Diag(Notes[I].first, Notes[I].second);
9073 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00009074 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009075 // Check whether the initializer of a const variable of integral or
9076 // enumeration type is an ICE now, since we can't tell whether it was
9077 // initialized by a constant expression if we check later.
9078 var->checkInitIsICE();
9079 }
Richard Smitheda3c842011-11-07 22:16:17 +00009080 }
John McCall8b7fd8f12011-01-19 11:48:09 +00009081
9082 // Require the destructor.
9083 if (const RecordType *recordType = baseType->getAs<RecordType>())
9084 FinalizeVarWithDestructor(var, recordType);
9085}
9086
Richard Smithb2bc2e62011-02-21 20:05:19 +00009087/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9088/// any semantic actions necessary after any initializer has been attached.
9089void
9090Sema::FinalizeDeclaration(Decl *ThisDecl) {
9091 // Note that we are no longer parsing the initializer for this declaration.
9092 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009093
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009094 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00009095 if (!VD)
9096 return;
9097
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00009098 checkAttributesAfterMerging(*this, *VD);
9099
Hans Wennborgef2272c2014-06-18 15:55:13 +00009100 // Static locals inherit dll attributes from their function.
9101 if (VD->isStaticLocal()) {
9102 if (FunctionDecl *FD =
9103 dyn_cast<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9104 if (Attr *A = getDLLAttr(FD)) {
9105 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9106 NewAttr->setInherited(true);
9107 VD->addAttr(NewAttr);
9108 }
9109 }
9110 }
9111
Nico Rieck078d2f82014-05-29 16:50:20 +00009112 // Imported static data members cannot be defined out-of-line.
9113 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) {
9114 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9115 VD->isThisDeclarationADefinition()) {
Hans Wennborge9af3162014-06-04 00:18:41 +00009116 // We allow definitions of dllimport class template static data members
9117 // with a warning.
Hans Wennborgcd959222014-06-09 18:30:28 +00009118 CXXRecordDecl *Context =
9119 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
Hans Wennborge9af3162014-06-04 00:18:41 +00009120 bool IsClassTemplateMember =
Hans Wennborgcd959222014-06-09 18:30:28 +00009121 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9122 Context->getDescribedClassTemplate();
Hans Wennborge9af3162014-06-04 00:18:41 +00009123
Nico Rieck078d2f82014-05-29 16:50:20 +00009124 Diag(VD->getLocation(),
Hans Wennborge9af3162014-06-04 00:18:41 +00009125 IsClassTemplateMember
9126 ? diag::warn_attribute_dllimport_static_field_definition
9127 : diag::err_attribute_dllimport_static_field_definition);
Nico Rieck078d2f82014-05-29 16:50:20 +00009128 Diag(IA->getLocation(), diag::note_attribute);
Hans Wennborge9af3162014-06-04 00:18:41 +00009129 if (!IsClassTemplateMember)
9130 VD->setInvalidDecl();
Nico Rieck078d2f82014-05-29 16:50:20 +00009131 }
9132 }
9133
Rafael Espindola87198cd2013-08-16 23:18:50 +00009134 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9135 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00009136 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00009137 VD->dropAttr<UsedAttr>();
9138 }
9139 }
9140
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009141 if (!VD->isInvalidDecl() &&
9142 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9143 if (const VarDecl *Def = VD->getDefinition()) {
9144 if (Def->hasAttr<AliasAttr>()) {
9145 Diag(VD->getLocation(), diag::err_tentative_after_alias)
9146 << VD->getDeclName();
9147 Diag(Def->getLocation(), diag::note_previous_definition);
9148 VD->setInvalidDecl();
9149 }
9150 }
9151 }
9152
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009153 const DeclContext *DC = VD->getDeclContext();
9154 // If there's a #pragma GCC visibility in scope, and this isn't a class
9155 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00009156 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009157 AddPushedVisibilityAttribute(VD);
9158
Richard Smithc3926172014-04-02 18:28:36 +00009159 // FIXME: Warn on unused templates.
Richard Smith6c6ef822014-04-25 19:21:40 +00009160 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9161 !isa<VarTemplatePartialSpecializationDecl>(VD))
Rafael Espindolad2ecc132013-01-03 04:29:20 +00009162 MarkUnusedFileScopedDecl(VD);
9163
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009164 // Now we have parsed the initializer and can update the table of magic
9165 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00009166 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9167 !VD->getType()->isIntegralOrEnumerationType())
9168 return;
9169
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00009170 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00009171 const Expr *MagicValueExpr = VD->getInit();
9172 if (!MagicValueExpr) {
9173 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009174 }
Rafael Espindola60470f12013-01-03 04:05:19 +00009175 llvm::APSInt MagicValueInt;
9176 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9177 Diag(I->getRange().getBegin(),
9178 diag::err_type_tag_for_datatype_not_ice)
9179 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9180 continue;
9181 }
9182 if (MagicValueInt.getActiveBits() > 64) {
9183 Diag(I->getRange().getBegin(),
9184 diag::err_type_tag_for_datatype_too_large)
9185 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9186 continue;
9187 }
9188 uint64_t MagicValue = MagicValueInt.getZExtValue();
9189 RegisterTypeTagForDatatype(I->getArgumentKind(),
9190 MagicValue,
9191 I->getMatchingCType(),
9192 I->getLayoutCompatible(),
9193 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009194 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009195}
9196
Rafael Espindolaab417692013-07-09 12:05:01 +00009197Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9198 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009199 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009200
9201 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009202 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009203
Craig Topperc3ec1492014-05-26 06:22:03 +00009204 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009205 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009206 if (Decl *D = Group[i]) {
9207 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9208 if (!FirstDeclaratorInGroup)
9209 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009210 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009211 }
Richard Smith2abf6762011-02-23 00:37:57 +00009212
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009213 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009214 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00009215 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00009216 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9217 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9218 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009219 }
David Blaikie095deba2012-11-14 01:52:05 +00009220
Rafael Espindolaab417692013-07-09 12:05:01 +00009221 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009222}
9223
9224/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9225/// group, performing any necessary semantic checking.
9226Sema::DeclGroupPtrTy
Rafael Espindolaab417692013-07-09 12:05:01 +00009227Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009228 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009229 // C++0x [dcl.spec.auto]p7:
9230 // If the type deduced for the template parameter U is not the same in each
9231 // deduction, the program is ill-formed.
9232 // FIXME: When initializer-list support is added, a distinction is needed
9233 // between the deduced type U and the deduced type which 'auto' stands for.
9234 // auto a = 0, b = { 1, 2, 3 };
9235 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009236 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009237 QualType Deduced;
9238 CanQualType DeducedCanon;
Craig Topperc3ec1492014-05-26 06:22:03 +00009239 VarDecl *DeducedDecl = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009240 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009241 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9242 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009243 // Don't reissue diagnostics when instantiating a template.
9244 if (AT && D->isInvalidDecl())
9245 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009246 QualType U = AT ? AT->getDeducedType() : QualType();
9247 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009248 CanQualType UCanon = Context.getCanonicalType(U);
9249 if (Deduced.isNull()) {
9250 Deduced = U;
9251 DeducedCanon = UCanon;
9252 DeducedDecl = D;
9253 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009254 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9255 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009256 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009257 << Deduced << DeducedDecl->getDeclName()
9258 << U << D->getDeclName()
9259 << DeducedDecl->getInit()->getSourceRange()
9260 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009261 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009262 break;
9263 }
9264 }
9265 }
9266 }
9267 }
9268
Rafael Espindolaab417692013-07-09 12:05:01 +00009269 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009270
Rafael Espindolaab417692013-07-09 12:05:01 +00009271 return DeclGroupPtrTy::make(
9272 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009273}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009274
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009275void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009276 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009277}
9278
Rafael Espindolaab417692013-07-09 12:05:01 +00009279void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009280 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009281 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009282 return;
9283
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009284 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009285 return;
9286
Rafael Espindolaab417692013-07-09 12:05:01 +00009287 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009288 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009289 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009290 // additional declaration references:
9291 // 'typedef struct S {} S;'
9292 // 'typedef struct S *S;'
9293 // 'struct S *pS;'
9294 // FinalizeDeclaratorGroup adds these as separate declarations.
9295 Decl *MaybeTagDecl = Group[0];
9296 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009297 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009298 }
9299 }
9300
9301 // See if there are any new comments that are not attached to a decl.
9302 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9303 if (!Comments.empty() &&
9304 !Comments.back()->isAttached()) {
9305 // There is at least one comment that not attached to a decl.
9306 // Maybe it should be attached to one of these decls?
9307 //
9308 // Note that this way we pick up not only comments that precede the
9309 // declaration, but also comments that *follow* the declaration -- thanks to
9310 // the lookahead in the lexer: we've consumed the semicolon and looked
9311 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009312 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009313 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009314 }
9315}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009316
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009317/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9318/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009319Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009320 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009321
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009322 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009323
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009324 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009325 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009326 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009327 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009328 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009329 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9330 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009331 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009332 Diag(DS.getStorageClassSpecLoc(),
9333 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009334 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009335 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009336
Richard Smithb4a9e862013-04-12 22:46:28 +00009337 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9338 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9339 << DeclSpec::getSpecifierName(TSCS);
9340 if (DS.isConstexprSpecified())
9341 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009342 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009343
Richard Smithb4a9e862013-04-12 22:46:28 +00009344 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009345
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009346 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009347 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009348
David Blaikiebbafb8a2012-03-11 07:00:24 +00009349 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009350 // Check that there are no default arguments inside the type of this
9351 // parameter.
9352 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009353
9354 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9355 if (D.getCXXScopeSpec().isSet()) {
9356 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9357 << D.getCXXScopeSpec().getRange();
9358 D.getCXXScopeSpec().clear();
9359 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009360 }
9361
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009362 // Ensure we have a valid name
Craig Topperc3ec1492014-05-26 06:22:03 +00009363 IdentifierInfo *II = nullptr;
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009364 if (D.hasName()) {
9365 II = D.getIdentifier();
9366 if (!II) {
9367 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009368 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009369 D.setInvalidType(true);
9370 }
9371 }
9372
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009373 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009374 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009375 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9376 ForRedeclaration);
9377 LookupName(R, S);
9378 if (R.isSingleResult()) {
9379 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009380 if (PrevDecl->isTemplateParameter()) {
9381 // Maybe we will complain about the shadowed template parameter.
9382 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9383 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00009384 PrevDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +00009385 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009386 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009387 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009388
Chris Lattnerd9773512009-01-21 02:38:50 +00009389 // Recover by removing the name
Craig Topperc3ec1492014-05-26 06:22:03 +00009390 II = nullptr;
9391 D.SetIdentifier(nullptr, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009392 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009393 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009394 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009395 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009396
John McCallf7b2fb52010-01-22 00:28:27 +00009397 // Temporarily put parameter variables in the translation unit, not
9398 // the enclosing context. This prevents them from accidentally
9399 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009400 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009401 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009402 D.getIdentifierLoc(), II,
9403 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009404 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009405
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009406 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009407 New->setInvalidDecl();
9408
9409 assert(S->isFunctionPrototypeScope());
9410 assert(S->getFunctionPrototypeDepth() >= 1);
9411 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9412 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009413
Douglas Gregor91f84212008-12-11 16:49:14 +00009414 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009415 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009416 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009417 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009418
Douglas Gregor758a8692009-06-17 21:51:59 +00009419 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009420
Douglas Gregor41866812011-09-12 18:37:38 +00009421 if (D.getDeclSpec().isModulePrivateSpecified())
9422 Diag(New->getLocation(), diag::err_module_private_local)
9423 << 1 << New->getDeclName()
9424 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9425 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9426
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009427 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009428 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9429 }
John McCall48871652010-08-21 09:40:31 +00009430 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009431}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009432
John McCalla3ccba02010-06-04 11:21:44 +00009433/// \brief Synthesizes a variable for a parameter arising from a
9434/// typedef.
9435ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9436 SourceLocation Loc,
9437 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009438 /* FIXME: setting StartLoc == Loc.
9439 Would it be worth to modify callers so as to provide proper source
9440 location for the unnamed parameters, embedding the parameter's type? */
Craig Topperc3ec1492014-05-26 06:22:03 +00009441 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
John McCalla3ccba02010-06-04 11:21:44 +00009442 T, Context.getTrivialTypeSourceInfo(T, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +00009443 SC_None, nullptr);
John McCalla3ccba02010-06-04 11:21:44 +00009444 Param->setImplicit();
9445 return Param;
9446}
9447
John McCallc5990642010-08-24 09:05:15 +00009448void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9449 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009450 // Don't diagnose unused-parameter errors in template instantiations; we
9451 // will already have done so in the template itself.
9452 if (!ActiveTemplateInstantiations.empty())
9453 return;
9454
9455 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009456 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009457 !(*Param)->hasAttr<UnusedAttr>()) {
9458 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9459 << (*Param)->getDeclName();
9460 }
9461 }
9462}
9463
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009464void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9465 ParmVarDecl * const *ParamEnd,
9466 QualType ReturnTy,
9467 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009468 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009469 return;
9470
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009471 // Warn if the return value is pass-by-value and larger than the specified
9472 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009473 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009474 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009475 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009476 Diag(D->getLocation(), diag::warn_return_value_size)
9477 << D->getDeclName() << Size;
9478 }
9479
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009480 // Warn if any parameter is pass-by-value and larger than the specified
9481 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009482 for (; Param != ParamEnd; ++Param) {
9483 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009484 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009485 continue;
9486 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009487 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009488 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9489 << (*Param)->getDeclName() << Size;
9490 }
9491}
9492
Abramo Bagnaradff19302011-03-08 08:55:46 +00009493ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9494 SourceLocation NameLoc, IdentifierInfo *Name,
9495 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009496 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009497 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009498 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009499 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009500 T->isObjCLifetimeType()) {
9501
9502 Qualifiers::ObjCLifetime lifetime;
9503
9504 // Special cases for arrays:
9505 // - if it's const, use __unsafe_unretained
9506 // - otherwise, it's an error
9507 if (T->isArrayType()) {
9508 if (!T.isConstQualified()) {
9509 DelayedDiagnostics.add(
9510 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009511 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009512 }
9513 lifetime = Qualifiers::OCL_ExplicitNone;
9514 } else {
9515 lifetime = T->getObjCARCImplicitLifetime();
9516 }
9517 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009518 }
9519
Abramo Bagnaradff19302011-03-08 08:55:46 +00009520 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009521 Context.getAdjustedParameterType(T),
9522 TSInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009523 StorageClass, nullptr);
Douglas Gregor940bca72010-04-12 07:48:19 +00009524
9525 // Parameters can not be abstract class types.
9526 // For record types, this is done by the AbstractClassUsageDiagnoser once
9527 // the class has been completely parsed.
9528 if (!CurContext->isRecord() &&
9529 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9530 AbstractParamType))
9531 New->setInvalidDecl();
9532
9533 // Parameter declarators cannot be interface types. All ObjC objects are
9534 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009535 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009536 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009537 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009538 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009539 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009540 T = Context.getObjCObjectPointerType(T);
9541 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009542 }
9543
9544 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9545 // duration shall not be qualified by an address-space qualifier."
9546 // Since all parameters have automatic store duration, they can not have
9547 // an address space.
9548 if (T.getAddressSpace() != 0) {
Fraser Cormack01648e02014-04-15 11:38:29 +00009549 // OpenCL allows function arguments declared to be an array of a type
9550 // to be qualified with an address space.
9551 if (!(getLangOpts().OpenCL && T->isArrayType())) {
9552 Diag(NameLoc, diag::err_arg_with_address_space);
9553 New->setInvalidDecl();
9554 }
Douglas Gregor940bca72010-04-12 07:48:19 +00009555 }
9556
9557 return New;
9558}
9559
Douglas Gregor170512f2009-04-01 23:51:29 +00009560void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9561 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009562 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009563
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009564 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9565 // for a K&R function.
9566 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009567 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009568 --i;
Craig Topperc3ec1492014-05-26 06:22:03 +00009569 if (FTI.Params[i].Param == nullptr) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009570 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009571 llvm::raw_svector_ostream(Code)
9572 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9573 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9574 << FTI.Params[i].Ident
9575 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009576
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009577 // Implicitly declare the argument as type 'int' for lack of a better
9578 // type.
John McCall084e83d2011-03-24 11:26:52 +00009579 AttributeFactory attrs;
9580 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009581 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009582 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009583 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9584 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009585 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009586 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9587 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009588 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009589 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9590 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009591 }
9592 }
Mike Stump11289f42009-09-09 15:08:12 +00009593 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009594}
9595
Richard Smith79a52e52012-04-17 22:30:01 +00009596Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009597 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009598 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009599 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009600
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009601 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009602 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009603 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009604}
9605
Hans Wennborga926d842014-05-23 20:37:38 +00009606void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
9607 Consumer.HandleInlineMethodDefinition(D);
9608}
9609
Anders Carlsson2a45e402012-12-18 01:29:20 +00009610static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9611 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009612 // Don't warn about invalid declarations.
9613 if (FD->isInvalidDecl())
9614 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009615
Anders Carlsson31c7e882009-12-09 03:30:09 +00009616 // Or declarations that aren't global.
9617 if (!FD->isGlobal())
9618 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009619
Anders Carlsson31c7e882009-12-09 03:30:09 +00009620 // Don't warn about C++ member functions.
9621 if (isa<CXXMethodDecl>(FD))
9622 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009623
Anders Carlsson31c7e882009-12-09 03:30:09 +00009624 // Don't warn about 'main'.
9625 if (FD->isMain())
9626 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009627
Anders Carlsson31c7e882009-12-09 03:30:09 +00009628 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009629 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009630 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009631
9632 // Don't warn about function templates.
9633 if (FD->getDescribedFunctionTemplate())
9634 return false;
9635
9636 // Don't warn about function template specializations.
9637 if (FD->isFunctionTemplateSpecialization())
9638 return false;
9639
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009640 // Don't warn for OpenCL kernels.
9641 if (FD->hasAttr<OpenCLKernelAttr>())
9642 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009643
Anders Carlsson31c7e882009-12-09 03:30:09 +00009644 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009645 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9646 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009647 // Ignore any declarations that occur in function or method
9648 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009649 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009650 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009651
Anders Carlsson31c7e882009-12-09 03:30:09 +00009652 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009653 if (FD->getNumParams() == 0)
9654 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009655 break;
9656 }
Richard Smith541b38b2013-09-20 01:15:31 +00009657
Anders Carlsson31c7e882009-12-09 03:30:09 +00009658 return MissingPrototype;
9659}
9660
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009661void
9662Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9663 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009664 // Don't complain if we're in GNU89 mode and the previous definition
9665 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009666 const FunctionDecl *Definition = EffectiveDefinition;
9667 if (!Definition)
9668 if (!FD->isDefined(Definition))
9669 return;
9670
9671 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009672 return;
9673
9674 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9675 Definition->getStorageClass() == SC_Extern)
9676 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009677 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009678 else
9679 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9680
9681 Diag(Definition->getLocation(), diag::note_previous_definition);
9682 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009683}
Faisal Valia17d19f2013-11-07 05:17:06 +00009684
9685
Faisal Valic1a6dc42013-10-23 16:10:50 +00009686static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9687 Sema &S) {
9688 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009689
9690 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009691 LSI->CallOperator = CallOperator;
9692 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009693 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009694 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9695
9696 if (LCD == LCD_None)
9697 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9698 else if (LCD == LCD_ByCopy)
9699 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9700 else if (LCD == LCD_ByRef)
9701 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9702 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9703
9704 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9705 LSI->Mutable = !CallOperator->isConst();
9706
Faisal Valia17d19f2013-11-07 05:17:06 +00009707 // Add the captures to the LSI so they can be noted as already
9708 // captured within tryCaptureVar.
Aaron Ballman6def98a2014-03-13 17:08:33 +00009709 for (const auto &C : LambdaClass->captures()) {
9710 if (C.capturesVariable()) {
9711 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +00009712 if (VD->isInitCapture())
9713 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9714 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +00009715 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +00009716 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +00009717 /*RefersToEnclosingLocal*/true, C.getLocation(),
9718 /*EllipsisLoc*/C.isPackExpansion()
9719 ? C.getEllipsisLoc() : SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009720 CaptureType, /*Expr*/ nullptr);
9721
Aaron Ballman6def98a2014-03-13 17:08:33 +00009722 } else if (C.capturesThis()) {
9723 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009724 S.getCurrentThisType(), /*Expr*/ nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00009725 }
9726 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009727}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009728
John McCall48871652010-08-21 09:40:31 +00009729Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009730 // Clear the last template instantiation error context.
9731 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9732
Douglas Gregor17a7c122009-06-24 00:54:41 +00009733 if (!D)
9734 return D;
Craig Topperc3ec1492014-05-26 06:22:03 +00009735 FunctionDecl *FD = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009736
John McCall48871652010-08-21 09:40:31 +00009737 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009738 FD = FunTmpl->getTemplatedDecl();
9739 else
John McCall48871652010-08-21 09:40:31 +00009740 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009741 // If we are instantiating a generic lambda call operator, push
9742 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009743 // that's already been calculated (ActOnLambdaExpr) to prime the current
9744 // LambdaScopeInfo.
9745 // When the template operator is being specialized, the LambdaScopeInfo,
9746 // has to be properly restored so that tryCaptureVariable doesn't try
9747 // and capture any new variables. In addition when calculating potential
9748 // captures during transformation of nested lambdas, it is necessary to
9749 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009750 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009751 assert(ActiveTemplateInstantiations.size() &&
9752 "There should be an active template instantiation on the stack "
9753 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009754 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009755 }
9756 else
9757 // Enter a new function scope
9758 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009759
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009760 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009761 if (!FD->isLateTemplateParsed())
9762 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009763
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009764 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009765 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009766 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9767 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009768 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009769 FD->setInvalidDecl();
9770 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009771 }
9772
Eli Friedman9ad72442009-03-04 07:30:59 +00009773 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009774 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009775 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009776 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009777 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009778 RequireCompleteType(FD->getLocation(), ResultType,
9779 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009780 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009781
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009782 // GNU warning -Wmissing-prototypes:
9783 // Warn if a global function is defined without a previous
9784 // prototype declaration. This warning is issued even if the
9785 // definition itself provides a prototype. The aim is to detect
9786 // global functions that fail to be declared in header files.
Craig Topperc3ec1492014-05-26 06:22:03 +00009787 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
Anders Carlsson2a45e402012-12-18 01:29:20 +00009788 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009789 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009790
Anders Carlsson2a45e402012-12-18 01:29:20 +00009791 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009792 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009793 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009794 if (TypeSourceInfo *TI =
9795 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9796 TypeLoc TL = TI->getTypeLoc();
9797 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9798 Diag(PossibleZeroParamPrototype->getLocation(),
9799 diag::note_declaration_not_a_prototype)
9800 << PossibleZeroParamPrototype
9801 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9802 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009803 }
9804 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009805
Douglas Gregor67da0d92009-05-15 17:59:04 +00009806 if (FnBodyScope)
9807 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009808
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009809 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009810 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9811 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009812
9813 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009814 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009815 Param->setOwningFunction(FD);
9816
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009817 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009818 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009819 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009820
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009821 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009822 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009823 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009824
James Molloy6f8780b2012-02-29 10:24:19 +00009825 // If we had any tags defined in the function prototype,
9826 // introduce them into the function scope.
9827 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009828 for (ArrayRef<NamedDecl *>::iterator
9829 I = FD->getDeclsInPrototypeScope().begin(),
9830 E = FD->getDeclsInPrototypeScope().end();
9831 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009832 NamedDecl *D = *I;
9833
9834 // Some of these decls (like enums) may have been pinned to the translation unit
9835 // for lack of a real context earlier. If so, remove from the translation unit
9836 // and reattach to the current context.
9837 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9838 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009839 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9840 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009841 Context.getTranslationUnitDecl()->removeDecl(D);
9842 break;
9843 }
9844 }
9845 // Either way, reassign the lexical decl context to our FunctionDecl.
9846 D->setLexicalDeclContext(CurContext);
9847 }
9848
9849 // If the decl has a non-null name, make accessible in the current scope.
9850 if (!D->getName().empty())
9851 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9852
9853 // Similarly, dive into enums and fish their constants out, making them
9854 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009855 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9856 for (auto *EI : ED->enumerators())
9857 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009858 }
9859 }
9860 }
9861
Richard Smith79a52e52012-04-17 22:30:01 +00009862 // Ensure that the function's exception specification is instantiated.
9863 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9864 ResolveExceptionSpec(D->getLocation(), FPT);
9865
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009866 // dllimport cannot be applied to non-inline function definitions.
Hans Wennborg7f26fa62014-05-19 20:14:13 +00009867 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
9868 !FD->isTemplateInstantiation()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009869 assert(!FD->hasAttr<DLLExportAttr>());
9870 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
9871 FD->setInvalidDecl();
9872 return D;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009873 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009874 // We want to attach documentation to original Decl (which might be
9875 // a function template).
9876 ActOnDocumentableDecl(D);
Fariborz Jahanian3451df82014-05-28 17:02:35 +00009877 if (getCurLexicalContext()->isObjCContainer() &&
9878 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
9879 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
9880 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
9881
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009882 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009883}
9884
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009885/// \brief Given the set of return statements within a function body,
9886/// compute the variables that are subject to the named return value
9887/// optimization.
9888///
9889/// Each of the variables that is subject to the named return value
9890/// optimization will be marked as NRVO variables in the AST, and any
9891/// return statement that has a marked NRVO variable as its NRVO candidate can
9892/// use the named return value optimization.
9893///
9894/// This function applies a very simplistic algorithm for NRVO: if every return
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009895/// statement in the scope of a variable has the same NRVO candidate, that
9896/// candidate is an NRVO variable.
Douglas Gregor49695f02011-09-06 20:46:03 +00009897void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009898 ReturnStmt **Returns = Scope->Returns.data();
9899
John McCallaab3e412010-08-25 08:40:02 +00009900 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009901 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
9902 if (!NRVOCandidate->isNRVOVariable())
9903 Returns[I]->setNRVOCandidate(nullptr);
9904 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009905 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009906}
9907
Richard Smith8e6002f2014-03-12 23:14:33 +00009908bool Sema::canDelayFunctionBody(const Declarator &D) {
9909 // We can't delay parsing the body of a constexpr function template (yet).
9910 if (D.getDeclSpec().isConstexprSpecified())
9911 return false;
9912
9913 // We can't delay parsing the body of a function template with a deduced
9914 // return type (yet).
9915 if (D.getDeclSpec().containsPlaceholderType()) {
9916 // If the placeholder introduces a non-deduced trailing return type,
9917 // we can still delay parsing it.
9918 if (D.getNumTypeObjects()) {
9919 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9920 if (Outer.Kind == DeclaratorChunk::Function &&
9921 Outer.Fun.hasTrailingReturnType()) {
9922 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9923 return Ty.isNull() || !Ty->isUndeducedType();
9924 }
9925 }
9926 return false;
9927 }
9928
9929 return true;
9930}
9931
Richard Smith1ab34b32012-11-19 21:13:18 +00009932bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009933 // We cannot skip the body of a function (or function template) which is
9934 // constexpr, since we may need to evaluate its body in order to parse the
9935 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009936 // We cannot skip the body of a function with an undeduced return type,
9937 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009938 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009939 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009940 return false;
9941 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009942}
9943
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009944Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009945 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009946 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009947 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009948 MD->setHasSkippedBody();
Craig Topperc3ec1492014-05-26 06:22:03 +00009949 return ActOnFinishFunctionBody(Decl, nullptr);
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009950}
9951
John McCallfaf5fb42010-08-26 23:41:50 +00009952Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009953 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009954}
9955
John McCallb268a282010-08-23 23:25:46 +00009956Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9957 bool IsInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009958 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009959
Ted Kremenek0b405322010-03-23 00:13:23 +00009960 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Craig Topperc3ec1492014-05-26 06:22:03 +00009961 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
Ted Kremenek918fe842010-03-20 21:06:02 +00009962
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009963 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00009964 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +00009965
Richard Smith7500ab22013-05-10 04:31:10 +00009966 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +00009967 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009968 // If the function has a deduced result type but contains no 'return'
9969 // statements, the result type as written must be exactly 'auto', and
9970 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +00009971 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +00009972 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +00009973 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +00009974 FD->setInvalidDecl();
9975 } else {
9976 // Substitute 'void' for the 'auto' in the type.
9977 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +00009978 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +00009979 Context.adjustDeducedFunctionResultType(
9980 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +00009981 }
9982 }
9983
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009984 // The only way to be included in UndefinedButUsed is if there is an
9985 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009986 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00009987 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009988 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00009989 UndefinedButUsed.erase(FD);
9990 else if (FD->isInlined() &&
9991 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9992 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9993 UndefinedButUsed.erase(FD);
9994 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +00009995
John McCall5ed3caf2012-02-14 19:50:52 +00009996 // If the function implicitly returns zero (like 'main') or is naked,
9997 // don't complain about missing return statements.
9998 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +00009999 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +000010000
Francois Pichet3abc9b82011-05-11 02:14:46 +000010001 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +000010002 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +000010003 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +000010004 Diag(FD->getLocation(), diag::warn_pure_function_definition);
10005
Douglas Gregor88d292c2010-05-13 16:44:06 +000010006 if (!FD->isInvalidDecl()) {
Reid Kleckner121b1a12014-04-30 16:31:28 +000010007 // Don't diagnose unused parameters of defaulted or deleted functions.
10008 if (Body)
10009 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010010 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010011 FD->getReturnType(), FD);
10012
Douglas Gregor88d292c2010-05-13 16:44:06 +000010013 // If this is a constructor, we need a vtable.
10014 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10015 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010016
Jordan Rosed39e5f12012-07-02 21:19:23 +000010017 // Try to apply the named return value optimization. We have to check
10018 // if we can do this here because lambdas keep return statements around
10019 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +000010020 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +000010021 !FD->isDependentContext())
10022 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +000010023 }
10024
Douglas Gregor21f46922012-02-08 20:17:14 +000010025 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10026 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +000010027 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +000010028 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +000010029 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010030 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010031 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010032 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010033 MD->getReturnType(), MD);
10034
Douglas Gregore3f3ea02011-09-06 20:33:37 +000010035 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +000010036 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010037 }
Jordan Rose2afd6612012-10-19 16:05:26 +000010038 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +000010039 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10040 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +000010041 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +000010042 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010043 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010044 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +000010045 bool isDesignated =
10046 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010047 assert(isDesignated && InitMethod);
10048 (void)isDesignated;
Argyrios Kyrtzidisde103662014-04-16 18:32:51 +000010049
10050 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10051 auto IFace = MD->getClassInterface();
10052 if (!IFace)
10053 return false;
10054 auto SuperD = IFace->getSuperClass();
10055 if (!SuperD)
10056 return false;
10057 return SuperD->getIdentifier() ==
10058 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10059 };
10060 // Don't issue this warning for unavailable inits or direct subclasses
10061 // of NSObject.
10062 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010063 Diag(MD->getLocation(),
10064 diag::warn_objc_designated_init_missing_super_call);
10065 Diag(InitMethod->getLocation(),
10066 diag::note_objc_designated_init_marked_here);
10067 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010068 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10069 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010070 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010071 // Don't issue this warning for unavaialable inits.
10072 if (!MD->isUnavailable())
10073 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010074 getCurFunction()->ObjCWarnForNoInitDelegation = false;
10075 }
Ted Kremenek5a201952009-02-07 01:47:29 +000010076 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +000010077 return nullptr;
Ted Kremenek5a201952009-02-07 01:47:29 +000010078 }
Douglas Gregor67da0d92009-05-15 17:59:04 +000010079
Jordan Rose2afd6612012-10-19 16:05:26 +000010080 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +000010081 "This should only be set for ObjC methods, which should have been "
10082 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +000010083
Chris Lattnere2473062007-05-28 06:28:18 +000010084 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +000010085 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000010086 // C++ constructors that have function-try-blocks can't have return
10087 // statements in the handlers of that block. (C++ [except.handle]p14)
10088 // Verify this.
10089 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10090 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10091
Richard Smithdef8bdb2011-08-12 18:44:32 +000010092 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +000010093 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000010094 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +000010095 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +000010096
John McCalldeb646e2010-08-04 01:04:25 +000010097 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10098 if (!Destructor->getParent()->isDependentType())
10099 CheckDestructor(Destructor);
10100
John McCalla6309952010-03-16 21:39:52 +000010101 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10102 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +000010103 }
Douglas Gregor9a28e842010-03-01 23:15:13 +000010104
10105 // If any errors have occurred, clear out any temporaries that may have
10106 // been leftover. This ensures that these temporaries won't be picked up for
10107 // deletion in some later function.
Alp Tokerb6cc5922014-05-03 03:45:55 +000010108 if (getDiagnostics().hasErrorOccurred() ||
10109 getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +000010110 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010111 }
Alp Tokerb6cc5922014-05-03 03:45:55 +000010112 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010113 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +000010114 // Since the body is valid, issue any analysis-based warnings that are
10115 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +000010116 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +000010117 }
10118
Richard Smith3607ffe2012-02-13 03:54:03 +000010119 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10120 (!CheckConstexprFunctionDecl(FD) ||
10121 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +000010122 FD->setInvalidDecl();
10123
John McCall28fc7092011-11-10 05:35:25 +000010124 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +000010125 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +000010126 assert(MaybeODRUseExprs.empty() &&
10127 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +000010128 }
10129
John McCalle99d5f32010-03-25 22:08:03 +000010130 if (!IsInstantiation)
10131 PopDeclContext();
10132
Eli Friedman71c80552012-01-05 03:35:19 +000010133 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +000010134 // If any errors have occurred, clear out any temporaries that may have
10135 // been leftover. This ensures that these temporaries won't be picked up for
10136 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +000010137 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +000010138 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +000010139 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +000010140
John McCall48871652010-08-21 09:40:31 +000010141 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +000010142}
10143
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010144
10145/// When we finish delayed parsing of an attribute, we must attach it to the
10146/// relevant Decl.
10147void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10148 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000010149 // Always attach attributes to the underlying decl.
10150 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10151 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +000010152 ProcessDeclAttributeList(S, D, Attrs.getList());
10153
10154 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10155 if (Method->isStatic())
10156 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010157}
10158
10159
Chris Lattnerac18be92006-11-20 06:49:47 +000010160/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10161/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +000010162NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +000010163 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010164 // Before we produce a declaration for an implicitly defined
10165 // function, see whether there was a locally-scoped declaration of
10166 // this name as a function or variable. If so, use that
10167 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +000010168 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10169 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10170 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10171 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010172 }
10173
Chris Lattner00e26072008-05-05 21:18:06 +000010174 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +000010175 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +000010176 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +000010177 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010178 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +000010179 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010180 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010181 diag_id = diag::warn_implicit_function_decl;
10182 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010183
Hans Wennborg70a13242011-12-08 15:56:07 +000010184 // Because typo correction is expensive, only do it if the implicit
10185 // function declaration is going to be treated as an error.
10186 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10187 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010188 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010189 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000010190 LookupOrdinaryName, S, nullptr, Validator,
John Thompson2255f2c2014-04-23 12:57:01 +000010191 CTK_NonError)))
Richard Smithf9b15102013-08-17 00:46:16 +000010192 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10193 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010194 }
10195
Chris Lattnerac18be92006-11-20 06:49:47 +000010196 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010197 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010198 AttributeFactory attrFactory;
10199 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010200 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +000010201 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10202 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010203 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010204 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010205 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010206 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010207 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10208 /*IsAmbiguous=*/false,
Richard Smith151b8a32014-04-07 15:16:58 +000010209 /*LParenLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010210 /*Params=*/nullptr,
Richard Smith151b8a32014-04-07 15:16:58 +000010211 /*NumParams=*/0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010212 /*EllipsisLoc=*/NoLoc,
10213 /*RParenLoc=*/NoLoc,
10214 /*TypeQuals=*/0,
10215 /*RefQualifierIsLvalueRef=*/true,
10216 /*RefQualifierLoc=*/NoLoc,
10217 /*ConstQualifierLoc=*/NoLoc,
10218 /*VolatileQualifierLoc=*/NoLoc,
10219 /*MutableLoc=*/NoLoc,
10220 EST_None,
10221 /*ESpecLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010222 /*Exceptions=*/nullptr,
10223 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010224 /*NumExceptions=*/0,
Craig Topperc3ec1492014-05-26 06:22:03 +000010225 /*NoexceptExpr=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010226 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010227 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010228 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010229 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010230
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010231 // Insert this function into translation-unit scope.
10232
10233 DeclContext *PrevDC = CurContext;
10234 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010235
Jordan Rosed03d99d2013-03-05 01:27:54 +000010236 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010237 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010238
10239 CurContext = PrevDC;
10240
Douglas Gregore711f702009-02-14 18:57:46 +000010241 AddKnownFunctionAttributes(FD);
10242
Steve Naroff3913ea42008-04-04 14:32:09 +000010243 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010244}
10245
Douglas Gregore711f702009-02-14 18:57:46 +000010246/// \brief Adds any function attributes that we know a priori based on
10247/// the declaration of this function.
10248///
10249/// These attributes can apply both to implicitly-declared builtins
10250/// (like __builtin___printf_chk) or to library-declared functions
10251/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010252///
10253/// We need to check for duplicate attributes both here and where user-written
10254/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010255void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10256 if (FD->isInvalidDecl())
10257 return;
10258
10259 // If this is a built-in function, map its builtin attributes to
10260 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010261 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010262 // Handle printf-formatting attributes.
10263 unsigned FormatIdx;
10264 bool HasVAListArg;
10265 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010266 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010267 const char *fmt = "printf";
10268 unsigned int NumParams = FD->getNumParams();
10269 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10270 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10271 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010272 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010273 &Context.Idents.get(fmt),
10274 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010275 HasVAListArg ? 0 : FormatIdx+2,
10276 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010277 }
Douglas Gregore711f702009-02-14 18:57:46 +000010278 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010279 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10280 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010281 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010282 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010283 &Context.Idents.get("scanf"),
10284 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010285 HasVAListArg ? 0 : FormatIdx+2,
10286 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010287 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010288
10289 // Mark const if we don't care about errno and that is the only
10290 // thing preventing the function from being const. This allows
10291 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010292 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010293 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010294 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010295 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010296 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010297
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010298 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010299 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010300 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10301 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010302 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010303 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010304 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010305 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010306 }
10307
10308 IdentifierInfo *Name = FD->getIdentifier();
10309 if (!Name)
10310 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010311 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010312 FD->getDeclContext()->isTranslationUnit()) ||
10313 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010314 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010315 LinkageSpecDecl::lang_c)) {
10316 // Okay: this could be a libc/libm/Objective-C function we know
10317 // about.
10318 } else
10319 return;
10320
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010321 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010322 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010323 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010324 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010325 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010326 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010327 Name->isStr("vasprintf") ? 0 : 3,
10328 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010329 }
Jordan Rose742c6072012-08-08 21:17:31 +000010330
10331 if (Name->isStr("__CFStringMakeConstantString")) {
10332 // We already have a __builtin___CFStringMakeConstantString,
10333 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010334 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010335 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10336 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010337 }
Douglas Gregore711f702009-02-14 18:57:46 +000010338}
Chris Lattner302b4be2006-11-19 02:31:38 +000010339
John McCall703a3f82009-10-24 08:00:42 +000010340TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010341 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010342 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010343 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010344
John McCallbcd03502009-12-07 02:54:59 +000010345 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010346 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010347 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010348 }
10349
Chris Lattner18b19622007-01-22 07:39:13 +000010350 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010351 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010352 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010353 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010354 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010355 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010356
John McCall04fcd0d2011-02-01 08:20:08 +000010357 // Bail out immediately if we have an invalid declaration.
10358 if (D.isInvalidType()) {
10359 NewTD->setInvalidDecl();
10360 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010361 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010362
Douglas Gregor41866812011-09-12 18:37:38 +000010363 if (D.getDeclSpec().isModulePrivateSpecified()) {
10364 if (CurContext->isFunctionOrMethod())
10365 Diag(NewTD->getLocation(), diag::err_module_private_local)
10366 << 2 << NewTD->getDeclName()
10367 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10368 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10369 else
10370 NewTD->setModulePrivate();
10371 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010372
John McCall04fcd0d2011-02-01 08:20:08 +000010373 // C++ [dcl.typedef]p8:
10374 // If the typedef declaration defines an unnamed class (or
10375 // enum), the first typedef-name declared by the declaration
10376 // to be that class type (or enum type) is used to denote the
10377 // class type (or enum type) for linkage purposes only.
10378 // We need to check whether the type was declared in the declaration.
10379 switch (D.getDeclSpec().getTypeSpecType()) {
10380 case TST_enum:
10381 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010382 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010383 case TST_union:
10384 case TST_class: {
10385 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10386
10387 // Do nothing if the tag is not anonymous or already has an
10388 // associated typedef (from an earlier typedef in this decl group).
10389 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010390 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010391
10392 // A well-formed anonymous tag must always be a TUK_Definition.
10393 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10394
10395 // The type must match the tag exactly; no qualifiers allowed.
10396 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10397 break;
10398
John McCall2575d882014-01-30 01:12:53 +000010399 // If we've already computed linkage for the anonymous tag, then
10400 // adding a typedef name for the anonymous decl can change that
10401 // linkage, which might be a serious problem. Diagnose this as
10402 // unsupported and ignore the typedef name. TODO: we should
10403 // pursue this as a language defect and establish a formal rule
10404 // for how to handle it.
10405 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10406 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10407
10408 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +000010409 tagLoc = getLocForEndOfToken(tagLoc);
John McCall2575d882014-01-30 01:12:53 +000010410
10411 llvm::SmallString<40> textToInsert;
10412 textToInsert += ' ';
10413 textToInsert += D.getIdentifier()->getName();
10414 Diag(tagLoc, diag::note_typedef_changes_linkage)
10415 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10416 break;
10417 }
10418
John McCall04fcd0d2011-02-01 08:20:08 +000010419 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010420 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010421 break;
10422 }
10423
10424 default:
10425 break;
10426 }
10427
Steve Narofff93b6722007-08-28 20:14:24 +000010428 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010429}
10430
Douglas Gregord9034f02009-05-14 16:41:31 +000010431
Richard Smith4b38ded2012-03-14 23:13:10 +000010432/// \brief Check that this is a valid underlying type for an enum declaration.
10433bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10434 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10435 QualType T = TI->getType();
10436
Eli Friedman52f32b92012-12-18 02:37:32 +000010437 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010438 return false;
10439
Eli Friedman52f32b92012-12-18 02:37:32 +000010440 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10441 if (BT->isInteger())
10442 return false;
10443
Richard Smith4b38ded2012-03-14 23:13:10 +000010444 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10445 return true;
10446}
10447
10448/// Check whether this is a valid redeclaration of a previous enumeration.
10449/// \return true if the redeclaration was invalid.
10450bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10451 QualType EnumUnderlyingTy,
10452 const EnumDecl *Prev) {
10453 bool IsFixed = !EnumUnderlyingTy.isNull();
10454
10455 if (IsScoped != Prev->isScoped()) {
10456 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10457 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010458 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010459 return true;
10460 }
10461
10462 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010463 if (!EnumUnderlyingTy->isDependentType() &&
10464 !Prev->getIntegerType()->isDependentType() &&
10465 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010466 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010467 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010468 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10469 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010470 Diag(Prev->getLocation(), diag::note_previous_declaration)
10471 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010472 return true;
10473 }
10474 } else if (IsFixed != Prev->isFixed()) {
10475 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10476 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010477 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010478 return true;
10479 }
10480
10481 return false;
10482}
10483
Joao Matosdc86f942012-08-31 18:45:21 +000010484/// \brief Get diagnostic %select index for tag kind for
10485/// redeclaration diagnostic message.
10486/// WARNING: Indexes apply to particular diagnostics only!
10487///
10488/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010489static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010490 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010491 case TTK_Struct: return 0;
10492 case TTK_Interface: return 1;
10493 case TTK_Class: return 2;
10494 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010495 }
Joao Matosdc86f942012-08-31 18:45:21 +000010496}
10497
10498/// \brief Determine if tag kind is a class-key compatible with
10499/// class for redeclaration (class, struct, or __interface).
10500///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010501/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010502static bool isClassCompatTagKind(TagTypeKind Tag)
10503{
10504 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10505}
10506
Douglas Gregord9034f02009-05-14 16:41:31 +000010507/// \brief Determine whether a tag with a given kind is acceptable
10508/// as a redeclaration of the given tag declaration.
10509///
10510/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010511bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010512 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010513 SourceLocation NewTagLoc,
10514 const IdentifierInfo &Name) {
10515 // C++ [dcl.type.elab]p3:
10516 // The class-key or enum keyword present in the
10517 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010518 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010519 // refers. This rule also applies to the form of
10520 // elaborated-type-specifier that declares a class-name or
10521 // friend class since it can be construed as referring to the
10522 // definition of the class. Thus, in any
10523 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010524 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010525 // used to refer to a union (clause 9), and either the class or
10526 // struct class-key shall be used to refer to a class (clause 9)
10527 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010528 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010529 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010530 if (OldTag == NewTag)
10531 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010532
Joao Matosdc86f942012-08-31 18:45:21 +000010533 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010534 // Warn about the struct/class tag mismatch.
10535 bool isTemplate = false;
10536 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10537 isTemplate = Record->getDescribedClassTemplate();
10538
Richard Trieucaa33d32011-06-10 03:11:26 +000010539 if (!ActiveTemplateInstantiations.empty()) {
10540 // In a template instantiation, do not offer fix-its for tag mismatches
10541 // since they usually mess up the template instead of fixing the problem.
10542 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010543 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10544 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010545 return true;
10546 }
10547
10548 if (isDefinition) {
10549 // On definitions, check previous tags and issue a fix-it for each
10550 // one that doesn't match the current tag.
10551 if (Previous->getDefinition()) {
10552 // Don't suggest fix-its for redefinitions.
10553 return true;
10554 }
10555
10556 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010557 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010558 if (I->getTagKind() != NewTag) {
10559 if (!previousMismatch) {
10560 previousMismatch = true;
10561 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010562 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10563 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010564 }
10565 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010566 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010567 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010568 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010569 }
10570 }
10571 return true;
10572 }
10573
10574 // Check for a previous definition. If current tag and definition
10575 // are same type, do nothing. If no definition, but disagree with
10576 // with previous tag type, give a warning, but no fix-it.
10577 const TagDecl *Redecl = Previous->getDefinition() ?
10578 Previous->getDefinition() : Previous;
10579 if (Redecl->getTagKind() == NewTag) {
10580 return true;
10581 }
10582
Douglas Gregord9034f02009-05-14 16:41:31 +000010583 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010584 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10585 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010586 Diag(Redecl->getLocation(), diag::note_previous_use);
10587
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010588 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010589 if (Previous->getDefinition()) {
10590 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010591 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010592 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010593 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010594 }
10595
Douglas Gregord9034f02009-05-14 16:41:31 +000010596 return true;
10597 }
10598 return false;
10599}
10600
Steve Naroff30d242c2007-09-15 18:49:24 +000010601/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010602/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010603/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010604/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010605///
10606/// IsTypeSpecifier is true if this is a type-specifier (or
10607/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010608Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010609 SourceLocation KWLoc, CXXScopeSpec &SS,
10610 IdentifierInfo *Name, SourceLocation NameLoc,
10611 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010612 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010613 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010614 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010615 SourceLocation ScopedEnumKWLoc,
10616 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010617 TypeResult UnderlyingType,
10618 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010619 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010620 IdentifierInfo *OrigName = Name;
Craig Topperc3ec1492014-05-26 06:22:03 +000010621 assert((Name != nullptr || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010622 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010623 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010624
Douglas Gregord6ab8742009-05-28 23:31:59 +000010625 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010626 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010627 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010628
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010629 // FIXME: Check explicit specializations more carefully.
10630 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010631 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010632
10633 // We only need to do this matching if we have template parameters
10634 // or a scope specifier, which also conveniently avoids this work
10635 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010636 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010637 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010638 if (TemplateParameterList *TemplateParams =
10639 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000010640 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
Richard Smith4b55a9c2014-04-17 03:29:33 +000010641 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010642 if (Kind == TTK_Enum) {
10643 Diag(KWLoc, diag::err_enum_template);
Craig Topperc3ec1492014-05-26 06:22:03 +000010644 return nullptr;
Richard Smith1d4b2e12013-04-01 21:43:41 +000010645 }
10646
Douglas Gregor3dad8422009-09-26 06:47:28 +000010647 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010648 // This is a declaration or definition of a class template (which may
10649 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010650
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010651 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000010652 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010653
Douglas Gregore93e46c2009-07-22 23:48:44 +000010654 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010655 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010656 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010657 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010658 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010659 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010660 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010661 return Result.get();
10662 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010663 // The "template<>" header is extraneous.
10664 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010665 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010666 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010667 }
Mike Stump11289f42009-09-09 15:08:12 +000010668 }
10669 }
10670
Douglas Gregor0bf31402010-10-08 23:50:27 +000010671 // Figure out the underlying type if this a enum declaration. We need to do
10672 // this early, because it's needed to detect if this is an incompatible
10673 // redeclaration.
10674 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10675
10676 if (Kind == TTK_Enum) {
10677 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10678 // No underlying type explicitly specified, or we failed to parse the
10679 // type, default to int.
10680 EnumUnderlying = Context.IntTy.getTypePtr();
10681 else if (UnderlyingType.get()) {
10682 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10683 // integral type; any cv-qualification is ignored.
Craig Topperc3ec1492014-05-26 06:22:03 +000010684 TypeSourceInfo *TI = nullptr;
Richard Smitheece8c32012-03-15 00:22:18 +000010685 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010686 EnumUnderlying = TI;
10687
Richard Smith4b38ded2012-03-14 23:13:10 +000010688 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010689 // Recover by falling back to int.
10690 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010691
Richard Smith4b38ded2012-03-14 23:13:10 +000010692 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010693 UPPC_FixedUnderlyingType))
10694 EnumUnderlying = Context.IntTy.getTypePtr();
10695
Alp Tokerbfa39342014-01-14 12:51:41 +000010696 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010697 // Microsoft enums are always of int type.
10698 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010699 }
10700
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010701 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010702 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010703 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010704
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010705 RedeclarationKind Redecl = ForRedeclaration;
10706 if (TUK == TUK_Friend || TUK == TUK_Reference)
10707 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010708
10709 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010710 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010711 if (Name && SS.isNotEmpty()) {
10712 // We have a nested-name tag ('struct foo::bar').
10713
10714 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010715 if (SS.isInvalid()) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010716 Name = nullptr;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010717 goto CreateNewDecl;
10718 }
10719
John McCall7f41d982009-09-11 04:59:25 +000010720 // If this is a friend or a reference to a class in a dependent
10721 // context, don't try to make a decl for it.
10722 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10723 DC = computeDeclContext(SS, false);
10724 if (!DC) {
10725 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000010726 return nullptr;
John McCall7f41d982009-09-11 04:59:25 +000010727 }
John McCall0b66eb32010-05-01 00:40:08 +000010728 } else {
10729 DC = computeDeclContext(SS, true);
10730 if (!DC) {
10731 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10732 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010733 return nullptr;
John McCall0b66eb32010-05-01 00:40:08 +000010734 }
John McCall7f41d982009-09-11 04:59:25 +000010735 }
10736
John McCall0b66eb32010-05-01 00:40:08 +000010737 if (RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +000010738 return nullptr;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010739
Douglas Gregor8761da52009-02-03 00:34:39 +000010740 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010741 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010742 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010743
John McCall1f82f242009-11-18 22:49:29 +000010744 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010745 return nullptr;
John McCall6538c932009-10-10 05:48:19 +000010746
John McCall1f82f242009-11-18 22:49:29 +000010747 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010748 // Name lookup did not find anything. However, if the
10749 // nested-name-specifier refers to the current instantiation,
10750 // and that current instantiation has any dependent base
10751 // classes, we might find something at instantiation time: treat
10752 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010753 // But this only makes any sense for reference-like lookups.
10754 if (Previous.wasNotFoundInCurrentInstantiation() &&
10755 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010756 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000010757 return nullptr;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010758 }
10759
10760 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010761 Diag(NameLoc, diag::err_not_tag_in_scope)
10762 << Kind << Name << DC << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010763 Name = nullptr;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010764 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010765 goto CreateNewDecl;
10766 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010767 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010768 // If this is a named struct, check to see if there was a previous forward
10769 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010770 // FIXME: We're looking into outer scopes here, even when we
10771 // shouldn't be. Doing so can result in ambiguities that we
10772 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010773 LookupName(Previous, S);
10774
John McCall3c581bf2013-03-20 01:53:00 +000010775 // When declaring or defining a tag, ignore ambiguities introduced
10776 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010777 if (Previous.isAmbiguous() &&
10778 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010779 LookupResult::Filter F = Previous.makeFilter();
10780 while (F.hasNext()) {
10781 NamedDecl *ND = F.next();
10782 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10783 F.erase();
10784 }
10785 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010786 }
John McCall3c581bf2013-03-20 01:53:00 +000010787
10788 // C++11 [namespace.memdef]p3:
10789 // If the name in a friend declaration is neither qualified nor
10790 // a template-id and the declaration is a function or an
10791 // elaborated-type-specifier, the lookup to determine whether
10792 // the entity has been previously declared shall not consider
10793 // any scopes outside the innermost enclosing namespace.
10794 //
10795 // Does it matter that this should be by scope instead of by
10796 // semantic context?
10797 if (!Previous.empty() && TUK == TUK_Friend) {
10798 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10799 LookupResult::Filter F = Previous.makeFilter();
10800 while (F.hasNext()) {
10801 NamedDecl *ND = F.next();
10802 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010803 if (DC->isFileContext() &&
10804 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010805 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010806 FriendSawTagOutsideEnclosingNamespace = true;
10807 }
John McCall3c581bf2013-03-20 01:53:00 +000010808 }
10809 F.done();
10810 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010811
John McCall1f82f242009-11-18 22:49:29 +000010812 // Note: there used to be some attempt at recovery here.
10813 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010814 return nullptr;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010815
David Blaikiebbafb8a2012-03-11 07:00:24 +000010816 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010817 // FIXME: This makes sure that we ignore the contexts associated
10818 // with C structs, unions, and enums when looking for a matching
10819 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010820 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010821 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10822 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010823 }
Douglas Gregor009f6992010-09-16 23:58:57 +000010824 } else if (S->isFunctionPrototypeScope()) {
10825 // If this is an enum declaration in function prototype scope, set its
10826 // initial context to the translation unit.
Nick Lewyckyd9e1e572012-03-10 07:45:33 +000010827 // FIXME: [citation needed]
Douglas Gregor009f6992010-09-16 23:58:57 +000010828 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010829 }
10830
John McCall1f82f242009-11-18 22:49:29 +000010831 if (Previous.isSingleResult() &&
10832 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010833 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010834 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010835 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010836 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010837 }
10838
David Blaikiebbafb8a2012-03-11 07:00:24 +000010839 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010840 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010841 // This is a declaration of or a reference to "std::bad_alloc".
10842 isStdBadAlloc = true;
10843
John McCall1f82f242009-11-18 22:49:29 +000010844 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010845 // std::bad_alloc has been implicitly declared (but made invisible to
10846 // name lookup). Fill in this implicit declaration as the previous
10847 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010848 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010849 }
10850 }
John McCall1f82f242009-11-18 22:49:29 +000010851
John McCalle9eaf8e2010-03-25 21:28:06 +000010852 // If we didn't find a previous declaration, and this is a reference
10853 // (or friend reference), move to the correct scope. In C++, we
10854 // also need to do a redeclaration lookup there, just in case
10855 // there's a shadow friend decl.
10856 if (Name && Previous.empty() &&
10857 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10858 if (Invalid) goto CreateNewDecl;
10859 assert(SS.isEmpty());
10860
10861 if (TUK == TUK_Reference) {
10862 // C++ [basic.scope.pdecl]p5:
10863 // -- for an elaborated-type-specifier of the form
10864 //
10865 // class-key identifier
10866 //
10867 // if the elaborated-type-specifier is used in the
10868 // decl-specifier-seq or parameter-declaration-clause of a
10869 // function defined in namespace scope, the identifier is
10870 // declared as a class-name in the namespace that contains
10871 // the declaration; otherwise, except as a friend
10872 // declaration, the identifier is declared in the smallest
10873 // non-class, non-function-prototype scope that contains the
10874 // declaration.
10875 //
10876 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10877 // C structs and unions.
10878 //
10879 // It is an error in C++ to declare (rather than define) an enum
10880 // type, including via an elaborated type specifier. We'll
10881 // diagnose that later; for now, declare the enum in the same
10882 // scope as we would have picked for any other tag type.
10883 //
10884 // GNU C also supports this behavior as part of its incomplete
10885 // enum types extension, while GNU C++ does not.
10886 //
10887 // Find the context where we'll be declaring the tag.
10888 // FIXME: We would like to maintain the current DeclContext as the
10889 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010890 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010891 SearchDC = SearchDC->getParent();
10892
10893 // Find the scope where we'll be declaring the tag.
10894 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010895 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010896 S->isFunctionPrototypeScope()) ||
10897 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010898 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010899 S = S->getParent();
10900 } else {
10901 assert(TUK == TUK_Friend);
10902 // C++ [namespace.memdef]p3:
10903 // If a friend declaration in a non-local class first declares a
10904 // class or function, the friend class or function is a member of
10905 // the innermost enclosing namespace.
10906 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010907 }
10908
John McCalle87beb22010-04-23 18:46:30 +000010909 // In C++, we need to do a redeclaration lookup to properly
10910 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010911 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010912 Previous.setRedeclarationKind(ForRedeclaration);
10913 LookupQualifiedName(Previous, SearchDC);
10914 }
10915 }
10916
John McCall1f82f242009-11-18 22:49:29 +000010917 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010918 NamedDecl *PrevDecl = Previous.getFoundDecl();
10919 NamedDecl *DirectPrevDecl =
10920 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010921
10922 // It's okay to have a tag decl in the same scope as a typedef
10923 // which hides a tag decl in the same scope. Finding this
10924 // insanity with a redeclaration lookup can only actually happen
10925 // in C++.
10926 //
10927 // This is also okay for elaborated-type-specifiers, which is
10928 // technically forbidden by the current standard but which is
10929 // okay according to the likely resolution of an open issue;
10930 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010931 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010932 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010933 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10934 TagDecl *Tag = TT->getDecl();
10935 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010936 Tag->getDeclContext()->getRedeclContext()
10937 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010938 PrevDecl = Tag;
10939 Previous.clear();
10940 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010941 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010942 }
10943 }
10944 }
10945 }
10946
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010947 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010948 // If this is a use of a previous tag, or if the tag is already declared
10949 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010950 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010951 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010952 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010953 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010954 // Make sure that this wasn't declared as an enum and now used as a
10955 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010956 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10957 TUK == TUK_Definition, KWLoc,
10958 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010959 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010960 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10961 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010962 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010963 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010964 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010965 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10966 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000010967 else
10968 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000010969 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000010970
Mike Stump11289f42009-09-09 15:08:12 +000010971 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000010972 Kind = PrevTagDecl->getTagKind();
10973 else {
10974 // Recover by making this an anonymous redefinition.
Craig Topperc3ec1492014-05-26 06:22:03 +000010975 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000010976 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000010977 Invalid = true;
10978 }
10979 }
10980
Douglas Gregor0bf31402010-10-08 23:50:27 +000010981 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10982 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10983
Richard Smith0f8ee222012-01-10 01:33:14 +000010984 // If this is an elaborated-type-specifier for a scoped enumeration,
10985 // the 'class' keyword is not necessary and not permitted.
10986 if (TUK == TUK_Reference || TUK == TUK_Friend) {
10987 if (ScopedEnum)
10988 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10989 << PrevEnum->isScoped()
10990 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10991 return PrevTagDecl;
10992 }
10993
Richard Smith4b38ded2012-03-14 23:13:10 +000010994 QualType EnumUnderlyingTy;
10995 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000010996 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000010997 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10998 EnumUnderlyingTy = QualType(T, 0);
10999
Douglas Gregor0bf31402010-10-08 23:50:27 +000011000 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000011001 // returning the previous declaration, unless this is a definition,
11002 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000011003 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11004 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Craig Topperc3ec1492014-05-26 06:22:03 +000011005 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
Douglas Gregor0bf31402010-10-08 23:50:27 +000011006 }
11007
David Majnemer55890bf2013-06-11 03:51:23 +000011008 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000011009 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000011010 // except that a nested class or member class template can be declared
11011 // and then later defined.
11012 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11013 S->isDeclScope(PrevDecl)) {
11014 Diag(NameLoc, diag::ext_member_redeclared);
11015 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11016 }
11017
Douglas Gregor170512f2009-04-01 23:51:29 +000011018 if (!Invalid) {
John McCall2976f8b2014-05-14 07:54:17 +000011019 // If this is a use, just return the declaration we found, unless
11020 // we have attributes.
Chris Lattner9ff58d72008-07-03 03:30:58 +000011021
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011022 // FIXME: In the future, return a variant or some other clue
11023 // for the consumer of this Decl to know it doesn't own it.
11024 // For our current ASTs this shouldn't be a problem, but will
11025 // need to be changed with DeclGroups.
John McCall2976f8b2014-05-14 07:54:17 +000011026 if (!Attr &&
11027 ((TUK == TUK_Reference &&
11028 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11029 || TUK == TUK_Friend))
John McCall48871652010-08-21 09:40:31 +000011030 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011031
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011032 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000011033 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000011034 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000011035 // If we're defining a specialization and the previous definition
11036 // is from an implicit instantiation, don't emit an error
11037 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000011038 bool IsExplicitSpecializationAfterInstantiation = false;
11039 if (isExplicitSpecialization) {
11040 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11041 IsExplicitSpecializationAfterInstantiation =
11042 RD->getTemplateSpecializationKind() !=
11043 TSK_ExplicitSpecialization;
11044 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11045 IsExplicitSpecializationAfterInstantiation =
11046 ED->getTemplateSpecializationKind() !=
11047 TSK_ExplicitSpecialization;
11048 }
11049
11050 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000011051 // A redeclaration in function prototype scope in C isn't
11052 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011053 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000011054 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11055 else
11056 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000011057 Diag(Def->getLocation(), diag::note_previous_definition);
11058 // If this is a redefinition, recover by making this
11059 // struct be anonymous, which will make any later
11060 // references get the previous definition.
Craig Topperc3ec1492014-05-26 06:22:03 +000011061 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011062 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000011063 Invalid = true;
11064 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011065 } else {
11066 // If the type is currently being defined, complain
11067 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000011068 const TagType *Tag
11069 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000011070 if (Tag->isBeingDefined()) {
11071 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000011072 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000011073 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011074 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011075 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000011076 Invalid = true;
11077 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011078 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011079
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011080 // Okay, this is definition of a previously declared or referenced
John McCalla16fc892014-05-14 18:31:48 +000011081 // tag. We're going to create a new Decl for it.
11082 }
11083
11084 // Okay, we're going to make a redeclaration. If this is some kind
11085 // of reference, make sure we build the redeclaration in the same DC
11086 // as the original, and ignore the current access specifier.
11087 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11088 SearchDC = PrevTagDecl->getDeclContext();
11089 AS = AS_none;
Douglas Gregordee1be82009-01-17 00:42:38 +000011090 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011091 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011092 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000011093 // have a definition. Just create a new decl.
11094
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011095 } else {
11096 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000011097 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011098 // new decl/type. We set PrevDecl to NULL so that the entities
11099 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000011100 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000011101 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011102 // If we get here, we're going to create a new Decl. If PrevDecl
11103 // is non-NULL, it's a definition of the tag declared by
11104 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000011105
11106
11107 // Otherwise, PrevDecl is not a tag, but was found with tag
11108 // lookup. This is only actually possible in C++, where a few
11109 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011110 } else {
John McCalle87beb22010-04-23 18:46:30 +000011111 // Use a better diagnostic if an elaborated-type-specifier
11112 // found the wrong kind of type on the first
11113 // (non-redeclaration) lookup.
11114 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11115 !Previous.isForRedeclaration()) {
11116 unsigned Kind = 0;
11117 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011118 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11119 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011120 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11121 Diag(PrevDecl->getLocation(), diag::note_declared_at);
11122 Invalid = true;
11123
11124 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000011125 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11126 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000011127 // do nothing
11128
11129 // Diagnose implicit declarations introduced by elaborated types.
11130 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11131 unsigned Kind = 0;
11132 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011133 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11134 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011135 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11136 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11137 Invalid = true;
11138
11139 // Otherwise it's a declaration. Call out a particularly common
11140 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000011141 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11142 unsigned Kind = 0;
11143 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000011144 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000011145 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000011146 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11147 Invalid = true;
11148
11149 // Otherwise, diagnose.
11150 } else {
11151 // The tag name clashes with something else in the target scope,
11152 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000011153 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000011154 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011155 Name = nullptr;
Douglas Gregordee1be82009-01-17 00:42:38 +000011156 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011157 }
John McCalle87beb22010-04-23 18:46:30 +000011158
11159 // The existing declaration isn't relevant to us; we're in a
11160 // new scope, so clear out the previous declaration.
11161 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000011162 }
Chris Lattner18b19622007-01-22 07:39:13 +000011163 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000011164
Chris Lattner438e5012008-12-17 07:13:27 +000011165CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000011166
Craig Topperc3ec1492014-05-26 06:22:03 +000011167 TagDecl *PrevDecl = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011168 if (Previous.isSingleResult())
11169 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11170
Chris Lattnerbf0b7982007-01-23 04:27:41 +000011171 // If there is an identifier, use the location of the identifier as the
11172 // location of the decl, otherwise use the location of the struct/union
11173 // keyword.
11174 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000011175
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011176 // Otherwise, create a new declaration. If there is a previous
11177 // declaration of the same entity, the two will be linked via
11178 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000011179 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000011180
Douglas Gregor0bf31402010-10-08 23:50:27 +000011181 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011182 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000011183 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11184 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011185 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000011186 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011187 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000011188 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011189 if (TUK != TUK_Definition && !Invalid) {
11190 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000011191 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11192 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000011193 // C++0x: 7.2p2: opaque-enum-declaration.
11194 // Conflicts are diagnosed above. Do nothing.
11195 }
11196 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011197 Diag(Loc, diag::ext_forward_ref_enum_def)
11198 << New;
11199 Diag(Def->getLocation(), diag::note_previous_definition);
11200 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000011201 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000011202 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000011203 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011204 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000011205 DiagID = diag::err_forward_ref_enum;
11206 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011207
11208 // If this is a forward-declared reference to an enumeration, make a
11209 // note of it; we won't actually be introducing the declaration into
11210 // the declaration context.
11211 if (TUK == TUK_Reference)
11212 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011213 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000011214 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000011215
11216 if (EnumUnderlying) {
11217 EnumDecl *ED = cast<EnumDecl>(New);
11218 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11219 ED->setIntegerTypeSourceInfo(TI);
11220 else
11221 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11222 ED->setPromotionType(ED->getIntegerType());
11223 }
11224
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011225 } else {
11226 // struct/union/class
11227
Chris Lattner776fac82007-06-09 00:53:06 +000011228 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11229 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011230 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011231 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011232 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011233 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011234
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011235 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011236 StdBadAlloc = cast<CXXRecordDecl>(New);
11237 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011238 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011239 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011240 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011241
Richard Smith649c7b062014-01-08 00:56:48 +000011242 // C++11 [dcl.type]p3:
11243 // A type-specifier-seq shall not define a class or enumeration [...].
11244 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11245 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11246 << Context.getTagDeclType(New);
11247 Invalid = true;
11248 }
11249
John McCall3e11ebe2010-03-15 10:12:16 +000011250 // Maybe add qualifier info.
11251 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011252 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011253 // If this is either a declaration or a definition, check the
11254 // nested-name-specifier against the current context. We don't do this
11255 // for explicit specializations, because they have similar checking
11256 // (with more specific diagnostics) in the call to
11257 // CheckMemberSpecialization, below.
11258 if (!isExplicitSpecialization &&
11259 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11260 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11261 Invalid = true;
11262
Douglas Gregor14454802011-02-25 02:25:35 +000011263 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011264 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011265 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011266 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011267 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011268 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011269 }
11270 else
11271 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011272 }
11273
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011274 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11275 // Add alignment attributes if necessary; these attributes are checked when
11276 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011277 //
11278 // It is important for implementing the correct semantics that this
11279 // happen here (in act on tag decl). The #pragma pack stack is
11280 // maintained as a result of parser callbacks which can occur at
11281 // many points during the parsing of a struct declaration (because
11282 // the #pragma tokens are effectively skipped over during the
11283 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011284 if (TUK == TUK_Definition) {
11285 AddAlignmentAttributesForRecord(RD);
11286 AddMsStructLayoutForRecord(RD);
11287 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011288 }
11289
Douglas Gregor21823bf2011-12-20 18:11:52 +000011290 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011291 if (isExplicitSpecialization)
11292 Diag(New->getLocation(), diag::err_module_private_specialization)
11293 << 2
11294 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011295 // __module_private__ does not apply to local classes. However, we only
11296 // diagnose this as an error when the declaration specifiers are
11297 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011298 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011299 New->setModulePrivate();
11300 }
11301
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011302 // If this is a specialization of a member class (of a class template),
11303 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011304 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011305 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011306
Douglas Gregordee1be82009-01-17 00:42:38 +000011307 if (Invalid)
11308 New->setInvalidDecl();
11309
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011310 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011311 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011312
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011313 // If we're declaring or defining a tag in function prototype scope in C,
11314 // note that this type can only be used within the function and add it to
11315 // the list of decls to inject into the function definition scope.
11316 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11317 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
Douglas Gregor658b9552009-01-09 22:42:13 +000011318 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
Peter Collingbournefa1d4e12014-02-22 03:05:49 +000011319 DeclsInPrototypeScope.push_back(New);
11320 }
Douglas Gregor658b9552009-01-09 22:42:13 +000011321
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011322 // Set the lexical context. If the tag has a C++ scope specifier, the
11323 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011324 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011325
John McCallaa74a0c2009-08-28 07:59:38 +000011326 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011327 // In Microsoft mode, a friend declaration also acts as a forward
11328 // declaration so we always pass true to setObjectOfFriendDecl to make
11329 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011330 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011331 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11332 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011333
Anders Carlsson5558ca12009-03-26 01:19:02 +000011334 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011335 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011336 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011337
John McCall9bb74a52009-07-31 02:45:11 +000011338 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011339 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011340
Chris Lattner18b19622007-01-22 07:39:13 +000011341 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011342 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011343 // We might be replacing an existing declaration in the lookup tables;
11344 // if so, borrow its access specifier.
11345 if (PrevDecl)
11346 New->setAccess(PrevDecl->getAccess());
11347
Sebastian Redl50c68252010-08-31 00:36:30 +000011348 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011349 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011350 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011351 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11352 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011353 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011354 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011355 PushOnScopeChains(New, S, !IsForwardReference);
11356 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011357 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011358
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011359 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011360 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011361 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011362
Douglas Gregor27821ce2009-07-07 16:35:42 +000011363 // If this is the C FILE type, notify the AST context.
11364 if (IdentifierInfo *II = New->getIdentifier())
11365 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011366 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011367 II->isStr("FILE"))
11368 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011369
Rafael Espindolac67f2232012-05-10 02:50:16 +000011370 if (PrevDecl)
11371 mergeDeclAttributes(New, PrevDecl);
11372
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011373 // If there's a #pragma GCC visibility in scope, set the visibility of this
11374 // record.
11375 AddPushedVisibilityAttribute(New);
11376
Douglas Gregord6ab8742009-05-28 23:31:59 +000011377 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011378 // In C++, don't return an invalid declaration. We can't recover well from
11379 // the cases where we make the type anonymous.
Craig Topperc3ec1492014-05-26 06:22:03 +000011380 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011381}
Chris Lattner1300fb92007-01-23 23:42:53 +000011382
John McCall48871652010-08-21 09:40:31 +000011383void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011384 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011385 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011386
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011387 // Enter the tag context.
11388 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011389
11390 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011391
11392 // If there's a #pragma GCC visibility in scope, set the visibility of this
11393 // record.
11394 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011395}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011396
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011397Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011398 assert(isa<ObjCContainerDecl>(IDecl) &&
11399 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11400 DeclContext *OCD = cast<DeclContext>(IDecl);
11401 assert(getContainingDC(OCD) == CurContext &&
11402 "The next DeclContext should be lexically contained in the current one.");
11403 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011404 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011405}
11406
John McCall48871652010-08-21 09:40:31 +000011407void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011408 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011409 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011410 SourceLocation LBraceLoc) {
11411 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011412 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011413
John McCall1c7e6ec2009-12-20 07:58:13 +000011414 FieldCollector->StartClass();
11415
11416 if (!Record->getIdentifier())
11417 return;
11418
Anders Carlsson30f29442011-03-25 14:31:08 +000011419 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011420 Record->addAttr(new (Context)
11421 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11422
John McCall1c7e6ec2009-12-20 07:58:13 +000011423 // C++ [class]p2:
11424 // [...] The class-name is also inserted into the scope of the
11425 // class itself; this is known as the injected-class-name. For
11426 // purposes of access checking, the injected-class-name is treated
11427 // as if it were a public member name.
11428 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011429 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11430 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011431 Record->getIdentifier(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011432 /*PrevDecl=*/nullptr,
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011433 /*DelayTypeCreation=*/true);
11434 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011435 InjectedClassName->setImplicit();
11436 InjectedClassName->setAccess(AS_public);
11437 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11438 InjectedClassName->setDescribedClassTemplate(Template);
11439 PushOnScopeChains(InjectedClassName, S);
11440 assert(InjectedClassName->isInjectedClassName() &&
11441 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011442}
11443
John McCall48871652010-08-21 09:40:31 +000011444void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011445 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011446 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011447 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011448 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011449
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011450 // Make sure we "complete" the definition even it is invalid.
11451 if (Tag->isBeingDefined()) {
11452 assert(Tag->isInvalidDecl() && "We should already have completed it");
11453 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11454 RD->completeDefinition();
11455 }
11456
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011457 if (isa<CXXRecordDecl>(Tag))
11458 FieldCollector->FinishClass();
11459
11460 // Exit this scope of this tag's definition.
11461 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011462
11463 if (getCurLexicalContext()->isObjCContainer() &&
11464 Tag->getDeclContext()->isFileContext())
11465 Tag->setTopLevelDeclInObjCContainer();
11466
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011467 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011468 if (!Tag->isInvalidDecl())
11469 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011470}
Chris Lattner535b8302008-06-21 19:39:06 +000011471
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011472void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011473 // Exit this scope of this interface definition.
11474 PopDeclContext();
11475}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011476
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011477void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011478 assert(DC == CurContext && "Mismatch of container contexts");
11479 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011480 ActOnObjCContainerFinishDefinition();
11481}
11482
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011483void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11484 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Craig Topperc3ec1492014-05-26 06:22:03 +000011485 OriginalLexicalContext = nullptr;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011486}
11487
John McCall48871652010-08-21 09:40:31 +000011488void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011489 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011490 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011491 Tag->setInvalidDecl();
11492
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011493 // Make sure we "complete" the definition even it is invalid.
11494 if (Tag->isBeingDefined()) {
11495 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11496 RD->completeDefinition();
11497 }
11498
John McCall71ba5f22010-03-17 19:25:57 +000011499 // We're undoing ActOnTagStartDefinition here, not
11500 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11501 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011502
11503 PopDeclContext();
11504}
11505
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011506// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011507ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11508 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011509 QualType FieldTy, bool IsMsStruct,
11510 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011511 // Default to true; that shouldn't confuse checks for emptiness
11512 if (ZeroWidth)
11513 *ZeroWidth = true;
11514
Chris Lattner73bf7b42009-03-05 22:45:59 +000011515 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011516 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011517 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011518 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011519 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011520 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011521 if (FieldName)
11522 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11523 << FieldName << FieldTy << BitWidth->getSourceRange();
11524 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11525 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011526 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11527 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011528 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011529
11530 // If the bit-width is type- or value-dependent, don't try to check
11531 // it now.
11532 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011533 return BitWidth;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011534
Anders Carlsson5df391e2008-12-06 20:33:04 +000011535 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011536 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11537 if (ICE.isInvalid())
11538 return ICE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011539 BitWidth = ICE.get();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011540
Eli Friedmanc96d4962009-08-15 21:55:26 +000011541 if (Value != 0 && ZeroWidth)
11542 *ZeroWidth = false;
11543
Chris Lattner81ed6802008-12-12 04:56:04 +000011544 // Zero-width bitfield is ok for anonymous field.
11545 if (Value == 0 && FieldName)
11546 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011547
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011548 if (Value.isSigned() && Value.isNegative()) {
11549 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011550 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011551 << FieldName << Value.toString(10);
11552 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11553 << Value.toString(10);
11554 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011555
Douglas Gregor1efa4372009-03-11 18:59:21 +000011556 if (!FieldTy->isDependentType()) {
11557 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011558 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011559 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11560 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011561 if (FieldName)
11562 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11563 << FieldName << (unsigned)Value.getZExtValue()
11564 << (unsigned)TypeSize;
11565
11566 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11567 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11568 }
11569
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011570 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011571 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11572 << FieldName << (unsigned)Value.getZExtValue()
11573 << (unsigned)TypeSize;
11574 else
11575 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11576 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011577 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011578 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011579
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011580 return BitWidth;
Anders Carlsson5df391e2008-12-06 20:33:04 +000011581}
11582
Richard Smith938f40b2011-06-11 17:19:42 +000011583/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011584/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011585Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011586 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011587 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011588 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011589 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011590 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011591}
11592
11593/// HandleField - Analyze a field of a C struct or a C++ data member.
11594///
11595FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11596 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011597 Declarator &D, Expr *BitWidth,
11598 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011599 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011600 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011601 SourceLocation Loc = DeclStart;
11602 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011603
John McCall8cb7bdf2010-06-04 23:28:52 +000011604 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11605 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011606 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011607 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011608
Douglas Gregora02a72a2010-12-15 23:18:36 +000011609 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11610 UPPC_DataMemberType)) {
11611 D.setInvalidType();
11612 T = Context.IntTy;
11613 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11614 }
11615 }
11616
Matt Arsenault376f7202013-02-26 21:16:00 +000011617 // TR 18037 does not allow fields to be declared with address spaces.
11618 if (T.getQualifiers().hasAddressSpace()) {
11619 Diag(Loc, diag::err_field_with_address_space);
11620 D.setInvalidType();
11621 }
11622
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011623 // OpenCL 1.2 spec, s6.9 r:
11624 // The event type cannot be used to declare a structure or union field.
11625 if (LangOpts.OpenCL && T->isEventT()) {
11626 Diag(Loc, diag::err_event_t_struct_field);
11627 D.setInvalidType();
11628 }
11629
Richard Smithb1402ae2013-03-18 22:52:47 +000011630 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011631
Richard Smithb4a9e862013-04-12 22:46:28 +000011632 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11633 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11634 diag::err_invalid_thread)
11635 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011636
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011637 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000011638 NamedDecl *PrevDecl = nullptr;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011639 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11640 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011641 switch (Previous.getResultKind()) {
11642 case LookupResult::Found:
11643 case LookupResult::FoundUnresolvedValue:
11644 PrevDecl = Previous.getAsSingle<NamedDecl>();
11645 break;
11646
11647 case LookupResult::FoundOverloaded:
11648 PrevDecl = Previous.getRepresentativeDecl();
11649 break;
11650
11651 case LookupResult::NotFound:
11652 case LookupResult::NotFoundInCurrentInstantiation:
11653 case LookupResult::Ambiguous:
11654 break;
11655 }
11656 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011657
11658 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11659 // Maybe we will complain about the shadowed template parameter.
11660 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11661 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011662 PrevDecl = nullptr;
Douglas Gregorf187420f2009-06-17 23:37:01 +000011663 }
11664
Douglas Gregor1efa4372009-03-11 18:59:21 +000011665 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000011666 PrevDecl = nullptr;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011667
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011668 bool Mutable
11669 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011670 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011671 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011672 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011673 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011674
11675 if (NewFD->isInvalidDecl())
11676 Record->setInvalidDecl();
11677
Douglas Gregor3baa6702011-09-12 16:11:24 +000011678 if (D.getDeclSpec().isModulePrivateSpecified())
11679 NewFD->setModulePrivate();
11680
Douglas Gregor1efa4372009-03-11 18:59:21 +000011681 if (NewFD->isInvalidDecl() && PrevDecl) {
11682 // Don't introduce NewFD into scope; there's already something
11683 // with the same name in the same scope.
11684 } else if (II) {
11685 PushOnScopeChains(NewFD, S);
11686 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011687 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011688
11689 return NewFD;
11690}
11691
11692/// \brief Build a new FieldDecl and check its well-formedness.
11693///
11694/// This routine builds a new FieldDecl given the fields name, type,
11695/// record, etc. \p PrevDecl should refer to any previous declaration
11696/// with the same name and in the same scope as the field to be
11697/// created.
11698///
11699/// \returns a new FieldDecl.
11700///
Mike Stump11289f42009-09-09 15:08:12 +000011701/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011702FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011703 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011704 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011705 bool Mutable, Expr *BitWidth,
11706 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011707 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011708 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011709 Declarator *D) {
11710 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011711 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011712 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011713
Douglas Gregor1efa4372009-03-11 18:59:21 +000011714 // If we receive a broken type, recover by assuming 'int' and
11715 // marking this declaration as invalid.
11716 if (T.isNull()) {
11717 InvalidDecl = true;
11718 T = Context.IntTy;
11719 }
11720
Eli Friedmand0e8de22009-12-07 00:22:08 +000011721 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011722 if (!EltTy->isDependentType()) {
11723 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11724 // Fields of incomplete type force their record to be invalid.
11725 Record->setInvalidDecl();
11726 InvalidDecl = true;
11727 } else {
11728 NamedDecl *Def;
11729 EltTy->isIncompleteType(&Def);
11730 if (Def && Def->isInvalidDecl()) {
11731 Record->setInvalidDecl();
11732 InvalidDecl = true;
11733 }
11734 }
John McCall2677e102010-08-16 23:42:35 +000011735 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011736
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011737 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11738 if (BitWidth && getLangOpts().OpenCL) {
11739 Diag(Loc, diag::err_opencl_bitfields);
11740 InvalidDecl = true;
11741 }
11742
Steve Naroff8eeeb132007-05-08 21:09:37 +000011743 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11744 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011745 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011746 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011747 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011748
11749 TypeSourceInfo *FixedTInfo =
11750 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11751 SizeIsNegative,
11752 Oversized);
11753 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011754 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011755 TInfo = FixedTInfo;
11756 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011757 } else {
11758 if (SizeIsNegative)
11759 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011760 else if (Oversized.getBoolValue())
11761 Diag(Loc, diag::err_array_too_large)
11762 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011763 else
11764 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011765 InvalidDecl = true;
11766 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011767 }
Mike Stump11289f42009-09-09 15:08:12 +000011768
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011769 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011770 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11771 diag::err_abstract_type_in_decl,
11772 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011773 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011774
Eli Friedmanc96d4962009-08-15 21:55:26 +000011775 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011776 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011777 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011778 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011779 &ZeroWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000011780 if (!BitWidth) {
11781 InvalidDecl = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000011782 BitWidth = nullptr;
Richard Smithf4c51d92012-02-04 09:53:13 +000011783 ZeroWidth = false;
11784 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011785 }
Mike Stump11289f42009-09-09 15:08:12 +000011786
John McCallb1cd7da2010-06-04 08:34:12 +000011787 // Check that 'mutable' is consistent with the type of the declaration.
11788 if (!InvalidDecl && Mutable) {
11789 unsigned DiagID = 0;
11790 if (T->isReferenceType())
11791 DiagID = diag::err_mutable_reference;
11792 else if (T.isConstQualified())
11793 DiagID = diag::err_mutable_const;
11794
11795 if (DiagID) {
11796 SourceLocation ErrLoc = Loc;
11797 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11798 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11799 Diag(ErrLoc, DiagID);
11800 Mutable = false;
11801 InvalidDecl = true;
11802 }
11803 }
11804
Richard Smithab44d5b2013-12-10 08:25:00 +000011805 // C++11 [class.union]p8 (DR1460):
11806 // At most one variant member of a union may have a
11807 // brace-or-equal-initializer.
11808 if (InitStyle != ICIS_NoInit)
11809 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11810
Abramo Bagnaradff19302011-03-08 08:55:46 +000011811 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011812 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011813 if (InvalidDecl)
11814 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011815
Douglas Gregor1efa4372009-03-11 18:59:21 +000011816 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11817 Diag(Loc, diag::err_duplicate_member) << II;
11818 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11819 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011820 }
11821
David Blaikiebbafb8a2012-03-11 07:00:24 +000011822 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011823 if (Record->isUnion()) {
11824 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11825 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11826 if (RDecl->getDefinition()) {
11827 // C++ [class.union]p1: An object of a class with a non-trivial
11828 // constructor, a non-trivial copy constructor, a non-trivial
11829 // destructor, or a non-trivial copy assignment operator
11830 // cannot be a member of a union, nor can an array of such
11831 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011832 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011833 NewFD->setInvalidDecl();
11834 }
11835 }
11836
11837 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011838 // the program is ill-formed, except when compiling with MSVC extensions
11839 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011840 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011841 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11842 diag::ext_union_member_of_reference_type :
11843 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011844 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011845 if (!getLangOpts().MicrosoftExt)
11846 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011847 }
11848 }
11849 }
11850
Douglas Gregor1efa4372009-03-11 18:59:21 +000011851 // FIXME: We need to pass in the attributes given an AST
11852 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011853 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011854 // FIXME: The current scope is almost... but not entirely... correct here.
11855 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011856
Richard Smith848e1f12013-02-01 08:12:08 +000011857 if (NewFD->hasAttrs())
11858 CheckAlignasUnderalignment(NewFD);
11859 }
11860
John McCall31168b02011-06-15 23:02:42 +000011861 // In auto-retain/release, infer strong retension for fields of
11862 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011863 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011864 NewFD->setInvalidDecl();
11865
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011866 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011867 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011868
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011869 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011870 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011871}
11872
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011873bool Sema::CheckNontrivialField(FieldDecl *FD) {
11874 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011875 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011876
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011877 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11878 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011879
11880 QualType EltTy = Context.getBaseElementType(FD->getType());
11881 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011882 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011883 if (RDecl->getDefinition()) {
11884 // We check for copy constructors before constructors
11885 // because otherwise we'll never get complaints about
11886 // copy constructors.
11887
11888 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011889 // We're required to check for any non-trivial constructors. Since the
11890 // implicit default constructor is suppressed if there are any
11891 // user-declared constructors, we just need to check that there is a
11892 // trivial default constructor and a trivial copy constructor. (We don't
11893 // worry about move constructors here, since this is a C++98 check.)
11894 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011895 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011896 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011897 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011898 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011899 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011900 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011901 member = CXXDestructor;
11902
11903 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011904 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011905 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011906 // Objective-C++ ARC: it is an error to have a non-trivial field of
11907 // a union. However, system headers in Objective-C programs
11908 // occasionally have Objective-C lifetime objects within unions,
11909 // and rather than cause the program to fail, we make those
11910 // members unavailable.
11911 SourceLocation Loc = FD->getLocation();
11912 if (getSourceManager().isInSystemHeader(Loc)) {
11913 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011914 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11915 "this system field has retaining ownership",
11916 Loc));
John McCall31168b02011-06-15 23:02:42 +000011917 return false;
11918 }
11919 }
Richard Smithf720df02011-10-19 20:41:51 +000011920
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011921 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011922 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11923 diag::err_illegal_union_or_anon_struct_member)
11924 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011925 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011926 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011927 }
11928 }
11929 }
Richard Smith92f241f2012-12-08 02:53:02 +000011930
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011931 return false;
11932}
11933
Mike Stump11289f42009-09-09 15:08:12 +000011934/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011935/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011936static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011937TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011938 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011939 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011940 case tok::objc_private: return ObjCIvarDecl::Private;
11941 case tok::objc_public: return ObjCIvarDecl::Public;
11942 case tok::objc_protected: return ObjCIvarDecl::Protected;
11943 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011944 }
11945}
11946
Mike Stump11289f42009-09-09 15:08:12 +000011947/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011948/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011949Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011950 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011951 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011952 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011953
Fariborz Jahaniande615832008-04-10 23:32:45 +000011954 IdentifierInfo *II = D.getIdentifier();
11955 Expr *BitWidth = (Expr*)BitfieldWidth;
11956 SourceLocation Loc = DeclStart;
11957 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011958
Fariborz Jahaniande615832008-04-10 23:32:45 +000011959 // FIXME: Unnamed fields can be handled in various different ways, for
11960 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000011961
John McCall8cb7bdf2010-06-04 23:28:52 +000011962 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11963 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000011964
Fariborz Jahaniande615832008-04-10 23:32:45 +000011965 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000011966 // 6.7.2.1p3, 6.7.2.1p4
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011967 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000011968 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011969 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011970 } else {
11971 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000011972
Fariborz Jahaniande615832008-04-10 23:32:45 +000011973 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000011974
Fariborz Jahaniande615832008-04-10 23:32:45 +000011975 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011976 if (T->isReferenceType()) {
11977 Diag(Loc, diag::err_ivar_reference_type);
11978 D.setInvalidType();
11979 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000011980 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11981 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000011982 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000011983 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011984 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000011985 }
Mike Stump11289f42009-09-09 15:08:12 +000011986
Ted Kremenek73295fa2008-07-23 18:04:17 +000011987 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000011988 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000011989 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11990 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000011991 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011992 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000011993 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +000011994 return nullptr;
Daniel Dunbar229385c2010-04-02 18:29:09 +000011995 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000011996 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000011997 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000011998 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000011999 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000012000 EnclosingContext = IMPDecl->getClassInterface();
12001 assert(EnclosingContext && "Implementation has no class interface!");
12002 }
12003 else
12004 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012005 } else {
12006 if (ObjCCategoryDecl *CDecl =
12007 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000012008 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012009 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
Craig Topperc3ec1492014-05-26 06:22:03 +000012010 return nullptr;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012011 }
12012 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000012013 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012014 }
Mike Stump11289f42009-09-09 15:08:12 +000012015
Ted Kremenek73295fa2008-07-23 18:04:17 +000012016 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012017 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12018 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000012019 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000012020
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012021 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012022 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000012023 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012024 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012025 && !isa<TagDecl>(PrevDecl)) {
12026 Diag(Loc, diag::err_duplicate_member) << II;
12027 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12028 NewID->setInvalidDecl();
12029 }
12030 }
12031
Ted Kremenek73295fa2008-07-23 18:04:17 +000012032 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000012033 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000012034
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012035 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000012036 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000012037
John McCall31168b02011-06-15 23:02:42 +000012038 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012039 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000012040 NewID->setInvalidDecl();
12041
Douglas Gregor3baa6702011-09-12 16:11:24 +000012042 if (D.getDeclSpec().isModulePrivateSpecified())
12043 NewID->setModulePrivate();
12044
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012045 if (II) {
12046 // FIXME: When interfaces are DeclContexts, we'll need to add
12047 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000012048 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012049 IdResolver.AddDecl(NewID);
12050 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012051
John McCall5fb5df92012-06-20 06:18:46 +000012052 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012053 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000012054 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012055
John McCall48871652010-08-21 09:40:31 +000012056 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000012057}
12058
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012059/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000012060/// class and class extensions. For every class \@interface and class
12061/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012062/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012063void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012064 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000012065 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012066 return;
12067
12068 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12069 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12070
Richard Smithcaf33902011-10-10 18:28:20 +000012071 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012072 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012073 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012074 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012075 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012076 if (!CD->IsClassExtension())
12077 return;
12078 }
12079 // No need to add this to end of @implementation.
12080 else
12081 return;
12082 }
12083 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000012084 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12085 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012086
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012087 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Craig Topperc3ec1492014-05-26 06:22:03 +000012088 DeclLoc, DeclLoc, nullptr,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012089 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000012090 Context.getTrivialTypeSourceInfo(Context.CharTy,
12091 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012092 ObjCIvarDecl::Private, BW,
12093 true);
12094 AllIvarDecls.push_back(Ivar);
12095}
12096
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012097void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12098 ArrayRef<Decl *> Fields, SourceLocation LBrac,
12099 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000012100 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000012101
Eric Christopher7457aaf2012-07-19 22:22:51 +000012102 // If this is an Objective-C @implementation or category and we have
12103 // new fields here we should reset the layout of the interface since
12104 // it will now change.
12105 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12106 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12107 switch (DC->getKind()) {
12108 default: break;
12109 case Decl::ObjCCategory:
12110 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12111 break;
12112 case Decl::ObjCImplementation:
12113 Context.
12114 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12115 break;
12116 }
12117 }
12118
Eli Friedmana7679412012-02-07 05:00:47 +000012119 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12120
12121 // Start counting up the number of named members; make sure to include
12122 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000012123 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000012124 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000012125 for (const auto *I : Record->decls()) {
12126 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000012127 if (IFD->getDeclName())
12128 ++NumNamedMembers;
12129 }
12130 }
12131
12132 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012133 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000012134
John McCall31168b02011-06-15 23:02:42 +000012135 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012136 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000012137 i != end; ++i) {
12138 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000012139
Chris Lattner720a0542007-01-25 00:44:24 +000012140 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000012141 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000012142
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012143 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000012144 // Remember all fields written by the user.
12145 RecFields.push_back(FD);
12146 }
Mike Stump11289f42009-09-09 15:08:12 +000012147
Chris Lattner73bf7b42009-03-05 22:45:59 +000012148 // If the field is already invalid for some reason, don't emit more
12149 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012150 if (FD->isInvalidDecl()) {
12151 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000012152 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000012153 }
Mike Stump11289f42009-09-09 15:08:12 +000012154
Douglas Gregorac1fb652009-03-24 19:52:54 +000012155 // C99 6.7.2.1p2:
12156 // A structure or union shall not contain a member with
12157 // incomplete or function type (hence, a structure shall not
12158 // contain an instance of itself, but may contain a pointer to
12159 // an instance of itself), except that the last member of a
12160 // structure with more than one named member may have incomplete
12161 // array type; such a structure (and any union containing,
12162 // possibly recursively, a member that is such a structure)
12163 // shall not be a member of a structure or an element of an
12164 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000012165 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012166 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000012167 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012168 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000012169 FD->setInvalidDecl();
12170 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012171 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000012172 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000012173 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000012174 ((getLangOpts().MicrosoftExt ||
12175 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000012176 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012177 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000012178 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000012179 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000012180 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000012181 unsigned DiagID = 0;
12182 if (Record->isUnion())
12183 DiagID = getLangOpts().MicrosoftExt
12184 ? diag::ext_flexible_array_union_ms
12185 : getLangOpts().CPlusPlus
12186 ? diag::ext_flexible_array_union_gnu
12187 : diag::err_flexible_array_union;
12188 else if (Fields.size() == 1)
12189 DiagID = getLangOpts().MicrosoftExt
12190 ? diag::ext_flexible_array_empty_aggregate_ms
12191 : getLangOpts().CPlusPlus
12192 ? diag::ext_flexible_array_empty_aggregate_gnu
12193 : NumNamedMembers < 1
12194 ? diag::err_flexible_array_empty_aggregate
12195 : 0;
12196
12197 if (DiagID)
12198 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12199 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000012200 // While the layout of types that contain virtual bases is not specified
12201 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12202 // virtual bases after the derived members. This would make a flexible
12203 // array member declared at the end of an object not adjacent to the end
12204 // of the type.
12205 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12206 if (RD->getNumVBases() != 0)
12207 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12208 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000012209 if (!getLangOpts().C99)
12210 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12211 << FD->getDeclName() << Record->getTagKind();
12212
Richard Smith6fa28ff2014-01-11 00:53:35 +000012213 // If the element type has a non-trivial destructor, we would not
12214 // implicitly destroy the elements, so disallow it for now.
12215 //
12216 // FIXME: GCC allows this. We should probably either implicitly delete
12217 // the destructor of the containing class, or just allow this.
12218 QualType BaseElem = Context.getBaseElementType(FD->getType());
12219 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12220 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000012221 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000012222 FD->setInvalidDecl();
12223 EnclosingDecl->setInvalidDecl();
12224 continue;
12225 }
Chris Lattner720a0542007-01-25 00:44:24 +000012226 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000012227 if (Record)
12228 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000012229 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000012230 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000012231 diag::err_field_incomplete)) {
12232 // Incomplete type
12233 FD->setInvalidDecl();
12234 EnclosingDecl->setInvalidDecl();
12235 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012236 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012237 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12238 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012239 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012240 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012241 } else {
12242 // If this is a struct/class and this is not the last element, reject
12243 // it. Note that GCC supports variable sized arrays in the middle of
12244 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012245 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012246 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012247 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012248 else {
12249 // We support flexible arrays at the end of structs in
12250 // other structs as an extension.
12251 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12252 << FD->getDeclName();
12253 if (Record)
12254 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012255 }
Chris Lattner720a0542007-01-25 00:44:24 +000012256 }
12257 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012258 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12259 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12260 diag::err_abstract_type_in_decl,
12261 AbstractIvarType)) {
12262 // Ivars can not have abstract class types
12263 FD->setInvalidDecl();
12264 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012265 if (Record && FDTTy->getDecl()->hasObjectMember())
12266 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012267 if (Record && FDTTy->getDecl()->hasVolatileMember())
12268 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012269 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012270 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012271 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12272 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12273 QualType T = Context.getObjCObjectPointerType(FD->getType());
12274 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012275 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12276 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12277 // It's an error in ARC if a field has lifetime.
12278 // We don't want to report this in a system header, though,
12279 // so we just make the field unavailable.
12280 // FIXME: that's really not sufficient; we need to make the type
12281 // itself invalid to, say, initialize or copy.
12282 QualType T = FD->getType();
12283 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12284 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12285 SourceLocation loc = FD->getLocation();
12286 if (getSourceManager().isInSystemHeader(loc)) {
12287 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012288 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12289 "this system field has retaining ownership",
12290 loc));
John McCall31168b02011-06-15 23:02:42 +000012291 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012292 } else {
12293 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012294 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012295 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012296 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012297 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012298 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012299 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012300 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012301 if (FD->getType()->isObjCObjectPointerType() ||
12302 FD->getType().isObjCGCStrong())
12303 Record->setHasObjectMember(true);
12304 else if (Context.getAsArrayType(FD->getType())) {
12305 QualType BaseType = Context.getBaseElementType(FD->getType());
12306 if (BaseType->isRecordType() &&
12307 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012308 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012309 else if (BaseType->isObjCObjectPointerType() ||
12310 BaseType.isObjCGCStrong())
12311 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012312 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012313 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012314 if (Record && FD->getType().isVolatileQualified())
12315 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012316 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012317 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012318 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012319 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012320
Chris Lattner82625602007-01-24 02:26:21 +000012321 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012322 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012323 bool Completed = false;
12324 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12325 if (!CXXRecord->isInvalidDecl()) {
12326 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012327 for (CXXRecordDecl::conversion_iterator
12328 I = CXXRecord->conversion_begin(),
12329 E = CXXRecord->conversion_end(); I != E; ++I)
12330 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012331
12332 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012333 if (CXXRecord->hasUserDeclaredDestructor()) {
12334 // Adjust user-defined destructor exception spec.
12335 if (getLangOpts().CPlusPlus11)
12336 AdjustDestructorExceptionSpec(CXXRecord,
12337 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012338 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012339
Douglas Gregor8fb95122010-09-29 00:15:42 +000012340 // Add any implicitly-declared members to this class.
12341 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12342
12343 // If we have virtual base classes, we may end up finding multiple
12344 // final overriders for a given virtual function. Check for this
12345 // problem now.
12346 if (CXXRecord->getNumVBases()) {
12347 CXXFinalOverriderMap FinalOverriders;
12348 CXXRecord->getFinalOverriders(FinalOverriders);
12349
12350 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12351 MEnd = FinalOverriders.end();
12352 M != MEnd; ++M) {
12353 for (OverridingMethods::iterator SO = M->second.begin(),
12354 SOEnd = M->second.end();
12355 SO != SOEnd; ++SO) {
12356 assert(SO->second.size() > 0 &&
12357 "Virtual function without overridding functions?");
12358 if (SO->second.size() == 1)
12359 continue;
12360
12361 // C++ [class.virtual]p2:
12362 // In a derived class, if a virtual member function of a base
12363 // class subobject has more than one final overrider the
12364 // program is ill-formed.
12365 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012366 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012367 Diag(M->first->getLocation(),
12368 diag::note_overridden_virtual_function);
12369 for (OverridingMethods::overriding_iterator
12370 OM = SO->second.begin(),
12371 OMEnd = SO->second.end();
12372 OM != OMEnd; ++OM)
12373 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012374 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012375
12376 Record->setInvalidDecl();
12377 }
12378 }
12379 CXXRecord->completeDefinition(&FinalOverriders);
12380 Completed = true;
12381 }
12382 }
12383 }
12384 }
12385
12386 if (!Completed)
12387 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012388
David Majnemer2c4e00a2014-01-29 22:07:36 +000012389 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012390 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012391
David Majnemer98c9ee22014-02-07 00:43:07 +000012392 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012393 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012394 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012395 IA->getSemanticSpelling());
12396 }
12397
Serge Pavlov3cb80222013-11-14 02:13:03 +000012398 // Check if the structure/union declaration is a type that can have zero
12399 // size in C. For C this is a language extension, for C++ it may cause
12400 // compatibility problems.
12401 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012402 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012403 CheckForZeroSize = true;
12404 } else {
12405 // For C++ filter out types that cannot be referenced in C code.
12406 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12407 CheckForZeroSize =
12408 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12409 !CXXRecord->isDependentType() &&
12410 CXXRecord->isCLike();
12411 }
12412 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012413 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012414 bool IsEmpty = true;
12415 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012416 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012417 E = Record->field_end();
12418 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12419 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012420 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012421 if (I->getBitWidthValue(Context) > 0)
12422 ZeroSize = false;
12423 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012424 ++NonBitFields;
12425 QualType FieldType = I->getType();
12426 if (FieldType->isIncompleteType() ||
12427 !Context.getTypeSizeInChars(FieldType).isZero())
12428 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012429 }
12430 }
12431
Serge Pavlov3cb80222013-11-14 02:13:03 +000012432 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12433 // allowed in C++, but warn if its declaration is inside
12434 // extern "C" block.
12435 if (ZeroSize) {
12436 Diag(RecLoc, getLangOpts().CPlusPlus ?
12437 diag::warn_zero_size_struct_union_in_extern_c :
12438 diag::warn_zero_size_struct_union_compat)
12439 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12440 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012441
Serge Pavlov3cb80222013-11-14 02:13:03 +000012442 // Structs without named members are extension in C (C99 6.7.2.1p7),
12443 // but are accepted by GCC.
12444 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12445 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12446 diag::ext_no_named_members_in_struct_union)
12447 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012448 }
12449 }
Chris Lattner622c1932008-02-06 00:51:33 +000012450 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012451 ObjCIvarDecl **ClsFields =
12452 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012453 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012454 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012455 // Add ivar's to class's DeclContext.
12456 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12457 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012458 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012459 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012460 // Must enforce the rule that ivars in the base classes may not be
12461 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012462 if (ID->getSuperClass())
12463 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012464 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012465 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012466 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012467 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12468 // Ivar declared in @implementation never belongs to the implementation.
12469 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012470 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012471 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012472 IMPDecl->setIvarLBraceLoc(LBrac);
12473 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012474 } else if (ObjCCategoryDecl *CDecl =
12475 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012476 // case of ivars in class extension; all other cases have been
12477 // reported as errors elsewhere.
12478 // FIXME. Class extension does not have a LocEnd field.
12479 // CDecl->setLocEnd(RBrac);
12480 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012481 // Diagnose redeclaration of private ivars.
12482 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012483 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012484 if (IDecl) {
12485 if (const ObjCIvarDecl *ClsIvar =
12486 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12487 Diag(ClsFields[i]->getLocation(),
12488 diag::err_duplicate_ivar_declaration);
12489 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12490 continue;
12491 }
Aaron Ballmanb4a53452014-03-13 21:57:01 +000012492 for (const auto *Ext : IDecl->known_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012493 if (const ObjCIvarDecl *ClsExtIvar
12494 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012495 Diag(ClsFields[i]->getLocation(),
12496 diag::err_duplicate_ivar_declaration);
12497 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12498 continue;
12499 }
12500 }
12501 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012502 ClsFields[i]->setLexicalDeclContext(CDecl);
12503 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012504 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012505 CDecl->setIvarLBraceLoc(LBrac);
12506 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012507 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012508 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012509
12510 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012511 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012512}
12513
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012514/// \brief Determine whether the given integral value is representable within
12515/// the given type T.
12516static bool isRepresentableIntegerValue(ASTContext &Context,
12517 llvm::APSInt &Value,
12518 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012519 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012520 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012521
Douglas Gregor0bf31402010-10-08 23:50:27 +000012522 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012523 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012524 --BitWidth;
12525 return Value.getActiveBits() <= BitWidth;
12526 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012527 return Value.getMinSignedBits() <= BitWidth;
12528}
12529
12530// \brief Given an integral type, return the next larger integral type
12531// (or a NULL type of no such type exists).
12532static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12533 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12534 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012535 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012536 const unsigned NumTypes = 4;
12537 QualType SignedIntegralTypes[NumTypes] = {
12538 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12539 };
12540 QualType UnsignedIntegralTypes[NumTypes] = {
12541 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12542 Context.UnsignedLongLongTy
12543 };
12544
12545 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012546 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12547 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012548 for (unsigned I = 0; I != NumTypes; ++I)
12549 if (Context.getTypeSize(Types[I]) > BitWidth)
12550 return Types[I];
12551
12552 return QualType();
12553}
12554
Douglas Gregor954f6b272009-03-17 19:05:46 +000012555EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12556 EnumConstantDecl *LastEnumConst,
12557 SourceLocation IdLoc,
12558 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012559 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012560 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012561 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012562 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012563
12564 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
Craig Topperc3ec1492014-05-26 06:22:03 +000012565 Val = nullptr;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012566
Eli Friedman7c6515a2011-12-06 00:10:34 +000012567 if (Val)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012568 Val = DefaultLvalueConversion(Val).get();
Eli Friedman7c6515a2011-12-06 00:10:34 +000012569
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012570 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012571 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012572 EltTy = Context.DependentTy;
12573 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012574 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012575 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012576 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012577 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12578 // constant-expression in the enumerator-definition shall be a converted
12579 // constant expression of the underlying type.
12580 EltTy = Enum->getIntegerType();
12581 ExprResult Converted =
12582 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12583 CCEK_Enumerator);
12584 if (Converted.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +000012585 Val = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +000012586 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012587 Val = Converted.get();
Richard Smithf8379a02012-01-18 23:55:52 +000012588 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012589 !(Val = VerifyIntegerConstantExpression(Val,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012590 &EnumVal).get())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012591 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012592 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012593 if (Enum->isFixed()) {
12594 EltTy = Enum->getIntegerType();
12595
Richard Smithf8379a02012-01-18 23:55:52 +000012596 // In Obj-C and Microsoft mode, require the enumeration value to be
12597 // representable in the underlying type of the enumeration. In C++11,
12598 // we perform a non-narrowing conversion as part of converted constant
12599 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012600 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012601 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012602 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012603 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +000012604 } else
12605 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012606 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012607 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012608 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012609 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012610 // If the underlying type is not fixed, the type of each enumerator
12611 // is the type of its initializing value:
12612 // - If an initializer is specified for an enumerator, the
12613 // initializing value has the same type as the expression.
12614 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012615 } else {
12616 // C99 6.7.2.2p2:
12617 // The expression that defines the value of an enumeration constant
12618 // shall be an integer constant expression that has a value
12619 // representable as an int.
12620
12621 // Complain if the value is not representable in an int.
12622 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12623 Diag(IdLoc, diag::ext_enum_value_not_int)
12624 << EnumVal.toString(10) << Val->getSourceRange()
12625 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12626 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12627 // Force the type of the expression to 'int'.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012628 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
Eli Friedman2beed112012-02-07 04:34:38 +000012629 }
12630 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012631 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012632 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012633 }
12634 }
Mike Stump11289f42009-09-09 15:08:12 +000012635
Douglas Gregor954f6b272009-03-17 19:05:46 +000012636 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012637 if (Enum->isDependentType())
12638 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012639 else if (!LastEnumConst) {
12640 // C++0x [dcl.enum]p5:
12641 // If the underlying type is not fixed, the type of each enumerator
12642 // is the type of its initializing value:
12643 // - If no initializer is specified for the first enumerator, the
12644 // initializing value has an unspecified integral type.
12645 //
12646 // GCC uses 'int' for its unspecified integral type, as does
12647 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012648 if (Enum->isFixed()) {
12649 EltTy = Enum->getIntegerType();
12650 }
12651 else {
12652 EltTy = Context.IntTy;
12653 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012654 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012655 // Assign the last value + 1.
12656 EnumVal = LastEnumConst->getInitVal();
12657 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012658 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012659
12660 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012661 if (EnumVal < LastEnumConst->getInitVal()) {
12662 // C++0x [dcl.enum]p5:
12663 // If the underlying type is not fixed, the type of each enumerator
12664 // is the type of its initializing value:
12665 //
12666 // - Otherwise the type of the initializing value is the same as
12667 // the type of the initializing value of the preceding enumerator
12668 // unless the incremented value is not representable in that type,
12669 // in which case the type is an unspecified integral type
12670 // sufficient to contain the incremented value. If no such type
12671 // exists, the program is ill-formed.
12672 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012673 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012674 // There is no integral type larger enough to represent this
12675 // value. Complain, then allow the value to wrap around.
12676 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012677 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012678 ++EnumVal;
12679 if (Enum->isFixed())
12680 // When the underlying type is fixed, this is ill-formed.
12681 Diag(IdLoc, diag::err_enumerator_wrapped)
12682 << EnumVal.toString(10)
12683 << EltTy;
12684 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012685 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012686 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012687 } else {
12688 EltTy = T;
12689 }
12690
12691 // Retrieve the last enumerator's value, extent that type to the
12692 // type that is supposed to be large enough to represent the incremented
12693 // value, then increment.
12694 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012695 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012696 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012697 ++EnumVal;
12698
12699 // If we're not in C++, diagnose the overflow of enumerator values,
12700 // which in C99 means that the enumerator value is not representable in
12701 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12702 // permits enumerator values that are representable in some larger
12703 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012704 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012705 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012706 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012707 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12708 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12709 Diag(IdLoc, diag::ext_enum_value_not_int)
12710 << EnumVal.toString(10) << 1;
12711 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012712 }
12713 }
Mike Stump11289f42009-09-09 15:08:12 +000012714
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012715 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012716 // Make the enumerator value match the signedness and size of the
12717 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012718 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012719 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012720 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012721
Douglas Gregor954f6b272009-03-17 19:05:46 +000012722 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012723 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012724}
12725
12726
John McCall811a0f52010-10-22 23:36:17 +000012727Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12728 SourceLocation IdLoc, IdentifierInfo *Id,
12729 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012730 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012731 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012732 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012733 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012734
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012735 // The scope passed in may not be a decl scope. Zip up the scope tree until
12736 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012737 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012738
Chris Lattner8116d1b2007-01-25 22:38:29 +000012739 // Verify that there isn't already something declared with this name in this
12740 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012741 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012742 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012743 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012744 // Maybe we will complain about the shadowed template parameter.
12745 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12746 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012747 PrevDecl = nullptr;
Douglas Gregor5101c242008-12-05 18:15:24 +000012748 }
12749
12750 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012751 // When in C++, we may get a TagDecl with the same name; in this case the
12752 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012753 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012754 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012755 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012756 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012757 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012758 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012759 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012760 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000012761 return nullptr;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012762 }
12763 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012764
Aaron Ballman24a10472012-07-19 03:12:23 +000012765 // C++ [class.mem]p15:
12766 // If T is the name of a class, then each of the following shall have a name
12767 // different from T:
12768 // - every enumerator of every member of class T that is an unscoped
12769 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012770 if (CXXRecordDecl *Record
12771 = dyn_cast<CXXRecordDecl>(
12772 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012773 if (!TheEnumDecl->isScoped() &&
12774 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012775 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12776
John McCall811a0f52010-10-22 23:36:17 +000012777 EnumConstantDecl *New =
12778 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012779
John McCall553c0792010-01-23 00:46:32 +000012780 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012781 // Process attributes.
12782 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12783
12784 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012785 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012786 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012787 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012788
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012789 ActOnDocumentableDecl(New);
12790
John McCall48871652010-08-21 09:40:31 +000012791 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012792}
12793
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012794// Returns true when the enum initial expression does not trigger the
12795// duplicate enum warning. A few common cases are exempted as follows:
12796// Element2 = Element1
12797// Element2 = Element1 + 1
12798// Element2 = Element1 - 1
12799// Where Element2 and Element1 are from the same enum.
12800static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12801 Expr *InitExpr = ECD->getInitExpr();
12802 if (!InitExpr)
12803 return true;
12804 InitExpr = InitExpr->IgnoreImpCasts();
12805
12806 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12807 if (!BO->isAdditiveOp())
12808 return true;
12809 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12810 if (!IL)
12811 return true;
12812 if (IL->getValue() != 1)
12813 return true;
12814
12815 InitExpr = BO->getLHS();
12816 }
12817
12818 // This checks if the elements are from the same enum.
12819 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12820 if (!DRE)
12821 return true;
12822
12823 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12824 if (!EnumConstant)
12825 return true;
12826
12827 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12828 Enum)
12829 return true;
12830
12831 return false;
12832}
12833
12834struct DupKey {
12835 int64_t val;
12836 bool isTombstoneOrEmptyKey;
12837 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12838 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12839};
12840
12841static DupKey GetDupKey(const llvm::APSInt& Val) {
12842 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12843 false);
12844}
12845
12846struct DenseMapInfoDupKey {
12847 static DupKey getEmptyKey() { return DupKey(0, true); }
12848 static DupKey getTombstoneKey() { return DupKey(1, true); }
12849 static unsigned getHashValue(const DupKey Key) {
12850 return (unsigned)(Key.val * 37);
12851 }
12852 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12853 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12854 LHS.val == RHS.val;
12855 }
12856};
12857
12858// Emits a warning when an element is implicitly set a value that
12859// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012860static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12861 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012862 QualType EnumType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012863 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012864 return;
12865 // Avoid anonymous enums
12866 if (!Enum->getIdentifier())
12867 return;
12868
12869 // Only check for small enums.
12870 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12871 return;
12872
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012873 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12874 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012875
12876 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12877 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12878 ValueToVectorMap;
12879
12880 DuplicatesVector DupVector;
12881 ValueToVectorMap EnumMap;
12882
12883 // Populate the EnumMap with all values represented by enum constants without
12884 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012885 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012886 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012887
12888 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12889 // this constant. Skip this enum since it may be ill-formed.
12890 if (!ECD) {
12891 return;
12892 }
12893
12894 if (ECD->getInitExpr())
12895 continue;
12896
12897 DupKey Key = GetDupKey(ECD->getInitVal());
12898 DeclOrVector &Entry = EnumMap[Key];
12899
12900 // First time encountering this value.
12901 if (Entry.isNull())
12902 Entry = ECD;
12903 }
12904
12905 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012906 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012907 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12908 if (!ValidDuplicateEnum(ECD, Enum))
12909 continue;
12910
12911 DupKey Key = GetDupKey(ECD->getInitVal());
12912
12913 DeclOrVector& Entry = EnumMap[Key];
12914 if (Entry.isNull())
12915 continue;
12916
12917 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12918 // Ensure constants are different.
12919 if (D == ECD)
12920 continue;
12921
12922 // Create new vector and push values onto it.
12923 ECDVector *Vec = new ECDVector();
12924 Vec->push_back(D);
12925 Vec->push_back(ECD);
12926
12927 // Update entry to point to the duplicates vector.
12928 Entry = Vec;
12929
12930 // Store the vector somewhere we can consult later for quick emission of
12931 // diagnostics.
12932 DupVector.push_back(Vec);
12933 continue;
12934 }
12935
12936 ECDVector *Vec = Entry.get<ECDVector*>();
12937 // Make sure constants are not added more than once.
12938 if (*Vec->begin() == ECD)
12939 continue;
12940
12941 Vec->push_back(ECD);
12942 }
12943
12944 // Emit diagnostics.
12945 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12946 DupVectorEnd = DupVector.end();
12947 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12948 ECDVector *Vec = *DupVectorIter;
12949 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12950
12951 // Emit warning for one enum constant.
12952 ECDVector::iterator I = Vec->begin();
12953 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12954 << (*I)->getName() << (*I)->getInitVal().toString(10)
12955 << (*I)->getSourceRange();
12956 ++I;
12957
12958 // Emit one note for each of the remaining enum constants with
12959 // the same value.
12960 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12961 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12962 << (*I)->getName() << (*I)->getInitVal().toString(10)
12963 << (*I)->getSourceRange();
12964 delete Vec;
12965 }
12966}
12967
Mike Stump6814d1c2009-05-16 07:06:02 +000012968void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000012969 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012970 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012971 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000012972 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000012973 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000012974
12975 if (Attr)
12976 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000012977
Eli Friedmand0e60972009-12-11 01:34:50 +000012978 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012979 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012980 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000012981 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000012982 if (!ECD) continue;
12983
12984 ECD->setType(EnumType);
12985 }
12986
John McCall9aa35be2010-05-06 08:49:23 +000012987 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000012988 return;
12989 }
12990
Chris Lattner67933c02007-08-28 05:10:31 +000012991 // TODO: If the result value doesn't fit in an int, it must be a long or long
12992 // long value. ISO C does not support this, but GCC does as an extension,
12993 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000012994 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12995 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12996 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000012997
Chris Lattnerb8a501c2007-08-28 06:15:15 +000012998 // Verify that all the values are okay, compute the size of the values, and
12999 // reverse the list.
13000 unsigned NumNegativeBits = 0;
13001 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000013002
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013003 // Keep track of whether all elements have type int.
13004 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000013005
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013006 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000013007 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000013008 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013009 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000013010
Chris Lattnerbf478cb2007-08-28 05:27:00 +000013011 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000013012
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013013 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000013014 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000013015 NumPositiveBits = std::max(NumPositiveBits,
13016 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013017 else
Chris Lattner49f980c2008-01-14 21:47:29 +000013018 NumNegativeBits = std::max(NumNegativeBits,
13019 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000013020
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013021 // Keep track of whether every enum element has type int (very commmon).
13022 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000013023 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000013024 }
Mike Stump11289f42009-09-09 15:08:12 +000013025
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013026 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013027 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013028 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013029
John McCall56774992009-12-09 09:09:27 +000013030 // C++0x N3000 [conv.prom]p3:
13031 // An rvalue of an unscoped enumeration type whose underlying
13032 // type is not fixed can be converted to an rvalue of the first
13033 // of the following types that can represent all the values of
13034 // the enumeration: int, unsigned int, long int, unsigned long
13035 // int, long long int, or unsigned long long int.
13036 // C99 6.4.4.3p2:
13037 // An identifier declared as an enumeration constant has type int.
13038 // The C99 rule is modified by a gcc extension
13039 QualType BestPromotionType;
13040
Aaron Ballman9ead1242013-12-19 02:39:40 +000013041 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000013042 // -fshort-enums is the equivalent to specifying the packed attribute on all
13043 // enum definitions.
13044 if (LangOpts.ShortEnums)
13045 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013046
Douglas Gregor0bf31402010-10-08 23:50:27 +000013047 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000013048 BestType = Enum->getIntegerType();
13049 if (BestType->isPromotableIntegerType())
13050 BestPromotionType = Context.getPromotedIntegerType(BestType);
13051 else
13052 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000013053 // We don't need to set BestWidth, because BestType is going to be the type
13054 // of the enumerators, but we do anyway because otherwise some compilers
13055 // warn that it might be used uninitialized.
13056 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000013057 }
13058 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000013059 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013060 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013061 // If it's packed, check also if it fits a char or a short.
13062 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013063 BestType = Context.SignedCharTy;
13064 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000013065 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013066 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013067 BestType = Context.ShortTy;
13068 BestWidth = ShortWidth;
13069 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013070 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013071 BestWidth = IntWidth;
13072 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013073 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013074
John McCall56774992009-12-09 09:09:27 +000013075 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013076 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000013077 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013078 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013079
Chris Lattner3a370bf2007-08-29 17:31:48 +000013080 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000013081 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013082 BestType = Context.LongLongTy;
13083 }
13084 }
John McCall56774992009-12-09 09:09:27 +000013085 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013086 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000013087 // If there is no negative value, figure out the smallest type that fits
13088 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013089 // If it's packed, check also if it fits a char or a short.
13090 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013091 BestType = Context.UnsignedCharTy;
13092 BestPromotionType = Context.IntTy;
13093 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013094 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013095 BestType = Context.UnsignedShortTy;
13096 BestPromotionType = Context.IntTy;
13097 BestWidth = ShortWidth;
13098 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013099 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013100 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000013101 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013102 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013103 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013104 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000013105 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013106 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013107 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013108 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013109 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000013110 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013111 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013112 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013113 "How could an initializer get larger than ULL?");
13114 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013115 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013116 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013117 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013118 }
13119 }
Mike Stump11289f42009-09-09 15:08:12 +000013120
Chris Lattner3a370bf2007-08-29 17:31:48 +000013121 // Loop over all of the enumerator constants, changing their types to match
13122 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013123 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000013124 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013125 if (!ECD) continue; // Already issued a diagnostic.
13126
13127 // Standard C says the enumerators have int type, but we allow, as an
13128 // extension, the enumerators to be larger than int size. If each
13129 // enumerator value fits in an int, type it as an int, otherwise type it the
13130 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
13131 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000013132
13133 // Determine whether the value fits into an int.
13134 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013135
13136 // If it fits into an integer type, force it. Otherwise force it to match
13137 // the enum decl type.
13138 QualType NewTy;
13139 unsigned NewWidth;
13140 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000013141 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000013142 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013143 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000013144 NewTy = Context.IntTy;
13145 NewWidth = IntWidth;
13146 NewSign = true;
13147 } else if (ECD->getType() == BestType) {
13148 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000013149 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013150 // C++ [dcl.enum]p4: Following the closing brace of an
13151 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013152 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013153 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013154 continue;
13155 } else {
13156 NewTy = BestType;
13157 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013158 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013159 }
13160
13161 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000013162 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013163 InitVal.setIsSigned(NewSign);
13164 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000013165
Chris Lattner3a370bf2007-08-29 17:31:48 +000013166 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000013167 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000013168 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000013169 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000013170 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000013171 ECD->getInitExpr(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013172 /*base paths*/ nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013173 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000013174 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013175 // C++ [dcl.enum]p4: Following the closing brace of an
13176 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013177 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013178 ECD->setType(EnumType);
13179 else
13180 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013181 }
Mike Stump11289f42009-09-09 15:08:12 +000013182
John McCall9aa35be2010-05-06 08:49:23 +000013183 Enum->completeDefinition(BestType, BestPromotionType,
13184 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000013185
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013186 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000013187
13188 // Now that the enum type is defined, ensure it's not been underaligned.
13189 if (Enum->hasAttrs())
13190 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013191}
Chris Lattner1300fb92007-01-23 23:42:53 +000013192
Abramo Bagnara348823a2011-03-03 14:20:18 +000013193Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13194 SourceLocation StartLoc,
13195 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000013196 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000013197
Douglas Gregor278f52e2009-05-30 00:08:05 +000013198 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000013199 AsmString, StartLoc,
13200 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013201 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000013202 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000013203}
Eli Friedman5ed51982009-06-05 02:44:36 +000013204
Richard Smith77944862014-03-02 05:58:18 +000013205static void checkModuleImportContext(Sema &S, Module *M,
13206 SourceLocation ImportLoc,
13207 DeclContext *DC) {
13208 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13209 switch (LSD->getLanguage()) {
13210 case LinkageSpecDecl::lang_c:
13211 if (!M->IsExternC) {
13212 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13213 << M->getFullModuleName();
13214 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13215 return;
13216 }
13217 break;
13218 case LinkageSpecDecl::lang_cxx:
13219 break;
13220 }
13221 DC = LSD->getParent();
13222 }
13223
13224 while (isa<LinkageSpecDecl>(DC))
13225 DC = DC->getParent();
13226 if (!isa<TranslationUnitDecl>(DC)) {
13227 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13228 << M->getFullModuleName() << DC;
13229 S.Diag(cast<Decl>(DC)->getLocStart(),
13230 diag::note_module_import_not_at_top_level)
13231 << DC;
13232 }
13233}
13234
Douglas Gregor22d09742012-01-03 18:04:46 +000013235DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13236 SourceLocation ImportLoc,
13237 ModuleIdPath Path) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000013238 Module *Mod =
13239 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13240 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013241 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013242 return true;
Richard Smith77944862014-03-02 05:58:18 +000013243
13244 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13245
Ben Langmuir527040e2014-05-05 05:31:33 +000013246 // FIXME: we should support importing a submodule within a different submodule
13247 // of the same top-level module. Until we do, make it an error rather than
13248 // silently ignoring the import.
13249 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13250 Diag(ImportLoc, diag::err_module_self_import)
13251 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13252
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013253 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013254 Module *ModCheck = Mod;
13255 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13256 // If we've run out of module parents, just drop the remaining identifiers.
13257 // We need the length to be consistent.
13258 if (!ModCheck)
13259 break;
13260 ModCheck = ModCheck->Parent;
13261
13262 IdentifierLocs.push_back(Path[I].second);
13263 }
13264
13265 ImportDecl *Import = ImportDecl::Create(Context,
13266 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013267 AtLoc.isValid()? AtLoc : ImportLoc,
13268 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013269 Context.getTranslationUnitDecl()->addDecl(Import);
13270 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013271}
13272
Richard Smithce587f52013-11-15 04:24:58 +000013273void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013274 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13275
Richard Smithce587f52013-11-15 04:24:58 +000013276 // FIXME: Should we synthesize an ImportDecl here?
Alp Tokerb6cc5922014-05-03 03:45:55 +000013277 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13278 /*Complain=*/true);
Richard Smithce587f52013-11-15 04:24:58 +000013279}
13280
Richard Smith3d23c422014-05-07 02:25:43 +000013281void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13282 Module *Mod) {
13283 // Bail if we're not allowed to implicitly import a module here.
13284 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13285 return;
13286
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013287 // Create the implicit import declaration.
13288 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13289 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13290 Loc, Mod, Loc);
13291 TU->addDecl(ImportD);
13292 Consumer.HandleImplicitImportDecl(ImportD);
13293
13294 // Make the module visible.
Alp Tokerb6cc5922014-05-03 03:45:55 +000013295 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13296 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013297}
13298
David Chisnall0867d9c2012-02-18 16:12:34 +000013299void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13300 IdentifierInfo* AliasName,
13301 SourceLocation PragmaLoc,
13302 SourceLocation NameLoc,
13303 SourceLocation AliasNameLoc) {
13304 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13305 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013306 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13307 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013308
13309 if (PrevDecl)
13310 PrevDecl->addAttr(Attr);
13311 else
13312 (void)ExtnameUndeclaredIdentifiers.insert(
13313 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13314}
13315
Eli Friedman5ed51982009-06-05 02:44:36 +000013316void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13317 SourceLocation PragmaLoc,
13318 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013319 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013320
Eli Friedman5ed51982009-06-05 02:44:36 +000013321 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013322 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013323 } else {
13324 (void)WeakUndeclaredIdentifiers.insert(
13325 std::pair<IdentifierInfo*,WeakInfo>
Craig Topperc3ec1492014-05-26 06:22:03 +000013326 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013327 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013328}
13329
13330void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13331 IdentifierInfo* AliasName,
13332 SourceLocation PragmaLoc,
13333 SourceLocation NameLoc,
13334 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013335 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13336 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013337 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013338
Eli Friedman5ed51982009-06-05 02:44:36 +000013339 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013340 if (!PrevDecl->hasAttr<AliasAttr>())
13341 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013342 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013343 } else {
13344 (void)WeakUndeclaredIdentifiers.insert(
13345 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013346 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013347}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013348
13349Decl *Sema::getObjCDeclContext() const {
13350 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13351}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013352
13353AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013354 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013355 // If we are within an Objective-C method, we should consult
13356 // both the availability of the method as well as the
13357 // enclosing class. If the class is (say) deprecated,
13358 // the entire method is considered deprecated from the
13359 // purpose of checking if the current context is deprecated.
13360 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13361 AvailabilityResult R = MD->getAvailability();
13362 if (R != AR_Available)
13363 return R;
13364 D = MD->getClassInterface();
13365 }
13366 // If we are within an Objective-c @implementation, it
13367 // gets the same availability context as the @interface.
13368 else if (const ObjCImplementationDecl *ID =
13369 dyn_cast<ObjCImplementationDecl>(D)) {
13370 D = ID->getClassInterface();
13371 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013372 return D->getAvailability();
13373}