blob: 849926327d0814e937feea7307e87e0e20a139d5 [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
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000441void 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 }
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000486 return;
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 }
Reid Klecknerc05ca5e2014-06-19 01:23:22 +0000505 return;
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000506 }
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 }
Douglas Gregor15e56022009-10-13 23:27:22 +0000532}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000533
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000534/// \brief Determine whether the given result set contains either a type name
535/// or
536static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000538 NextToken.is(tok::less);
539
540 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
541 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
542 return true;
543
544 if (CheckTemplate && isa<TemplateDecl>(*I))
545 return true;
546 }
547
548 return false;
549}
550
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000551static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
552 Scope *S, CXXScopeSpec &SS,
553 IdentifierInfo *&Name,
554 SourceLocation NameLoc) {
Richard Smithaa31b4b2012-09-06 01:37:56 +0000555 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
556 SemaRef.LookupParsedName(R, S, &SS);
557 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
Alp Toker68837432014-05-20 22:03:47 +0000558 StringRef FixItTagName;
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000559 switch (Tag->getTagKind()) {
560 case TTK_Class:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000561 FixItTagName = "class ";
562 break;
563
564 case TTK_Enum:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000565 FixItTagName = "enum ";
566 break;
567
568 case TTK_Struct:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000569 FixItTagName = "struct ";
570 break;
571
Joao Matosdc86f942012-08-31 18:45:21 +0000572 case TTK_Interface:
Joao Matosdc86f942012-08-31 18:45:21 +0000573 FixItTagName = "__interface ";
574 break;
575
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000576 case TTK_Union:
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000577 FixItTagName = "union ";
578 break;
579 }
580
Alp Toker68837432014-05-20 22:03:47 +0000581 StringRef TagName = FixItTagName.drop_back();
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000582 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
583 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
584 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
585
Richard Smithaa31b4b2012-09-06 01:37:56 +0000586 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
587 I != IEnd; ++I)
588 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
589 << Name << TagName;
590
591 // Replace lookup results with just the tag decl.
592 Result.clear(Sema::LookupTagName);
593 SemaRef.LookupParsedName(Result, S, &SS);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000594 return true;
595 }
596
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000597 return false;
598}
599
Richard Smith4f605af2012-08-18 00:55:03 +0000600/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
601static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
602 QualType T, SourceLocation NameLoc) {
603 ASTContext &Context = S.Context;
604
605 TypeLocBuilder Builder;
606 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
607
608 T = S.getElaboratedType(ETK_None, SS, T);
609 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
610 ElabTL.setElaboratedKeywordLoc(SourceLocation());
611 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
612 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
613}
614
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000615Sema::NameClassification Sema::ClassifyName(Scope *S,
616 CXXScopeSpec &SS,
617 IdentifierInfo *&Name,
618 SourceLocation NameLoc,
Richard Smith4f605af2012-08-18 00:55:03 +0000619 const Token &NextToken,
620 bool IsAddressOfOperand,
621 CorrectionCandidateCallback *CCC) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000622 DeclarationNameInfo NameInfo(Name, NameLoc);
623 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000624
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000625 if (NextToken.is(tok::coloncolon)) {
626 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000627 QualType(), false, SS, nullptr, false);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000628 }
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000629
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000630 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
631 LookupParsedName(Result, S, &SS, !CurMethod);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000632
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000633 // Perform lookup for Objective-C instance variables (including automatically
634 // synthesized instance variables), if we're in an Objective-C method.
635 // FIXME: This lookup really, really needs to be folded in to the normal
636 // unqualified lookup mechanism.
637 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
638 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000639 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000640 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000641 }
642
643 bool SecondTry = false;
644 bool IsFilteredTemplateName = false;
645
646Corrected:
647 switch (Result.getResultKind()) {
648 case LookupResult::NotFound:
649 // If an unqualified-id is followed by a '(', then we have a function
650 // call.
651 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
652 // In C++, this is an ADL-only call.
653 // FIXME: Reference?
David Blaikiebbafb8a2012-03-11 07:00:24 +0000654 if (getLangOpts().CPlusPlus)
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000655 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
656
657 // C90 6.3.2.2:
658 // If the expression that precedes the parenthesized argument list in a
659 // function call consists solely of an identifier, and if no
660 // declaration is visible for this identifier, the identifier is
661 // implicitly declared exactly as if, in the innermost block containing
662 // the function call, the declaration
663 //
664 // extern int identifier ();
665 //
666 // appeared.
667 //
668 // We also allow this in C99 as an extension.
669 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
670 Result.addDecl(D);
671 Result.resolveKind();
672 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
673 }
674 }
675
676 // In C, we first see whether there is a tag type by the same name, in
677 // which case it's likely that the user just forget to write "enum",
678 // "struct", or "union".
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000679 if (!getLangOpts().CPlusPlus && !SecondTry &&
680 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
681 break;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000682 }
683
684 // Perform typo correction to determine if there is another name that is
685 // close to this name.
Richard Smith4f605af2012-08-18 00:55:03 +0000686 if (!SecondTry && CCC) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000687 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000688 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
David Blaikie30d15442011-10-19 22:56:21 +0000689 Result.getLookupKind(), S,
John Thompson2255f2c2014-04-23 12:57:01 +0000690 &SS, *CCC,
691 CTK_ErrorRecovery)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000692 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
693 unsigned QualifiedDiag = diag::err_no_member_suggest;
Richard Smithf9b15102013-08-17 00:46:16 +0000694
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000695 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000696 NamedDecl *UnderlyingFirstDecl
Craig Topperc3ec1492014-05-26 06:22:03 +0000697 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000698 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000699 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000700 UnqualifiedDiag = diag::err_no_template_suggest;
701 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000702 } else if (UnderlyingFirstDecl &&
703 (isa<TypeDecl>(UnderlyingFirstDecl) ||
704 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
705 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
David Blaikie9db06042013-03-21 21:35:15 +0000706 UnqualifiedDiag = diag::err_unknown_typename_suggest;
707 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
708 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000709
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000710 if (SS.isEmpty()) {
Richard Smithf9b15102013-08-17 00:46:16 +0000711 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000712 } else {// FIXME: is this even reachable? Test it.
Richard Smithf9b15102013-08-17 00:46:16 +0000713 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
714 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000715 Name->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +0000716 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
717 << Name << computeDeclContext(SS, false)
718 << DroppedSpecifier << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000719 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000720
721 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000722 Name = Corrected.getCorrectionAsIdentifierInfo();
Richard Smithf9b15102013-08-17 00:46:16 +0000723
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000724 // Typo correction corrected to a keyword.
725 if (Corrected.isKeyword())
Richard Smithf9b15102013-08-17 00:46:16 +0000726 return Name;
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000727
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000728 // Also update the LookupResult...
729 // FIXME: This should probably go away at some point
730 Result.clear();
731 Result.setLookupName(Corrected.getCorrection());
Richard Smithf9b15102013-08-17 00:46:16 +0000732 if (FirstDecl)
Kaelyn Uhrain9ce58bd2012-01-24 19:45:35 +0000733 Result.addDecl(FirstDecl);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000734
735 // If we found an Objective-C instance variable, let
736 // LookupInObjCMethod build the appropriate expression to
737 // reference the ivar.
738 // FIXME: This is a gross hack.
739 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
740 Result.clear();
741 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000742 return E;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000743 }
744
745 goto Corrected;
746 }
747 }
748
749 // We failed to correct; just fall through and let the parser deal with it.
750 Result.suppressDiagnostics();
751 return NameClassification::Unknown();
752
Abramo Bagnara7945c982012-01-27 09:46:47 +0000753 case LookupResult::NotFoundInCurrentInstantiation: {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000754 // We performed name lookup into the current instantiation, and there were
755 // dependent bases, so we treat this result the same way as any other
756 // dependent nested-name-specifier.
757
758 // C++ [temp.res]p2:
759 // A name used in a template declaration or definition and that is
760 // dependent on a template-parameter is assumed not to name a type
761 // unless the applicable name lookup finds a type name or the name is
762 // qualified by the keyword typename.
763 //
764 // FIXME: If the next token is '<', we might want to ask the parser to
765 // perform some heroics to see if we actually have a
766 // template-argument-list, which would indicate a missing 'template'
767 // keyword here.
Richard Smith4f605af2012-08-18 00:55:03 +0000768 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
769 NameInfo, IsAddressOfOperand,
Craig Topperc3ec1492014-05-26 06:22:03 +0000770 /*TemplateArgs=*/nullptr);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000771 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000772
773 case LookupResult::Found:
774 case LookupResult::FoundOverloaded:
775 case LookupResult::FoundUnresolvedValue:
776 break;
777
778 case LookupResult::Ambiguous:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000779 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000780 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000781 // C++ [temp.local]p3:
782 // A lookup that finds an injected-class-name (10.2) can result in an
783 // ambiguity in certain cases (for example, if it is found in more than
784 // one base class). If all of the injected-class-names that are found
785 // refer to specializations of the same class template, and if the name
786 // is followed by a template-argument-list, the reference refers to the
787 // class template itself and not a specialization thereof, and is not
788 // ambiguous.
789 //
790 // This filtering can make an ambiguous result into an unambiguous one,
791 // so try again after filtering out template names.
792 FilterAcceptableTemplateNames(Result);
793 if (!Result.isAmbiguous()) {
794 IsFilteredTemplateName = true;
795 break;
796 }
797 }
798
799 // Diagnose the ambiguity and return an error.
800 return NameClassification::Error();
801 }
802
David Blaikiebbafb8a2012-03-11 07:00:24 +0000803 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000804 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
805 // C++ [temp.names]p3:
806 // After name lookup (3.4) finds that a name is a template-name or that
807 // an operator-function-id or a literal- operator-id refers to a set of
808 // overloaded functions any member of which is a function template if
809 // this is followed by a <, the < is always taken as the delimiter of a
810 // template-argument-list and never as the less-than operator.
811 if (!IsFilteredTemplateName)
812 FilterAcceptableTemplateNames(Result);
813
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000814 if (!Result.empty()) {
815 bool IsFunctionTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000816 bool IsVarTemplate;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000817 TemplateName Template;
818 if (Result.end() - Result.begin() > 1) {
819 IsFunctionTemplate = true;
820 Template = Context.getOverloadedTemplateName(Result.begin(),
821 Result.end());
822 } else {
823 TemplateDecl *TD
824 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
825 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000826 IsVarTemplate = isa<VarTemplateDecl>(TD);
827
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000828 if (SS.isSet() && !SS.isInvalid())
829 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000830 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000831 TD);
832 else
833 Template = TemplateName(TD);
834 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000835
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000836 if (IsFunctionTemplate) {
837 // Function templates always go through overload resolution, at which
838 // point we'll perform the various checks (e.g., accessibility) we need
839 // to based on which function we selected.
840 Result.suppressDiagnostics();
841
842 return NameClassification::FunctionTemplate(Template);
843 }
Larisse Voufo39a1e502013-08-06 01:03:05 +0000844
845 return IsVarTemplate ? NameClassification::VarTemplate(Template)
846 : NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000847 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000848 }
Richard Smith4f605af2012-08-18 00:55:03 +0000849
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000850 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000851 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
852 DiagnoseUseOfDecl(Type, NameLoc);
853 QualType T = Context.getTypeDeclType(Type);
Richard Smith4f605af2012-08-18 00:55:03 +0000854 if (SS.isNotEmpty())
855 return buildNestedType(*this, SS, T, NameLoc);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000856 return ParsedType::make(T);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000857 }
Richard Smith4f605af2012-08-18 00:55:03 +0000858
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000859 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
860 if (!Class) {
861 // FIXME: It's unfortunate that we don't have a Type node for handling this.
Nico Weberdfc59202014-05-03 22:07:35 +0000862 if (ObjCCompatibleAliasDecl *Alias =
863 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000864 Class = Alias->getClassInterface();
865 }
866
867 if (Class) {
868 DiagnoseUseOfDecl(Class, NameLoc);
869
870 if (NextToken.is(tok::period)) {
871 // Interface. <something> is parsed as a property reference expression.
872 // Just return "unknown" as a fall-through for now.
873 Result.suppressDiagnostics();
874 return NameClassification::Unknown();
875 }
876
877 QualType T = Context.getObjCInterfaceType(Class);
878 return ParsedType::make(T);
879 }
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000880
Richard Smith4f605af2012-08-18 00:55:03 +0000881 // We can have a type template here if we're classifying a template argument.
882 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
883 return NameClassification::TypeTemplate(
884 TemplateName(cast<TemplateDecl>(FirstDecl)));
885
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000886 // Check for a tag type hidden by a non-type decl in a few cases where it
887 // seems likely a type is wanted instead of the non-type that was found.
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000888 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
889 if ((NextToken.is(tok::identifier) ||
Alp Tokera2794f92014-01-22 07:29:52 +0000890 (NextIsOp &&
891 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
Argyrios Kyrtzidisc64c0292013-05-07 19:54:28 +0000892 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
893 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
894 DiagnoseUseOfDecl(Type, NameLoc);
895 QualType T = Context.getTypeDeclType(Type);
896 if (SS.isNotEmpty())
897 return buildNestedType(*this, SS, T, NameLoc);
898 return ParsedType::make(T);
Kaelyn Uhrain71792052012-05-02 00:11:40 +0000899 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000900
Richard Smith4f605af2012-08-18 00:55:03 +0000901 if (FirstDecl->isCXXClassMember())
Craig Topperc3ec1492014-05-26 06:22:03 +0000902 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
903 nullptr);
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000904
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000905 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
906 return BuildDeclarationNameExpr(SS, Result, ADL);
907}
908
John McCall5ed6e8f2009-08-18 00:00:49 +0000909// Determines the context to return to after temporarily entering a
910// context. This depends in an unnecessarily complicated way on the
911// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000912DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000913
John McCall5ed6e8f2009-08-18 00:00:49 +0000914 // Functions defined inline within classes aren't parsed until we've
915 // finished parsing the top-level class, so the top-level class is
916 // the context we'll need to return to.
Faisal Valibb9071e2013-12-04 22:43:08 +0000917 // A Lambda call operator whose parent is a class must not be treated
918 // as an inline member function. A Lambda can be used legally
919 // either as an in-class member initializer or a default argument. These
920 // are parsed once the class has been marked complete and so the containing
921 // context would be the nested class (when the lambda is defined in one);
922 // If the class is not complete, then the lambda is being used in an
923 // ill-formed fashion (such as to specify the width of a bit-field, or
924 // in an array-bound) - in which case we still want to return the
925 // lexically containing DC (which could be a nested class).
926 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
John McCall5ed6e8f2009-08-18 00:00:49 +0000927 DC = DC->getLexicalParent();
928
929 // A function not defined within a class will always return to its
930 // lexical context.
931 if (!isa<CXXRecordDecl>(DC))
932 return DC;
933
934 // A C++ inline method/friend is parsed *after* the topmost class
935 // it was declared in is fully parsed ("complete"); the topmost
936 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000937 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000938 DC = RD;
939
940 // Return the declaration context of the topmost class the inline method is
941 // declared in.
942 return DC;
943 }
944
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000945 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946}
947
Douglas Gregor91f84212008-12-11 16:49:14 +0000948void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000949 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000950 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000951 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000952 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000953}
954
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000955void Sema::PopDeclContext() {
956 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000957
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000958 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000959 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000960}
961
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000962/// EnterDeclaratorContext - Used when we must lookup names in the context
963/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000964///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000965void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000966 // C++0x [basic.lookup.unqual]p13:
967 // A name used in the definition of a static data member of class
968 // X (after the qualified-id of the static member) is looked up as
969 // if the name was used in a member function of X.
970 // C++0x [basic.lookup.unqual]p14:
971 // If a variable member of a namespace is defined outside of the
972 // scope of its namespace then any name used in the definition of
973 // the variable member (after the declarator-id) is looked up as
974 // if the definition of the variable member occurred in its
975 // namespace.
976 // Both of these imply that we should push a scope whose context
977 // is the semantic context of the declaration. We can't use
978 // PushDeclContext here because that context is not necessarily
979 // lexically contained in the current context. Fortunately,
980 // the containing scope should have the appropriate information.
981
982 assert(!S->getEntity() && "scope already has entity");
983
984#ifndef NDEBUG
985 Scope *Ancestor = S->getParent();
986 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
987 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
988#endif
989
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000990 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000991 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000992}
993
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000994void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000995 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000996
John McCall6df5fef2009-12-19 10:49:29 +0000997 // Switch back to the lexical context. The safety of this is
998 // enforced by an assert in EnterDeclaratorContext.
999 Scope *Ancestor = S->getParent();
1000 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
Ted Kremenekc37877d2013-10-08 17:08:03 +00001001 CurContext = Ancestor->getEntity();
John McCall6df5fef2009-12-19 10:49:29 +00001002
1003 // We don't need to do anything with the scope, which is going to
1004 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00001005}
1006
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001007
1008void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
Alp Tokera2794f92014-01-22 07:29:52 +00001009 // We assume that the caller has already called
1010 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1011 FunctionDecl *FD = D->getAsFunction();
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001012 if (!FD)
1013 return;
1014
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001015 // Same implementation as PushDeclContext, but enters the context
1016 // from the lexical parent, rather than the top-level class.
1017 assert(CurContext == FD->getLexicalParent() &&
1018 "The next DeclContext should be lexically contained in the current one.");
1019 CurContext = FD;
1020 S->setEntity(CurContext);
1021
Caitlin Sadowski990d5712011-09-08 17:42:31 +00001022 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1023 ParmVarDecl *Param = FD->getParamDecl(P);
1024 // If the parameter has an identifier, then add it to the scope
1025 if (Param->getIdentifier()) {
1026 S->AddDecl(Param);
1027 IdResolver.AddDecl(Param);
1028 }
1029 }
1030}
1031
1032
DeLesley Hutchins6f860042012-04-06 15:10:17 +00001033void Sema::ActOnExitFunctionContext() {
1034 // Same implementation as PopDeclContext, but returns to the lexical parent,
1035 // rather than the top-level class.
1036 assert(CurContext && "DeclContext imbalance!");
1037 CurContext = CurContext->getLexicalParent();
1038 assert(CurContext && "Popped translation unit!");
1039}
1040
1041
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001042/// \brief Determine whether we allow overloading of the function
1043/// PrevDecl with another declaration.
1044///
1045/// This routine determines whether overloading is possible, not
1046/// whether some new function is actually an overload. It will return
1047/// true in C++ (where we can always provide overloads) or, as an
1048/// extension, in C when the previous function is already an
1049/// overloaded function declaration or has the "overloadable"
1050/// attribute.
John McCall1f82f242009-11-18 22:49:29 +00001051static bool AllowOverloadingOfFunction(LookupResult &Previous,
1052 ASTContext &Context) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001053 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 return true;
1055
John McCall1f82f242009-11-18 22:49:29 +00001056 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001057 return true;
1058
John McCall1f82f242009-11-18 22:49:29 +00001059 return (Previous.getResultKind() == LookupResult::Found
1060 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001061}
1062
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001063/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +00001064void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +00001065 // Move up the scope chain until we find the nearest enclosing
1066 // non-transparent context. The declaration will be introduced into this
1067 // scope.
Ted Kremenekc37877d2013-10-08 17:08:03 +00001068 while (S->getEntity() && S->getEntity()->isTransparentContext())
Douglas Gregor07665a62009-01-05 19:45:36 +00001069 S = S->getParent();
1070
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001071 // Add scoped declarations into their context, so that they can be
1072 // found later. Declarations without a context won't be inserted
1073 // into any context.
John McCall759e32b2009-08-31 22:39:49 +00001074 if (AddToContext)
1075 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001076
Richard Smith541b38b2013-09-20 01:15:31 +00001077 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1078 // are function-local declarations.
1079 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
Douglas Gregorf7b98952011-10-09 22:57:49 +00001080 !D->getDeclContext()->getRedeclContext()->Equals(
Richard Smith541b38b2013-09-20 01:15:31 +00001081 D->getLexicalDeclContext()->getRedeclContext()) &&
1082 !D->getLexicalDeclContext()->isFunctionOrMethod())
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001083 return;
1084
1085 // Template instantiations should also not be pushed into scope.
1086 if (isa<FunctionDecl>(D) &&
1087 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +00001088 return;
1089
John McCall9f3059a2009-10-09 21:13:30 +00001090 // If this replaces anything in the current scope,
1091 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1092 IEnd = IdResolver.end();
1093 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +00001094 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1095 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +00001096 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001097
John McCall9f3059a2009-10-09 21:13:30 +00001098 // Should only need to replace one decl.
1099 break;
Douglas Gregor38feed82009-04-24 02:57:34 +00001100 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001101 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102
John McCall48871652010-08-21 09:40:31 +00001103 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001104
1105 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1106 // Implicitly-generated labels may end up getting generated in an order that
1107 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1108 // the label at the appropriate place in the identifier chain.
1109 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +00001110 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +00001111 if (IDC == CurContext) {
1112 if (!S->isDeclScope(*I))
1113 continue;
1114 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +00001115 break;
1116 }
1117
Douglas Gregor46c04e72011-03-16 16:39:03 +00001118 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +00001119 } else {
1120 IdResolver.AddDecl(D);
1121 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001122}
1123
Douglas Gregor935bc7a22011-10-27 09:33:13 +00001124void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1125 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1126 TUScope->AddDecl(D);
1127}
1128
Richard Smith1c34fb72013-08-13 18:18:50 +00001129bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
Richard Smith72bcaec2013-12-05 04:30:04 +00001130 bool AllowInlineNamespace) {
1131 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
Douglas Gregor505ad492009-09-28 00:47:05 +00001132}
1133
John McCallcc14d1f2010-08-24 08:50:51 +00001134Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1135 DeclContext *TargetDC = DC->getPrimaryContext();
1136 do {
Ted Kremenekc37877d2013-10-08 17:08:03 +00001137 if (DeclContext *ScopeDC = S->getEntity())
John McCallcc14d1f2010-08-24 08:50:51 +00001138 if (ScopeDC->getPrimaryContext() == TargetDC)
1139 return S;
1140 } while ((S = S->getParent()));
1141
Craig Topperc3ec1492014-05-26 06:22:03 +00001142 return nullptr;
John McCallcc14d1f2010-08-24 08:50:51 +00001143}
1144
John McCall1f82f242009-11-18 22:49:29 +00001145static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1146 DeclContext*,
1147 ASTContext&);
1148
1149/// Filters out lookup results that don't fall within the given scope
1150/// as determined by isDeclInScope.
Richard Smith72bcaec2013-12-05 04:30:04 +00001151void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
Richard Smith3f1b5d02011-05-05 21:57:07 +00001152 bool ConsiderLinkage,
Richard Smith72bcaec2013-12-05 04:30:04 +00001153 bool AllowInlineNamespace) {
John McCall1f82f242009-11-18 22:49:29 +00001154 LookupResult::Filter F = R.makeFilter();
1155 while (F.hasNext()) {
1156 NamedDecl *D = F.next();
1157
Richard Smith72bcaec2013-12-05 04:30:04 +00001158 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
John McCall1f82f242009-11-18 22:49:29 +00001159 continue;
1160
Richard Smith72bcaec2013-12-05 04:30:04 +00001161 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +00001162 continue;
Richard Smith72bcaec2013-12-05 04:30:04 +00001163
John McCall1f82f242009-11-18 22:49:29 +00001164 F.erase();
1165 }
1166
1167 F.done();
1168}
1169
1170static bool isUsingDecl(NamedDecl *D) {
1171 return isa<UsingShadowDecl>(D) ||
1172 isa<UnresolvedUsingTypenameDecl>(D) ||
1173 isa<UnresolvedUsingValueDecl>(D);
1174}
1175
1176/// Removes using shadow declarations from the lookup results.
1177static void RemoveUsingDecls(LookupResult &R) {
1178 LookupResult::Filter F = R.makeFilter();
1179 while (F.hasNext())
1180 if (isUsingDecl(F.next()))
1181 F.erase();
1182
1183 F.done();
1184}
1185
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001186/// \brief Check for this common pattern:
1187/// @code
1188/// class S {
1189/// S(const S&); // DO NOT IMPLEMENT
1190/// void operator=(const S&); // DO NOT IMPLEMENT
1191/// };
1192/// @endcode
1193static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1194 // FIXME: Should check for private access too but access is set after we get
1195 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001196 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001197 return false;
1198
1199 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1200 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001201 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1202 return Method->isCopyAssignmentOperator();
1203 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001204}
1205
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001206// We need this to handle
1207//
1208// typedef struct {
1209// void *foo() { return 0; }
1210// } A;
1211//
1212// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1213// for example. If 'A', foo will have external linkage. If we have '*A',
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001214// foo will have no linkage. Since we can't know until we get to the end
Alp Tokerd4733632013-12-05 04:47:09 +00001215// of the typedef, this function finds out if D might have non-external linkage.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001216// Callers should verify at the end of the TU if it D has external linkage or
1217// not.
1218bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1219 const DeclContext *DC = D->getDeclContext();
1220 while (!DC->isTranslationUnit()) {
1221 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1222 if (!RD->hasNameForLinkage())
1223 return true;
1224 }
1225 DC = DC->getParent();
1226 }
1227
Rafael Espindola3ae00052013-05-13 00:12:11 +00001228 return !D->isExternallyVisible();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001229}
1230
Eli Friedman5ef21752013-09-10 03:05:56 +00001231// FIXME: This needs to be refactored; some other isInMainFile users want
1232// these semantics.
1233static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1234 if (S.TUKind != TU_Complete)
1235 return false;
1236 return S.SourceMgr.isInMainFile(Loc);
1237}
1238
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001239bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1240 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +00001241
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001242 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1243 return false;
1244
Richard Smithc3926172014-04-02 18:28:36 +00001245 // Ignore all entities declared within templates, and out-of-line definitions
1246 // of members of class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +00001247 if (D->getDeclContext()->isDependentContext() ||
1248 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001249 return false;
1250
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001252 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1253 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001254
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1256 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1257 return false;
1258 } else {
Eli Friedman5ef21752013-09-10 03:05:56 +00001259 // 'static inline' functions are defined in headers; don't warn.
Richard Smitha90ee352014-05-11 21:25:24 +00001260 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +00001261 return false;
1262 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001263
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001264 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +00001265 Context.DeclMustBeEmitted(FD))
1266 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001267 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Eli Friedman5ef21752013-09-10 03:05:56 +00001268 // Constants and utility variables are defined in headers with internal
1269 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1270 // like "inline".)
1271 if (!isMainFileLoc(*this, VD->getLocation()))
1272 return false;
1273
Eli Friedman5ef21752013-09-10 03:05:56 +00001274 if (Context.DeclMustBeEmitted(VD))
John McCalld37d35b2010-10-27 01:41:35 +00001275 return false;
1276
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001277 if (VD->isStaticDataMember() &&
1278 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1279 return false;
John McCalld37d35b2010-10-27 01:41:35 +00001280 } else {
1281 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001282 }
1283
John McCalld37d35b2010-10-27 01:41:35 +00001284 // Only warn for unused decls internal to the translation unit.
Richard Smitha90ee352014-05-11 21:25:24 +00001285 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1286 // for inline functions defined in the main source file, for instance.
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001287 return mightHaveNonExternalLinkage(D);
John McCalld37d35b2010-10-27 01:41:35 +00001288}
1289
1290void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001291 if (!D)
1292 return;
1293
1294 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001295 const FunctionDecl *First = FD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001296 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1297 return; // First should already be in the vector.
1298 }
1299
1300 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001301 const VarDecl *First = VD->getFirstDecl();
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001302 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1303 return; // First should already be in the vector.
1304 }
1305
David Blaikie3d8edc22012-05-26 05:35:39 +00001306 if (ShouldWarnIfUnusedFileScopedDecl(D))
1307 UnusedFileScopedDecls.push_back(D);
1308}
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001309
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001310static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001311 if (D->isInvalidDecl())
1312 return false;
1313
Ted Kremenekce0e3f82014-01-09 20:19:45 +00001314 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1315 D->hasAttr<ObjCPreciseLifetimeAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001316 return false;
John McCall67da35c2010-02-04 22:26:26 +00001317
Chris Lattnercab02a62011-02-17 20:34:02 +00001318 if (isa<LabelDecl>(D))
1319 return true;
1320
John McCall67da35c2010-02-04 22:26:26 +00001321 // White-list anything that isn't a local variable.
1322 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1323 !D->getDeclContext()->isFunctionOrMethod())
1324 return false;
1325
1326 // Types of valid local variables should be complete, so this should succeed.
Rafael Espindola7c23b082012-01-06 04:54:01 +00001327 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001328
1329 // White-list anything with an __attribute__((unused)) type.
1330 QualType Ty = VD->getType();
1331
1332 // Only look at the outermost level of typedef.
Douglas Gregor5c65f622012-09-14 05:10:40 +00001333 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
John McCallcef15822010-03-31 02:47:45 +00001334 if (TT->getDecl()->hasAttr<UnusedAttr>())
1335 return false;
1336 }
1337
Douglas Gregor14f232e2010-05-08 23:05:03 +00001338 // If we failed to complete the type for some reason, or if the type is
1339 // dependent, don't diagnose the variable.
1340 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001341 return false;
1342
John McCallcef15822010-03-31 02:47:45 +00001343 if (const TagType *TT = Ty->getAs<TagType>()) {
1344 const TagDecl *Tag = TT->getDecl();
1345 if (Tag->hasAttr<UnusedAttr>())
1346 return false;
1347
1348 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Lubos Lunakedc13882013-07-20 15:05:36 +00001349 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001350 return false;
Rafael Espindola7c23b082012-01-06 04:54:01 +00001351
1352 if (const Expr *Init = VD->getInit()) {
Nico Weberdfc59202014-05-03 22:07:35 +00001353 if (const ExprWithCleanups *Cleanups =
1354 dyn_cast<ExprWithCleanups>(Init))
David Blaikiea9d4a932012-10-24 21:29:06 +00001355 Init = Cleanups->getSubExpr();
Rafael Espindola7c23b082012-01-06 04:54:01 +00001356 const CXXConstructExpr *Construct =
1357 dyn_cast<CXXConstructExpr>(Init);
1358 if (Construct && !Construct->isElidable()) {
1359 CXXConstructorDecl *CD = Construct->getConstructor();
Lubos Lunakedc13882013-07-20 15:05:36 +00001360 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
Rafael Espindola7c23b082012-01-06 04:54:01 +00001361 return false;
1362 }
1363 }
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001364 }
1365 }
John McCallcef15822010-03-31 02:47:45 +00001366
1367 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001368 }
1369
John McCall67da35c2010-02-04 22:26:26 +00001370 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001371}
1372
Anna Zaks964f4c62011-07-28 20:52:06 +00001373static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1374 FixItHint &Hint) {
1375 if (isa<LabelDecl>(D)) {
1376 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001377 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
Anna Zaks964f4c62011-07-28 20:52:06 +00001378 if (AfterColon.isInvalid())
1379 return;
1380 Hint = FixItHint::CreateRemoval(CharSourceRange::
1381 getCharRange(D->getLocStart(), AfterColon));
1382 }
1383 return;
1384}
1385
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001386/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1387/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001388void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1389 if (!ShouldDiagnoseUnusedDecl(D))
1390 return;
1391
Nico Weberdfc59202014-05-03 22:07:35 +00001392 FixItHint Hint;
Anna Zaks964f4c62011-07-28 20:52:06 +00001393 GenerateFixForUnusedDecl(D, Context, Hint);
1394
Chris Lattnercab02a62011-02-17 20:34:02 +00001395 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001396 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001397 DiagID = diag::warn_unused_exception_param;
1398 else if (isa<LabelDecl>(D))
1399 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001400 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001401 DiagID = diag::warn_unused_variable;
1402
Anna Zaks964f4c62011-07-28 20:52:06 +00001403 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001404}
1405
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001406static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1407 // Verify that we have no forward references left. If so, there was a goto
1408 // or address of a label taken, but no definition of it. Label fwd
1409 // definitions are indicated with a null substmt.
Craig Topperc3ec1492014-05-26 06:22:03 +00001410 if (L->getStmt() == nullptr)
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001411 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1412}
1413
Steve Naroffc62adb62007-10-09 22:01:59 +00001414void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00001415 S->mergeNRVOIntoParent();
1416
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001417 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001418 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001419 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001420
Aaron Ballman35c54952014-03-17 16:55:25 +00001421 for (auto *TmpD : S->decls()) {
Steve Naroff9324db12007-09-13 18:10:37 +00001422 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001423
Douglas Gregor91f84212008-12-11 16:49:14 +00001424 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1425 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001426
Douglas Gregor91f84212008-12-11 16:49:14 +00001427 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001428
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001429 // Diagnose unused variables in this scope.
Matt Beaumont-Gay8f511212013-03-28 21:46:45 +00001430 if (!S->hasUnrecoverableErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001431 DiagnoseUnusedDecl(D);
1432
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001433 // If this was a forward reference to a label, verify it was defined.
1434 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1435 CheckPoppedLabel(LD, *this);
1436
Douglas Gregor91f84212008-12-11 16:49:14 +00001437 // Remove this name from our lexical scope.
1438 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001439 }
1440}
1441
Douglas Gregor1c283312010-08-11 12:19:30 +00001442/// \brief Look for an Objective-C class in the translation unit.
1443///
1444/// \param Id The name of the Objective-C class we're looking for. If
1445/// typo-correction fixes this name, the Id will be updated
1446/// to the fixed name.
1447///
1448/// \param IdLoc The location of the name in the translation unit.
1449///
James Dennett41725122012-06-22 10:16:05 +00001450/// \param DoTypoCorrection If true, this routine will attempt typo correction
Douglas Gregor1c283312010-08-11 12:19:30 +00001451/// if there is no class with the given name.
1452///
1453/// \returns The declaration of the named Objective-C class, or NULL if the
1454/// class could not be found.
1455ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1456 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001457 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001458 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1459 // creation from this context.
1460 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1461
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001462 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001463 // Perform typo correction at the given location, but only if we
1464 // find an Objective-C class name.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001465 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1466 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
Craig Topperc3ec1492014-05-26 06:22:03 +00001467 LookupOrdinaryName, TUScope, nullptr,
John Thompson2255f2c2014-04-23 12:57:01 +00001468 Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001469 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00001470 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor1c283312010-08-11 12:19:30 +00001471 Id = IDecl->getIdentifier();
1472 }
1473 }
Fariborz Jahanian4f8cb1e2012-01-12 00:18:35 +00001474 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1475 // This routine must always return a class definition, if any.
1476 if (Def && Def->getDefinition())
1477 Def = Def->getDefinition();
1478 return Def;
Douglas Gregor1c283312010-08-11 12:19:30 +00001479}
1480
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001481/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1482/// from S, where a non-field would be declared. This routine copes
1483/// with the difference between C and C++ scoping rules in structs and
1484/// unions. For example, the following code is well-formed in C but
1485/// ill-formed in C++:
1486/// @code
1487/// struct S6 {
1488/// enum { BAR } e;
1489/// };
Mike Stump11289f42009-09-09 15:08:12 +00001490///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001491/// void test_S6() {
1492/// struct S6 a;
1493/// a.e = BAR;
1494/// }
1495/// @endcode
1496/// For the declaration of BAR, this routine will return a different
1497/// scope. The scope S will be the scope of the unnamed enumeration
1498/// within S6. In C++, this routine will return the scope associated
1499/// with S6, because the enumeration's scope is a transparent
1500/// context but structures can contain non-field names. In C, this
1501/// routine will return the translation unit scope, since the
1502/// enumeration's scope is a transparent context and structures cannot
1503/// contain non-field names.
1504Scope *Sema::getNonFieldDeclScope(Scope *S) {
1505 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +00001506 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001507 (S->isClassScope() && !getLangOpts().CPlusPlus))
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001508 S = S->getParent();
1509 return S;
1510}
1511
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001512/// \brief Looks up the declaration of "struct objc_super" and
1513/// saves it for later use in building builtin declaration of
1514/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1515/// pre-existing declaration exists no action takes place.
1516static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1517 IdentifierInfo *II) {
1518 if (!II->isStr("objc_msgSendSuper"))
1519 return;
1520 ASTContext &Context = ThisSema.Context;
1521
1522 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1523 SourceLocation(), Sema::LookupTagName);
1524 ThisSema.LookupName(Result, S);
1525 if (Result.getResultKind() == LookupResult::Found)
1526 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1527 Context.setObjCSuperType(Context.getTagDeclType(TD));
1528}
1529
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001530/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1531/// file scope. lazily create a decl for it. ForRedeclaration is true
1532/// if we're creating this built-in in anticipation of redeclaring the
1533/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001534NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001535 Scope *S, bool ForRedeclaration,
1536 SourceLocation Loc) {
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001537 LookupPredefedObjCSuperType(*this, S, II);
1538
Chris Lattner9561a0b2007-01-28 08:20:04 +00001539 Builtin::ID BID = (Builtin::ID)bid;
1540
Chris Lattnerecd79c62009-06-14 00:45:47 +00001541 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001542 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001543 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001544 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001545 // Okay
1546 break;
1547
Mike Stump93246cc2009-07-28 23:57:15 +00001548 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001549 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001550 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001551 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001552 return nullptr;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001553
Mike Stump93246cc2009-07-28 23:57:15 +00001554 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001555 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001556 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001557 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001558 return nullptr;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00001559
1560 case ASTContext::GE_Missing_ucontext:
1561 if (ForRedeclaration)
1562 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1563 << Context.BuiltinInfo.GetName(BID);
Craig Topperc3ec1492014-05-26 06:22:03 +00001564 return nullptr;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001565 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001566
1567 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1568 Diag(Loc, diag::ext_implicit_lib_function_decl)
1569 << Context.BuiltinInfo.GetName(BID)
1570 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001571 if (Context.BuiltinInfo.getHeaderName(BID) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001572 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001573 Diag(Loc, diag::note_please_include_header)
1574 << Context.BuiltinInfo.getHeaderName(BID)
1575 << Context.BuiltinInfo.GetName(BID);
1576 }
1577
Warren Hunt445d83e2013-11-01 23:46:51 +00001578 DeclContext *Parent = Context.getTranslationUnitDecl();
1579 if (getLangOpts().CPlusPlus) {
1580 LinkageSpecDecl *CLinkageDecl =
1581 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1582 LinkageSpecDecl::lang_c, false);
Enea Zaffanellad8430922013-11-20 15:41:05 +00001583 CLinkageDecl->setImplicit();
Warren Hunt445d83e2013-11-01 23:46:51 +00001584 Parent->addDecl(CLinkageDecl);
1585 Parent = CLinkageDecl;
1586 }
1587
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001588 FunctionDecl *New = FunctionDecl::Create(Context,
Warren Hunt445d83e2013-11-01 23:46:51 +00001589 Parent,
Craig Topperc3ec1492014-05-26 06:22:03 +00001590 Loc, Loc, II, R, /*TInfo=*/nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001591 SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001592 false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001593 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001594 New->setImplicit();
1595
Chris Lattner4dd27102008-05-05 22:18:14 +00001596 // Create Decl objects for each parameter, adding them to the
1597 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001598 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001599 SmallVector<ParmVarDecl*, 16> Params;
Alp Toker9cacbab2014-01-20 20:26:09 +00001600 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001601 ParmVarDecl *parm =
Alp Toker9cacbab2014-01-20 20:26:09 +00001602 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001603 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1604 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00001605 parm->setScopeInfo(0, i);
1606 Params.push_back(parm);
1607 }
David Blaikie9c70e042011-09-21 18:16:56 +00001608 New->setParams(Params);
Chris Lattner4dd27102008-05-05 22:18:14 +00001609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
1611 AddKnownFunctionAttributes(New);
Warren Hunt445d83e2013-11-01 23:46:51 +00001612 RegisterLocallyScopedExternCDecl(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00001613
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001614 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001615 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1616 // relate Scopes to DeclContexts, and probably eliminate CurContext
1617 // entirely, but we're not there yet.
1618 DeclContext *SavedContext = CurContext;
Warren Hunt445d83e2013-11-01 23:46:51 +00001619 CurContext = Parent;
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001620 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001621 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001622 return New;
1623}
1624
Douglas Gregor3552dab2013-01-09 00:47:56 +00001625/// \brief Filter out any previous declarations that the given declaration
1626/// should not consider because they are not permitted to conflict, e.g.,
1627/// because they come from hidden sub-modules and do not refer to the same
1628/// entity.
1629static void filterNonConflictingPreviousDecls(ASTContext &context,
1630 NamedDecl *decl,
1631 LookupResult &previous){
1632 // This is only interesting when modules are enabled.
1633 if (!context.getLangOpts().Modules)
1634 return;
1635
1636 // Empty sets are uninteresting.
1637 if (previous.empty())
1638 return;
1639
Douglas Gregor3552dab2013-01-09 00:47:56 +00001640 LookupResult::Filter filter = previous.makeFilter();
1641 while (filter.hasNext()) {
1642 NamedDecl *old = filter.next();
1643
1644 // Non-hidden declarations are never ignored.
1645 if (!old->isHidden())
1646 continue;
1647
Rafael Espindola3ae00052013-05-13 00:12:11 +00001648 if (!old->isExternallyVisible())
Douglas Gregor3552dab2013-01-09 00:47:56 +00001649 filter.erase();
1650 }
1651
1652 filter.done();
1653}
1654
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001655bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1656 QualType OldType;
1657 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1658 OldType = OldTypedef->getUnderlyingType();
1659 else
1660 OldType = Context.getTypeDeclType(Old);
1661 QualType NewType = New->getUnderlyingType();
1662
Douglas Gregoraab36982012-01-11 22:33:48 +00001663 if (NewType->isVariablyModifiedType()) {
1664 // Must not redefine a typedef with a variably-modified type.
1665 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1666 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1667 << Kind << NewType;
1668 if (Old->getLocation().isValid())
1669 Diag(Old->getLocation(), diag::note_previous_definition);
1670 New->setInvalidDecl();
1671 return true;
1672 }
1673
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001674 if (OldType != NewType &&
1675 !OldType->isDependentType() &&
1676 !NewType->isDependentType() &&
Douglas Gregoraab36982012-01-11 22:33:48 +00001677 !Context.hasSameType(OldType, NewType)) {
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001678 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1679 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1680 << Kind << NewType << OldType;
1681 if (Old->getLocation().isValid())
1682 Diag(Old->getLocation(), diag::note_previous_definition);
1683 New->setInvalidDecl();
1684 return true;
1685 }
1686 return false;
1687}
1688
Richard Smithdda56e42011-04-15 14:24:37 +00001689/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001690/// same name and scope as a previous declaration 'Old'. Figure out
1691/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001692/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001693///
Richard Smithdda56e42011-04-15 14:24:37 +00001694void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001695 // If the new decl is known invalid already, don't bother doing any
1696 // merging checks.
1697 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001698
Steve Naroff44cfcb62008-09-09 14:32:20 +00001699 // Allow multiple definitions for ObjC built-in typedefs.
1700 // FIXME: Verify the underlying types are equivalent!
David Blaikiebbafb8a2012-03-11 07:00:24 +00001701 if (getLangOpts().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001702 const IdentifierInfo *TypeID = New->getIdentifier();
1703 switch (TypeID->getLength()) {
1704 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001705 case 2:
Fariborz Jahanian16d71bb2012-05-14 22:48:56 +00001706 {
1707 if (!TypeID->isStr("id"))
1708 break;
1709 QualType T = New->getUnderlyingType();
1710 if (!T->isPointerType())
1711 break;
1712 if (!T->isVoidPointerType()) {
1713 QualType PT = T->getAs<PointerType>()->getPointeeType();
1714 if (!PT->isStructureType())
1715 break;
1716 }
1717 Context.setObjCIdRedefinitionType(T);
1718 // Install the built-in type for 'id', ignoring the current definition.
1719 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1720 return;
1721 }
Chris Lattner66e32812008-11-20 05:41:43 +00001722 case 5:
1723 if (!TypeID->isStr("Class"))
1724 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001725 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
Steve Naroff7cae42b2009-07-10 23:34:53 +00001726 // Install the built-in type for 'Class', ignoring the current definition.
1727 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001728 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001729 case 3:
1730 if (!TypeID->isStr("SEL"))
1731 break;
Douglas Gregor97673472011-08-11 20:58:55 +00001732 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001733 // Install the built-in type for 'SEL', ignoring the current definition.
1734 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001735 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001736 }
1737 // Fall through - the typedef name was not a builtin type.
1738 }
John McCall1f82f242009-11-18 22:49:29 +00001739
Douglas Gregorfb034662009-01-28 17:15:10 +00001740 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001741 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1742 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001743 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001744 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001745
1746 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001747 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001748 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001749
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001750 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001751 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001752
John McCall1f82f242009-11-18 22:49:29 +00001753 // If the old declaration is invalid, just give up here.
1754 if (Old->isInvalidDecl())
1755 return New->setInvalidDecl();
1756
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001757 // If the typedef types are not identical, reject them in all languages and
1758 // with any extensions enabled.
Rafael Espindolacde2c8f2011-12-26 22:42:47 +00001759 if (isIncompatibleTypedef(Old, New))
1760 return;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001762 // The types match. Link up the redeclaration chain and merge attributes if
1763 // the old declaration was a typedef.
1764 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001765 New->setPreviousDecl(Typedef);
Justin Bogner84ff5ee2013-10-08 00:19:09 +00001766 mergeDeclAttributes(New, Old);
1767 }
Eli Friedmane7b8aa92013-07-16 02:07:49 +00001768
David Blaikiebbafb8a2012-03-11 07:00:24 +00001769 if (getLangOpts().MicrosoftExt)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001770 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001771
David Blaikiebbafb8a2012-03-11 07:00:24 +00001772 if (getLangOpts().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001773 // C++ [dcl.typedef]p2:
1774 // In a given non-class scope, a typedef specifier can be used to
1775 // redefine the name of any type declared in that scope to refer
1776 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001777 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001778 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001779
1780 // C++0x [dcl.typedef]p4:
1781 // In a given class scope, a typedef specifier can be used to redefine
1782 // any class-name declared in that scope that is not also a typedef-name
1783 // to refer to the type to which it already refers.
1784 //
1785 // This wording came in via DR424, which was a correction to the
1786 // wording in DR56, which accidentally banned code like:
1787 //
1788 // struct S {
1789 // typedef struct A { } A;
1790 // };
1791 //
1792 // in the C++03 standard. We implement the C++0x semantics, which
1793 // allow the above but disallow
1794 //
1795 // struct S {
1796 // typedef int I;
1797 // typedef int I;
1798 // };
1799 //
1800 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001801 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001802 return;
1803
Chris Lattner2581fc32009-04-17 22:04:20 +00001804 Diag(New->getLocation(), diag::err_redefinition)
1805 << New->getDeclName();
1806 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001807 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001808 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001809
Douglas Gregor7363fb02012-01-11 04:25:01 +00001810 // Modules always permit redefinition of typedefs, as does C11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001811 if (getLangOpts().Modules || getLangOpts().C11)
Douglas Gregordbd93bf2012-01-09 15:36:04 +00001812 return;
1813
Chris Lattner2581fc32009-04-17 22:04:20 +00001814 // If we have a redefinition of a typedef in C, emit a warning. This warning
1815 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001816 // -Wtypedef-redefinition. If either the original or the redefinition is
1817 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001818 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001819 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1820 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001821 return;
Mike Stump11289f42009-09-09 15:08:12 +00001822
Chris Lattner2581fc32009-04-17 22:04:20 +00001823 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1824 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001825 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001826 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001827}
1828
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001829/// DeclhasAttr - returns true if decl Declaration already has the target
1830/// attribute.
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00001831static bool DeclHasAttr(const Decl *D, const Attr *A) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001832 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001833 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001834 for (const auto *i : D->attrs())
1835 if (i->getKind() == A->getKind()) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001836 if (Ann) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001837 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001838 return true;
1839 continue;
1840 }
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001841 // FIXME: Don't hardcode this check
Aaron Ballmanb97112e2014-03-08 22:19:01 +00001842 if (OA && isa<OwnershipAttr>(i))
1843 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001844 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001845 }
Chris Lattner84966392008-03-03 03:28:21 +00001846
1847 return false;
1848}
1849
Richard Smithbc8caaf2013-02-22 04:55:39 +00001850static bool isAttributeTargetADefinition(Decl *D) {
1851 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1852 return VD->isThisDeclarationADefinition();
1853 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1854 return TD->isCompleteDefinition() || TD->isBeingDefined();
1855 return true;
1856}
1857
1858/// Merge alignment attributes from \p Old to \p New, taking into account the
1859/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1860///
1861/// \return \c true if any attributes were added to \p New.
1862static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1863 // Look for alignas attributes on Old, and pick out whichever attribute
1864 // specifies the strictest alignment requirement.
Craig Topperc3ec1492014-05-26 06:22:03 +00001865 AlignedAttr *OldAlignasAttr = nullptr;
1866 AlignedAttr *OldStrictestAlignAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001867 unsigned OldAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001868 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001869 // FIXME: We have no way of representing inherited dependent alignments
1870 // in a case like:
1871 // template<int A, int B> struct alignas(A) X;
1872 // template<int A, int B> struct alignas(B) X {};
1873 // For now, we just ignore any alignas attributes which are not on the
1874 // definition in such a case.
1875 if (I->isAlignmentDependent())
1876 return false;
1877
1878 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001879 OldAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001880
1881 unsigned Align = I->getAlignment(S.Context);
1882 if (Align > OldAlign) {
1883 OldAlign = Align;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001884 OldStrictestAlignAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001885 }
1886 }
1887
1888 // Look for alignas attributes on New.
Craig Topperc3ec1492014-05-26 06:22:03 +00001889 AlignedAttr *NewAlignasAttr = nullptr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001890 unsigned NewAlign = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001891 for (auto *I : New->specific_attrs<AlignedAttr>()) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00001892 if (I->isAlignmentDependent())
1893 return false;
1894
1895 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001896 NewAlignasAttr = I;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001897
1898 unsigned Align = I->getAlignment(S.Context);
1899 if (Align > NewAlign)
1900 NewAlign = Align;
1901 }
1902
1903 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1904 // Both declarations have 'alignas' attributes. We require them to match.
1905 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1906 // fall short. (If two declarations both have alignas, they must both match
1907 // every definition, and so must match each other if there is a definition.)
1908
1909 // If either declaration only contains 'alignas(0)' specifiers, then it
1910 // specifies the natural alignment for the type.
1911 if (OldAlign == 0 || NewAlign == 0) {
1912 QualType Ty;
1913 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1914 Ty = VD->getType();
1915 else
1916 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1917
1918 if (OldAlign == 0)
1919 OldAlign = S.Context.getTypeAlign(Ty);
1920 if (NewAlign == 0)
1921 NewAlign = S.Context.getTypeAlign(Ty);
1922 }
1923
1924 if (OldAlign != NewAlign) {
1925 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1926 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1927 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1928 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1929 }
1930 }
1931
1932 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1933 // C++11 [dcl.align]p6:
1934 // if any declaration of an entity has an alignment-specifier,
1935 // every defining declaration of that entity shall specify an
1936 // equivalent alignment.
1937 // C11 6.7.5/7:
1938 // If the definition of an object does not have an alignment
1939 // specifier, any other declaration of that object shall also
1940 // have no alignment specifier.
1941 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001942 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001943 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00001944 << OldAlignasAttr;
Richard Smithbc8caaf2013-02-22 04:55:39 +00001945 }
1946
1947 bool AnyAdded = false;
1948
1949 // Ensure we have an attribute representing the strictest alignment.
1950 if (OldAlign > NewAlign) {
1951 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1952 Clone->setInherited(true);
1953 New->addAttr(Clone);
1954 AnyAdded = true;
1955 }
1956
1957 // Ensure we have an alignas attribute if the old declaration had one.
1958 if (OldAlignasAttr && !NewAlignasAttr &&
1959 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1960 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1961 Clone->setInherited(true);
1962 New->addAttr(Clone);
1963 AnyAdded = true;
1964 }
1965
1966 return AnyAdded;
1967}
1968
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001969static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
1970 const InheritableAttr *Attr, bool Override) {
1971 InheritableAttr *NewAttr = nullptr;
Michael Han99315932013-01-24 16:46:58 +00001972 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001973 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001974 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1975 AA->getIntroduced(), AA->getDeprecated(),
1976 AA->getObsoleted(), AA->getUnavailable(),
1977 AA->getMessage(), Override,
John McCalld041a9b2013-02-20 01:54:26 +00001978 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001979 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001980 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1981 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001982 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001983 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1984 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001985 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001986 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1987 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001988 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001989 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1990 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001991 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001992 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1993 FA->getFormatIdx(), FA->getFirstArg(),
1994 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001995 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00001996 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1997 AttrSpellingListIndex);
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00001998 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
David Majnemer4bb09802014-02-10 19:50:15 +00001999 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2000 AttrSpellingListIndex,
David Majnemer2c4e00a2014-01-29 22:07:36 +00002001 IA->getSemanticSpelling());
Richard Smithbc8caaf2013-02-22 04:55:39 +00002002 else if (isa<AlignedAttr>(Attr))
2003 // AlignedAttrs are handled separately, because we need to handle all
2004 // such attributes on a declaration at the same time.
Aaron Ballman7a2fb5f2014-04-17 20:08:36 +00002005 NewAttr = nullptr;
Aaron Ballmanb9023ed2014-01-20 18:07:09 +00002006 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
Richard Smithbc8caaf2013-02-22 04:55:39 +00002007 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
Rafael Espindolac67f2232012-05-10 02:50:16 +00002008
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002009 if (NewAttr) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002010 NewAttr->setInherited(true);
2011 D->addAttr(NewAttr);
2012 return true;
2013 }
2014
2015 return false;
2016}
2017
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002018static const Decl *getDefinition(const Decl *D) {
2019 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
Rafael Espindola36191042012-05-18 01:47:00 +00002020 return TD->getDefinition();
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002021 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2022 const VarDecl *Def = VD->getDefinition();
2023 if (Def)
2024 return Def;
2025 return VD->getActingDefinition();
2026 }
Rafael Espindolaa5bba702012-07-15 01:05:36 +00002027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Rafael Espindola36191042012-05-18 01:47:00 +00002028 const FunctionDecl* Def;
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002029 if (FD->isDefined(Def))
Rafael Espindola36191042012-05-18 01:47:00 +00002030 return Def;
2031 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002032 return nullptr;
Rafael Espindola36191042012-05-18 01:47:00 +00002033}
2034
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002035static bool hasAttribute(const Decl *D, attr::Kind Kind) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00002036 for (const auto *Attribute : D->attrs())
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002037 if (Attribute->getKind() == Kind)
2038 return true;
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002039 return false;
2040}
2041
2042/// checkNewAttributesAfterDef - If we already have a definition, check that
2043/// there are no new attributes in this declaration.
2044static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2045 if (!New->hasAttrs())
2046 return;
2047
2048 const Decl *Def = getDefinition(Old);
2049 if (!Def || Def == New)
2050 return;
2051
2052 AttrVec &NewAttributes = New->getAttrs();
2053 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2054 const Attr *NewAttribute = NewAttributes[I];
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002055
2056 if (isa<AliasAttr>(NewAttribute)) {
2057 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2058 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2059 else {
2060 VarDecl *VD = cast<VarDecl>(New);
2061 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2062 VarDecl::TentativeDefinition
2063 ? diag::err_alias_after_tentative
2064 : diag::err_redefinition;
2065 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2066 S.Diag(Def->getLocation(), diag::note_previous_definition);
2067 VD->setInvalidDecl();
2068 }
2069 ++I;
2070 continue;
2071 }
2072
2073 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2074 // Tentative definitions are only interesting for the alias check above.
2075 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2076 ++I;
2077 continue;
2078 }
2079 }
2080
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002081 if (hasAttribute(Def, NewAttribute->getKind())) {
2082 ++I;
2083 continue; // regular attr merging will take care of validating this.
2084 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002085
Richard Smithdebc59d2013-01-30 05:45:05 +00002086 if (isa<C11NoReturnAttr>(NewAttribute)) {
Richard Smithbc8caaf2013-02-22 04:55:39 +00002087 // C's _Noreturn is allowed to be added to a function after it is defined.
Richard Smithdebc59d2013-01-30 05:45:05 +00002088 ++I;
2089 continue;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2091 if (AA->isAlignas()) {
2092 // C++11 [dcl.align]p6:
2093 // if any declaration of an entity has an alignment-specifier,
2094 // every defining declaration of that entity shall specify an
2095 // equivalent alignment.
2096 // C11 6.7.5/7:
2097 // If the definition of an object does not have an alignment
2098 // specifier, any other declaration of that object shall also
2099 // have no alignment specifier.
2100 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002101 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002102 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
Aaron Ballman3d216a52014-01-02 23:39:11 +00002103 << AA;
Richard Smithbc8caaf2013-02-22 04:55:39 +00002104 NewAttributes.erase(NewAttributes.begin() + I);
2105 --E;
2106 continue;
2107 }
Richard Smithdebc59d2013-01-30 05:45:05 +00002108 }
Richard Smithbc8caaf2013-02-22 04:55:39 +00002109
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002110 S.Diag(NewAttribute->getLocation(),
2111 diag::warn_attribute_precede_definition);
2112 S.Diag(Def->getLocation(), diag::note_previous_definition);
2113 NewAttributes.erase(NewAttributes.begin() + I);
2114 --E;
2115 }
2116}
2117
John McCallf79e87d2011-03-02 04:00:57 +00002118/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002119void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002120 AvailabilityMergeKind AMK) {
Rafael Espindolab0938852013-10-25 01:28:12 +00002121 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2122 UsedAttr *NewAttr = OldAttr->clone(Context);
2123 NewAttr->setInherited(true);
2124 New->addAttr(NewAttr);
2125 }
2126
Richard Smithe233fbf2013-01-28 22:42:45 +00002127 if (!Old->hasAttrs() && !New->hasAttrs())
2128 return;
2129
Rafael Espindola36191042012-05-18 01:47:00 +00002130 // attributes declared post-definition are currently ignored
Rafael Espindolafaf556b2012-07-15 01:33:40 +00002131 checkNewAttributesAfterDef(*this, New, Old);
Rafael Espindola36191042012-05-18 01:47:00 +00002132
Douglas Gregor32c17572012-01-01 20:30:41 +00002133 if (!Old->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002134 return;
John McCallf79e87d2011-03-02 04:00:57 +00002135
Douglas Gregor32c17572012-01-01 20:30:41 +00002136 bool foundAny = New->hasAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002137
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002138 // Ensure that any moving of objects within the allocated map is done before
2139 // we process them.
Douglas Gregor32c17572012-01-01 20:30:41 +00002140 if (!foundAny) New->setAttrs(AttrVec());
John McCallf79e87d2011-03-02 04:00:57 +00002141
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002142 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002143 bool Override = false;
Douglas Gregorb1fa1482011-09-23 20:23:42 +00002144 // Ignore deprecated/unavailable/availability attributes if requested.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002145 if (isa<DeprecatedAttr>(I) ||
2146 isa<UnavailableAttr>(I) ||
2147 isa<AvailabilityAttr>(I)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002148 switch (AMK) {
2149 case AMK_None:
2150 continue;
John McCalld2930c22011-07-22 02:45:48 +00002151
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002152 case AMK_Redeclaration:
2153 break;
2154
2155 case AMK_Override:
2156 Override = true;
2157 break;
2158 }
2159 }
2160
Rafael Espindolab0938852013-10-25 01:28:12 +00002161 // Already handled.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002162 if (isa<UsedAttr>(I))
Rafael Espindolab0938852013-10-25 01:28:12 +00002163 continue;
2164
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002165 if (mergeDeclAttribute(*this, New, I, Override))
John McCallf79e87d2011-03-02 04:00:57 +00002166 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00002167 }
John McCallf79e87d2011-03-02 04:00:57 +00002168
Richard Smithbc8caaf2013-02-22 04:55:39 +00002169 if (mergeAlignedAttrs(*this, New, Old))
2170 foundAny = true;
2171
Douglas Gregor32c17572012-01-01 20:30:41 +00002172 if (!foundAny) New->dropAttrs();
John McCallf79e87d2011-03-02 04:00:57 +00002173}
2174
2175/// mergeParamDeclAttributes - Copy attributes from the old parameter
2176/// to the new one.
2177static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2178 const ParmVarDecl *oldDecl,
Richard Smithe233fbf2013-01-28 22:42:45 +00002179 Sema &S) {
2180 // C++11 [dcl.attr.depend]p2:
2181 // The first declaration of a function shall specify the
2182 // carries_dependency attribute for its declarator-id if any declaration
2183 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002184 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2185 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2186 S.Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002187 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2188 // Find the first declaration of the parameter.
2189 // FIXME: Should we build redeclaration chains for function parameters?
2190 const FunctionDecl *FirstFD =
Rafael Espindola8db352d2013-10-17 15:37:26 +00002191 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
Richard Smithe233fbf2013-01-28 22:42:45 +00002192 const ParmVarDecl *FirstVD =
2193 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2194 S.Diag(FirstVD->getLocation(),
2195 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2196 }
2197
John McCallf79e87d2011-03-02 04:00:57 +00002198 if (!oldDecl->hasAttrs())
2199 return;
2200
2201 bool foundAny = newDecl->hasAttrs();
2202
2203 // Ensure that any moving of objects within the allocated map is
2204 // done before we process them.
2205 if (!foundAny) newDecl->setAttrs(AttrVec());
2206
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002207 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2208 if (!DeclHasAttr(newDecl, I)) {
Richard Smithe233fbf2013-01-28 22:42:45 +00002209 InheritableAttr *newAttr =
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002210 cast<InheritableParamAttr>(I->clone(S.Context));
John McCallf79e87d2011-03-02 04:00:57 +00002211 newAttr->setInherited(true);
2212 newDecl->addAttr(newAttr);
2213 foundAny = true;
2214 }
2215 }
2216
2217 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00002218}
2219
Dan Gohman28ade552010-07-26 21:25:24 +00002220namespace {
2221
Douglas Gregora74a2972009-03-06 22:43:54 +00002222/// Used in MergeFunctionDecl to keep track of function parameters in
2223/// C.
2224struct GNUCompatibleParamWarning {
2225 ParmVarDecl *OldParm;
2226 ParmVarDecl *NewParm;
2227 QualType PromotedType;
2228};
2229
Dan Gohman28ade552010-07-26 21:25:24 +00002230}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002231
2232/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00002233Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002234 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002235 if (Ctor->isDefaultConstructor())
2236 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00002237
2238 if (Ctor->isCopyConstructor())
2239 return Sema::CXXCopyConstructor;
2240
2241 if (Ctor->isMoveConstructor())
2242 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002243 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002244 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002245 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002246 return Sema::CXXCopyAssignment;
Sebastian Redle9c4e842011-09-04 18:14:28 +00002247 } else if (MD->isMoveAssignmentOperator()) {
2248 return Sema::CXXMoveAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00002249 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002250
Alexis Hunt80f00ff2011-05-10 19:08:14 +00002251 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002252}
2253
David Majnemer5b63fa02014-06-18 23:26:25 +00002254// Determine whether the previous declaration was a definition, implicit
2255// declaration, or a declaration.
2256template <typename T>
2257static std::pair<diag::kind, SourceLocation>
2258getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2259 diag::kind PrevDiag;
2260 SourceLocation OldLocation = Old->getLocation();
2261 if (Old->isThisDeclarationADefinition())
2262 PrevDiag = diag::note_previous_definition;
2263 else if (Old->isImplicit()) {
2264 PrevDiag = diag::note_previous_implicit_declaration;
2265 if (OldLocation.isInvalid())
2266 OldLocation = New->getLocation();
2267 } else
2268 PrevDiag = diag::note_previous_declaration;
2269 return std::make_pair(PrevDiag, OldLocation);
2270}
2271
Sebastian Redl243d9052010-06-09 21:17:41 +00002272/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00002273/// only extern inline functions can be redefined, and even then only in
2274/// GNU89 mode.
2275static bool canRedefineFunction(const FunctionDecl *FD,
2276 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00002277 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2278 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00002279 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00002280 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00002281}
2282
Reid Kleckner78af0702013-08-27 23:08:25 +00002283const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2284 const AttributedType *AT = T->getAs<AttributedType>();
2285 while (AT && !AT->isCallingConv())
2286 AT = AT->getModifiedType()->getAs<AttributedType>();
2287 return AT;
John McCalla5f46fb2012-08-25 02:00:03 +00002288}
2289
Benjamin Kramer3e350262013-02-15 12:30:38 +00002290template <typename T>
2291static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002292 const DeclContext *DC = Old->getDeclContext();
2293 if (DC->isRecord())
2294 return false;
2295
2296 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
Rafael Espindola593537a2013-05-05 20:15:21 +00002297 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002298 return true;
Rafael Espindola593537a2013-05-05 20:15:21 +00002299 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002300 return true;
2301 return false;
2302}
2303
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002304/// MergeFunctionDecl - We just parsed a function 'New' from
2305/// declarator D which has the same name and scope as a previous
2306/// declaration 'Old'. Figure out how to resolve this situation,
2307/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002308///
2309/// In C++, New and Old must be declarations that are not
2310/// overloaded. Use IsOverload to determine whether New and Old are
2311/// overloaded, and to select the Old declaration that New should be
2312/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002313///
2314/// Returns true if there was an error, false otherwise.
Richard Smith18819302014-02-06 01:31:33 +00002315bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2316 Scope *S, bool MergeTypeWithOld) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00002317 // Verify the old decl was also a function.
Alp Tokera2794f92014-01-22 07:29:52 +00002318 FunctionDecl *Old = OldD->getAsFunction();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002319 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00002320 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
John McCallc70fca62013-04-03 21:19:47 +00002321 if (New->getFriendObjectKind()) {
2322 Diag(New->getLocation(), diag::err_using_decl_friend);
2323 Diag(Shadow->getTargetDecl()->getLocation(),
2324 diag::note_using_decl_target);
2325 Diag(Shadow->getUsingDecl()->getLocation(),
2326 diag::note_using_decl) << 0;
2327 return true;
2328 }
2329
Richard Smith18819302014-02-06 01:31:33 +00002330 // C++11 [namespace.udecl]p14:
2331 // If a function declaration in namespace scope or block scope has the
2332 // same name and the same parameter-type-list as a function introduced
2333 // by a using-declaration, and the declarations do not declare the same
2334 // function, the program is ill-formed.
2335
2336 // Check whether the two declarations might declare the same function.
2337 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2338 if (Old &&
2339 !Old->getDeclContext()->getRedeclContext()->Equals(
2340 New->getDeclContext()->getRedeclContext()) &&
2341 !(Old->isExternC() && New->isExternC()))
Craig Topperc3ec1492014-05-26 06:22:03 +00002342 Old = nullptr;
Richard Smith18819302014-02-06 01:31:33 +00002343
2344 if (!Old) {
2345 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2346 Diag(Shadow->getTargetDecl()->getLocation(),
2347 diag::note_using_decl_target);
2348 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2349 return true;
2350 }
2351 OldD = Old;
2352 } else {
2353 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2354 << New->getDeclName();
2355 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCalle29c5cd2009-12-10 19:51:03 +00002356 return true;
2357 }
Chris Lattnerc511efb2007-01-27 19:32:14 +00002358 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002359
David Majnemerea5092a2013-07-07 23:49:50 +00002360 // If the old declaration is invalid, just give up here.
2361 if (Old->isInvalidDecl())
2362 return true;
2363
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002364 diag::kind PrevDiag;
David Majnemer5b63fa02014-06-18 23:26:25 +00002365 SourceLocation OldLocation;
2366 std::tie(PrevDiag, OldLocation) =
2367 getNoteDiagForInvalidRedeclaration(Old, New);
Mike Stump11289f42009-09-09 15:08:12 +00002368
Charles Davisfea48452010-02-18 02:00:42 +00002369 // Don't complain about this if we're in GNU89 mode and the old function
2370 // is an extern inline function.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002371 // Don't complain about specializations. They are not supposed to have
2372 // storage classes.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002373 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00002374 New->getStorageClass() == SC_Static &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00002375 Old->hasExternalFormalLinkage() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002376 !New->getTemplateSpecializationInfo() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002377 !canRedefineFunction(Old, getLangOpts())) {
2378 if (getLangOpts().MicrosoftExt) {
David Majnemer5b63fa02014-06-18 23:26:25 +00002379 Diag(New->getLocation(), diag::ext_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002380 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002381 } else {
2382 Diag(New->getLocation(), diag::err_static_non_static) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002383 Diag(OldLocation, PrevDiag);
Francois Pichet6841a122011-04-22 19:50:06 +00002384 return true;
2385 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00002386 }
2387
Reid Kleckner78af0702013-08-27 23:08:25 +00002388
2389 // If a function is first declared with a calling convention, but is later
2390 // declared or defined without one, all following decls assume the calling
2391 // convention of the first.
John McCallcddbad02010-02-04 05:44:44 +00002392 //
John McCalla5f46fb2012-08-25 02:00:03 +00002393 // It's OK if a function is first declared without a calling convention,
2394 // but is later declared or defined with the default calling convention.
2395 //
Reid Kleckner78af0702013-08-27 23:08:25 +00002396 // To test if either decl has an explicit calling convention, we look for
2397 // AttributedType sugar nodes on the type as written. If they are missing or
2398 // were canonicalized away, we assume the calling convention was implicit.
John McCallcddbad02010-02-04 05:44:44 +00002399 //
2400 // Note also that we DO NOT return at this point, because we still have
2401 // other tests to run.
Reid Kleckner78af0702013-08-27 23:08:25 +00002402 QualType OldQType = Context.getCanonicalType(Old->getType());
2403 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall4f5019e2010-12-19 02:44:49 +00002404 const FunctionType *OldType = cast<FunctionType>(OldQType);
Reid Kleckner78af0702013-08-27 23:08:25 +00002405 const FunctionType *NewType = cast<FunctionType>(NewQType);
John McCall4f5019e2010-12-19 02:44:49 +00002406 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2407 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2408 bool RequiresAdjustment = false;
John McCalla5f46fb2012-08-25 02:00:03 +00002409
Reid Kleckner78af0702013-08-27 23:08:25 +00002410 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002411 FunctionDecl *First = Old->getFirstDecl();
Reid Kleckner78af0702013-08-27 23:08:25 +00002412 const FunctionType *FT =
2413 First->getType().getCanonicalType()->castAs<FunctionType>();
2414 FunctionType::ExtInfo FI = FT->getExtInfo();
2415 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2416 if (!NewCCExplicit) {
2417 // Inherit the CC from the previous declaration if it was specified
2418 // there but not here.
2419 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2420 RequiresAdjustment = true;
2421 } else {
2422 // Calling conventions aren't compatible, so complain.
2423 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2424 Diag(New->getLocation(), diag::err_cconv_change)
2425 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2426 << !FirstCCExplicit
2427 << (!FirstCCExplicit ? "" :
2428 FunctionType::getNameForCallConv(FI.getCC()));
John McCalla5f46fb2012-08-25 02:00:03 +00002429
Reid Kleckner78af0702013-08-27 23:08:25 +00002430 // Put the note on the first decl, since it is the one that matters.
2431 Diag(First->getLocation(), diag::note_previous_declaration);
2432 return true;
2433 }
John McCallcddbad02010-02-04 05:44:44 +00002434 }
2435
John McCallab26cfa2010-02-05 21:31:56 +00002436 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00002437 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2438 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2439 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00002440 }
2441
Douglas Gregor77e274f2010-06-18 21:30:25 +00002442 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00002443 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2444 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2445 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00002446 Diag(New->getLocation(), diag::err_regparm_mismatch)
2447 << NewType->getRegParmType()
2448 << OldType->getRegParmType();
Richard Smithbdd14642014-02-04 01:14:30 +00002449 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002450 return true;
2451 }
John McCall4f5019e2010-12-19 02:44:49 +00002452
2453 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2454 RequiresAdjustment = true;
2455 }
2456
Douglas Gregorf1404d72011-10-14 15:55:40 +00002457 // Merge ns_returns_retained attribute.
2458 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2459 if (NewTypeInfo.getProducesResult()) {
2460 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
Richard Smithbdd14642014-02-04 01:14:30 +00002461 Diag(OldLocation, diag::note_previous_declaration);
Douglas Gregorf1404d72011-10-14 15:55:40 +00002462 return true;
2463 }
2464
2465 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2466 RequiresAdjustment = true;
2467 }
2468
John McCall4f5019e2010-12-19 02:44:49 +00002469 if (RequiresAdjustment) {
Eli Friedmane934af82013-09-06 21:09:09 +00002470 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2471 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2472 New->setType(QualType(AdjustedType, 0));
John McCall4f5019e2010-12-19 02:44:49 +00002473 NewQType = Context.getCanonicalType(New->getType());
Eli Friedmane934af82013-09-06 21:09:09 +00002474 NewType = cast<FunctionType>(NewQType);
Douglas Gregor77e274f2010-06-18 21:30:25 +00002475 }
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002476
2477 // If this redeclaration makes the function inline, we may need to add it to
2478 // UndefinedButUsed.
2479 if (!Old->isInlined() && New->isInlined() &&
2480 !New->hasAttr<GNUInlineAttr>() &&
2481 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2482 Old->isUsed(false) &&
2483 !Old->isDefined() && !New->isThisDeclarationADefinition())
2484 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2485 SourceLocation()));
2486
2487 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2488 // about it.
2489 if (New->hasAttr<GNUInlineAttr>() &&
2490 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2491 UndefinedButUsed.erase(Old->getCanonicalDecl());
2492 }
Douglas Gregor77e274f2010-06-18 21:30:25 +00002493
David Blaikiebbafb8a2012-03-11 07:00:24 +00002494 if (getLangOpts().CPlusPlus) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002495 // (C++98 13.1p2):
2496 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00002497 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002498 // cannot be overloaded.
Richard Smith2a7d4812013-05-04 07:00:32 +00002499
2500 // Go back to the type source info to compare the declared return types,
Richard Smithc58f38f2013-08-14 20:16:31 +00002501 // per C++1y [dcl.type.auto]p13:
Richard Smith2a7d4812013-05-04 07:00:32 +00002502 // Redeclarations or specializations of a function or function template
2503 // with a declared return type that uses a placeholder type shall also
2504 // use that placeholder, not a deduced type.
Alp Toker314cc812014-01-25 16:55:45 +00002505 QualType OldDeclaredReturnType =
2506 (Old->getTypeSourceInfo()
2507 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2508 : OldType)->getReturnType();
2509 QualType NewDeclaredReturnType =
2510 (New->getTypeSourceInfo()
2511 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2512 : NewType)->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002513 QualType ResQT;
Richard Smith541b38b2013-09-20 01:15:31 +00002514 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2515 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2516 New->isLocalExternDecl())) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002517 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2518 OldDeclaredReturnType->isObjCObjectPointerType())
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002519 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2520 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002521 if (New->isCXXClassMember() && New->isOutOfLine())
Alp Tokerd0787eb2014-07-02 01:47:15 +00002522 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2523 << New << New->getReturnTypeSourceRange();
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00002524 else
Alp Tokerd0787eb2014-07-02 01:47:15 +00002525 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2526 << New->getReturnTypeSourceRange();
2527 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2528 << Old->getReturnTypeSourceRange();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00002529 return true;
2530 }
2531 else
2532 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002533 }
2534
Alp Toker314cc812014-01-25 16:55:45 +00002535 QualType OldReturnType = OldType->getReturnType();
2536 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002537 if (OldReturnType != NewReturnType) {
2538 // If this function has a deduced return type and has already been
2539 // defined, copy the deduced value from the old declaration.
Alp Toker314cc812014-01-25 16:55:45 +00002540 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002541 if (OldAT && OldAT->isDeduced()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00002542 New->setType(
2543 SubstAutoType(New->getType(),
2544 OldAT->isDependentType() ? Context.DependentTy
2545 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002546 NewQType = Context.getCanonicalType(
Richard Smithc58f38f2013-08-14 20:16:31 +00002547 SubstAutoType(NewQType,
2548 OldAT->isDependentType() ? Context.DependentTy
2549 : OldAT->getDeducedType()));
Richard Smith2a7d4812013-05-04 07:00:32 +00002550 }
2551 }
2552
2553 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2554 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002555 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00002556 // Preserve triviality.
2557 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00002558
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002559 // MSVC allows explicit template specialization at class scope:
Alp Toker8db6e7a2014-01-05 06:38:57 +00002560 // 2 CXXMethodDecls referring to the same function will be injected.
2561 // We don't want a redeclaration error.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002562 bool IsClassScopeExplicitSpecialization =
2563 OldMethod->isFunctionTemplateSpecialization() &&
2564 NewMethod->isFunctionTemplateSpecialization();
John McCall43314ab2010-04-13 07:45:41 +00002565 bool isFriend = NewMethod->getFriendObjectKind();
2566
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002567 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2568 !IsClassScopeExplicitSpecialization) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002569 // -- Member function declarations with the same name and the
2570 // same parameter types cannot be overloaded if any of them
2571 // is a static member function declaration.
Eli Friedmanf26b81b2013-06-19 22:43:55 +00002572 if (OldMethod->isStatic() != NewMethod->isStatic()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002573 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Richard Smithbdd14642014-02-04 01:14:30 +00002574 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002575 return true;
2576 }
Richard Smith57e7ff92012-07-13 04:12:04 +00002577
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002578 // C++ [class.mem]p1:
2579 // [...] A member shall not be declared twice in the
2580 // member-specification, except that a nested class or member
2581 // class template can be declared and then later defined.
Richard Smith57e7ff92012-07-13 04:12:04 +00002582 if (ActiveTemplateInstantiations.empty()) {
2583 unsigned NewDiag;
2584 if (isa<CXXConstructorDecl>(OldMethod))
2585 NewDiag = diag::err_constructor_redeclared;
2586 else if (isa<CXXDestructorDecl>(NewMethod))
2587 NewDiag = diag::err_destructor_redeclared;
2588 else if (isa<CXXConversionDecl>(NewMethod))
2589 NewDiag = diag::err_conv_function_redeclared;
2590 else
2591 NewDiag = diag::err_member_redeclared;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002592
Richard Smith57e7ff92012-07-13 04:12:04 +00002593 Diag(New->getLocation(), NewDiag);
2594 } else {
2595 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2596 << New << New->getType();
2597 }
Richard Smithbdd14642014-02-04 01:14:30 +00002598 Diag(OldLocation, PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00002599
2600 // Complain if this is an explicit declaration of a special
2601 // member that was initially declared implicitly.
2602 //
2603 // As an exception, it's okay to befriend such methods in order
2604 // to permit the implicit constructor/destructor/operator calls.
2605 } else if (OldMethod->isImplicit()) {
2606 if (isFriend) {
2607 NewMethod->setImplicit();
2608 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002609 Diag(NewMethod->getLocation(),
2610 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00002611 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00002612 return true;
2613 }
Richard Smith337a5a12012-06-08 01:30:54 +00002614 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00002615 Diag(NewMethod->getLocation(),
2616 diag::err_definition_of_explicitly_defaulted_member)
2617 << getSpecialMember(OldMethod);
2618 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002619 }
2620 }
2621
Richard Smith10876ef2013-01-17 01:30:42 +00002622 // C++11 [dcl.attr.noreturn]p1:
2623 // The first declaration of a function shall specify the noreturn
2624 // attribute if any declaration of that function specifies the noreturn
2625 // attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002626 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2627 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2628 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
Rafael Espindola8db352d2013-10-17 15:37:26 +00002629 Diag(Old->getFirstDecl()->getLocation(),
Richard Smith10876ef2013-01-17 01:30:42 +00002630 diag::note_noreturn_missing_first_decl);
2631 }
2632
Richard Smithe233fbf2013-01-28 22:42:45 +00002633 // C++11 [dcl.attr.depend]p2:
2634 // The first declaration of a function shall specify the
2635 // carries_dependency attribute for its declarator-id if any declaration
2636 // of the function specifies the carries_dependency attribute.
Aaron Ballmancf3b4832013-12-19 13:36:16 +00002637 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2638 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2639 Diag(CDA->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002640 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002641 Diag(Old->getFirstDecl()->getLocation(),
Richard Smithe233fbf2013-01-28 22:42:45 +00002642 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2643 }
2644
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002645 // (C++98 8.3.5p3):
2646 // All declarations for a function shall agree exactly in both the
2647 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00002648 // We also want to respect all the extended bits except noreturn.
2649
2650 // noreturn should now match unless the old type info didn't have it.
2651 QualType OldQTypeForComparison = OldQType;
2652 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2653 assert(OldQType == QualType(OldType, 0));
2654 const FunctionType *OldTypeForComparison
2655 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2656 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2657 assert(OldQTypeForComparison.isCanonical());
2658 }
2659
Rafael Espindolaf4187652013-02-14 01:18:37 +00002660 if (haveIncompatibleLanguageLinkages(Old, New)) {
Alp Tokerdd551fc2013-10-22 22:53:01 +00002661 // As a special case, retain the language linkage from previous
2662 // declarations of a friend function as an extension.
2663 //
2664 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2665 // and is useful because there's otherwise no way to specify language
2666 // linkage within class scope.
2667 //
2668 // Check cautiously as the friend object kind isn't yet complete.
2669 if (New->getFriendObjectKind() != Decl::FOK_None) {
2670 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002671 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002672 } else {
2673 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002674 Diag(OldLocation, PrevDiag);
Alp Tokerdd551fc2013-10-22 22:53:01 +00002675 return true;
2676 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00002677 }
2678
John McCall4f5019e2010-12-19 02:44:49 +00002679 if (OldQTypeForComparison == NewQType)
Richard Smith1c34fb72013-08-13 18:18:50 +00002680 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002681
Richard Smith541b38b2013-09-20 01:15:31 +00002682 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2683 New->isLocalExternDecl()) {
2684 // It's OK if we couldn't merge types for a local function declaraton
2685 // if either the old or new type is dependent. We'll merge the types
2686 // when we instantiate the function.
2687 return false;
2688 }
2689
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002690 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00002691 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002692
2693 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00002694 // duplicate function decls like "void f(int); void f(enum X);" properly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002695 if (!getLangOpts().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00002696 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00002697 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2698 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Craig Topperc3ec1492014-05-26 06:22:03 +00002699 const FunctionProtoType *OldProto = nullptr;
Richard Smith1c34fb72013-08-13 18:18:50 +00002700 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002701 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002702 // The old declaration provided a function prototype, but the
2703 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002704 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002705 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
Alp Toker314cc812014-01-25 16:55:45 +00002706 NewQType =
2707 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2708 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002709 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00002710 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002711
Alp Toker4284c6e2014-05-11 16:05:55 +00002712 // Synthesize parameters with the same types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002713 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002714 for (const auto &ParamType : OldProto->param_types()) {
2715 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002716 SourceLocation(), nullptr,
2717 ParamType, /*TInfo=*/nullptr,
2718 SC_None, nullptr);
John McCall8fb0d9d2011-05-01 22:35:37 +00002719 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00002720 Param->setImplicit();
2721 Params.push_back(Param);
2722 }
2723
David Blaikie9c70e042011-09-21 18:16:56 +00002724 New->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00002725 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00002726
Richard Smith1c34fb72013-08-13 18:18:50 +00002727 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002728 }
Chris Lattner45d561a2007-11-06 06:07:26 +00002729
Douglas Gregora74a2972009-03-06 22:43:54 +00002730 // GNU C permits a K&R definition to follow a prototype declaration
2731 // if the declared types of the parameters in the K&R definition
2732 // match the types in the prototype declaration, even when the
2733 // promoted types of the parameters from the K&R definition differ
2734 // from the types in the prototype. GCC then keeps the types from
2735 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002736 //
2737 // If a variadic prototype is followed by a non-variadic K&R definition,
2738 // the K&R definition becomes variadic. This is sort of an edge case, but
2739 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2740 // C99 6.9.1p8.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002741 if (!getLangOpts().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002742 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00002743 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00002744 Old->getNumParams() == New->getNumParams()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002745 SmallVector<QualType, 16> ArgTypes;
2746 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00002747 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00002748 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002749 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00002750 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00002751
Douglas Gregora74a2972009-03-06 22:43:54 +00002752 // Determine whether this is the GNU C extension.
Alp Toker314cc812014-01-25 16:55:45 +00002753 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2754 NewProto->getReturnType());
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002755 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00002756 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002757 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002758 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2759 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00002760 if (Context.typesAreCompatible(OldParm->getType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00002761 NewProto->getParamType(Idx))) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002762 ArgTypes.push_back(NewParm->getType());
2763 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002764 NewParm->getType(),
2765 /*CompareUnqualified=*/true)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002766 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2767 NewProto->getParamType(Idx) };
Douglas Gregora74a2972009-03-06 22:43:54 +00002768 Warnings.push_back(Warn);
2769 ArgTypes.push_back(NewParm->getType());
2770 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002771 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00002772 }
2773
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002774 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00002775 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2776 Diag(Warnings[Warn].NewParm->getLocation(),
2777 diag::ext_param_promoted_not_compatible_with_prototype)
2778 << Warnings[Warn].PromotedType
2779 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00002780 if (Warnings[Warn].OldParm->getLocation().isValid())
2781 Diag(Warnings[Warn].OldParm->getLocation(),
2782 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00002783 }
2784
Richard Smith1c34fb72013-08-13 18:18:50 +00002785 if (MergeTypeWithOld)
2786 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2787 OldProto->getExtProtoInfo()));
2788 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
Douglas Gregora74a2972009-03-06 22:43:54 +00002789 }
2790
2791 // Fall through to diagnose conflicting types.
2792 }
2793
John McCallad327cd2013-04-14 08:50:55 +00002794 // A function that has already been declared has been redeclared or
2795 // defined with a different type; show an appropriate diagnostic.
2796
2797 // If the previous declaration was an implicitly-generated builtin
2798 // declaration, then at the very least we should use a specialized note.
2799 unsigned BuiltinID;
2800 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2801 // If it's actually a library-defined builtin function like 'malloc'
2802 // or 'printf', just warn about the incompatible redeclaration.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002803 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002804 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Richard Smithbdd14642014-02-04 01:14:30 +00002805 Diag(OldLocation, diag::note_previous_builtin_declaration)
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002806 << Old << Old->getType();
John McCallad327cd2013-04-14 08:50:55 +00002807
2808 // If this is a global redeclaration, just forget hereafter
2809 // about the "builtin-ness" of the function.
2810 //
2811 // Doing this for local extern declarations is problematic. If
2812 // the builtin declaration remains visible, a second invalid
2813 // local declaration will produce a hard error; if it doesn't
2814 // remain visible, a single bogus local redeclaration (which is
2815 // actually only a warning) could break all the downstream code.
Richard Smith541b38b2013-09-20 01:15:31 +00002816 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
John McCallad327cd2013-04-14 08:50:55 +00002817 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2818
Douglas Gregor893c2c92009-03-23 17:47:24 +00002819 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002820 }
Steve Naroff17832a42008-01-16 15:01:34 +00002821
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002822 PrevDiag = diag::note_previous_builtin_declaration;
2823 }
2824
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002825 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Richard Smithbdd14642014-02-04 01:14:30 +00002826 Diag(OldLocation, PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002827 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00002828}
2829
Douglas Gregore62c0a42009-02-24 01:23:02 +00002830/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00002831/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00002832///
2833/// This routine handles the merging of attributes and other
Alp Toker5f6b8ac2013-10-22 09:00:49 +00002834/// properties of function declarations from the old declaration to
Douglas Gregore62c0a42009-02-24 01:23:02 +00002835/// the new declaration, once we know that New is in fact a
2836/// redeclaration of Old.
2837///
2838/// \returns false
James Molloye9430032012-03-13 08:55:35 +00002839bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Richard Smith1c34fb72013-08-13 18:18:50 +00002840 Scope *S, bool MergeTypeWithOld) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00002841 // Merge the attributes
Douglas Gregor32c17572012-01-01 20:30:41 +00002842 mergeDeclAttributes(New, Old);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002843
Douglas Gregore62c0a42009-02-24 01:23:02 +00002844 // Merge "pure" flag.
2845 if (Old->isPure())
2846 New->setPure();
2847
Rafael Espindolabefe1302012-11-25 14:07:59 +00002848 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00002849 if (Old->getMostRecentDecl()->isUsed(false))
2850 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00002851
John McCallf79e87d2011-03-02 04:00:57 +00002852 // Merge attributes from the parameters. These can mismatch with K&R
2853 // declarations.
2854 if (New->getNumParams() == Old->getNumParams())
2855 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2856 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
Richard Smithe233fbf2013-01-28 22:42:45 +00002857 *this);
John McCallf79e87d2011-03-02 04:00:57 +00002858
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 if (getLangOpts().CPlusPlus)
James Molloye9430032012-03-13 08:55:35 +00002860 return MergeCXXFunctionDecl(New, Old, S);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002861
Rafael Espindola8778c282012-11-29 16:09:03 +00002862 // Merge the function types so the we get the composite types for the return
Richard Smith1c34fb72013-08-13 18:18:50 +00002863 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2864 // was visible.
Rafael Espindola8778c282012-11-29 16:09:03 +00002865 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
Richard Smith1c34fb72013-08-13 18:18:50 +00002866 if (!Merged.isNull() && MergeTypeWithOld)
Rafael Espindola8778c282012-11-29 16:09:03 +00002867 New->setType(Merged);
2868
Douglas Gregore62c0a42009-02-24 01:23:02 +00002869 return false;
2870}
2871
John McCall31168b02011-06-15 23:02:42 +00002872
John McCallf79e87d2011-03-02 04:00:57 +00002873void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
Douglas Gregor32c17572012-01-01 20:30:41 +00002874 ObjCMethodDecl *oldMethod) {
John McCalld2930c22011-07-22 02:45:48 +00002875
Fariborz Jahanian3da28f82012-06-05 21:14:46 +00002876 // Merge the attributes, including deprecated/unavailable
Ted Kremenekb5445722013-04-06 00:34:27 +00002877 AvailabilityMergeKind MergeKind =
2878 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2879 : AMK_Override;
2880 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
John McCallf79e87d2011-03-02 04:00:57 +00002881
2882 // Merge attributes from the parameters.
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002883 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2884 oe = oldMethod->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002885 for (ObjCMethodDecl::param_iterator
John McCallf79e87d2011-03-02 04:00:57 +00002886 ni = newMethod->param_begin(), ne = newMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002887 ni != ne && oi != oe; ++ni, ++oi)
Richard Smithe233fbf2013-01-28 22:42:45 +00002888 mergeParamDeclAttributes(*ni, *oi, *this);
John McCalld2930c22011-07-22 02:45:48 +00002889
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002890 CheckObjCMethodOverride(newMethod, oldMethod);
John McCallf79e87d2011-03-02 04:00:57 +00002891}
2892
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002893/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2894/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00002895/// emitting diagnostics as appropriate.
2896///
2897/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
Sebastian Redla9351792012-02-11 23:51:47 +00002898/// to here in AddInitializerToDecl. We can't check them before the initializer
2899/// is attached.
Richard Smith1c34fb72013-08-13 18:18:50 +00002900void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2901 bool MergeTypeWithOld) {
Richard Smith30482bc2011-02-20 03:19:35 +00002902 if (New->isInvalidDecl() || Old->isInvalidDecl())
2903 return;
2904
2905 QualType MergedT;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002906 if (getLangOpts().CPlusPlus) {
Richard Smith27d807c2013-04-30 13:56:41 +00002907 if (New->getType()->isUndeducedType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00002908 // We don't know what the new type is until the initializer is attached.
2909 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002910 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2911 // These could still be something that needs exception specs checked.
2912 return MergeVarDeclExceptionSpecs(New, Old);
2913 }
Richard Smith30482bc2011-02-20 03:19:35 +00002914 // C++ [basic.link]p10:
2915 // [...] the types specified by all declarations referring to a given
2916 // object or function shall be identical, except that declarations for an
2917 // array object can specify array types that differ by the presence or
2918 // absence of a major array bound (8.3.4).
2919 else if (Old->getType()->isIncompleteArrayType() &&
2920 New->getType()->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002921 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2922 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2923 if (Context.hasSameType(OldArray->getElementType(),
2924 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002925 MergedT = New->getType();
2926 } else if (Old->getType()->isArrayType() &&
Richard Smith541b38b2013-09-20 01:15:31 +00002927 New->getType()->isIncompleteArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00002928 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2929 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2930 if (Context.hasSameType(OldArray->getElementType(),
2931 NewArray->getElementType()))
Richard Smith30482bc2011-02-20 03:19:35 +00002932 MergedT = Old->getType();
Richard Smith541b38b2013-09-20 01:15:31 +00002933 } else if (New->getType()->isObjCObjectPointerType() &&
2934 Old->getType()->isObjCObjectPointerType()) {
2935 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2936 Old->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00002937 }
2938 } else {
Richard Smith541b38b2013-09-20 01:15:31 +00002939 // C 6.2.7p2:
2940 // All declarations that refer to the same object or function shall have
2941 // compatible type.
Richard Smith30482bc2011-02-20 03:19:35 +00002942 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2943 }
2944 if (MergedT.isNull()) {
Richard Smith1c34fb72013-08-13 18:18:50 +00002945 // It's OK if we couldn't merge types if either type is dependent, for a
2946 // block-scope variable. In other cases (static data members of class
2947 // templates, variable templates, ...), we require the types to be
2948 // equivalent.
2949 // FIXME: The C++ standard doesn't say anything about this.
2950 if ((New->getType()->isDependentType() ||
2951 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2952 // If the old type was dependent, we can't merge with it, so the new type
2953 // becomes dependent for now. We'll reproduce the original type when we
2954 // instantiate the TypeSourceInfo for the variable.
2955 if (!New->getType()->isDependentType() && MergeTypeWithOld)
2956 New->setType(Context.DependentTy);
2957 return;
2958 }
2959
2960 // FIXME: Even if this merging succeeds, some other non-visible declaration
2961 // of this variable might have an incompatible type. For instance:
2962 //
2963 // extern int arr[];
2964 // void f() { extern int arr[2]; }
2965 // void g() { extern int arr[3]; }
2966 //
2967 // Neither C nor C++ requires a diagnostic for this, but we should still try
2968 // to diagnose it.
Richard Smith30482bc2011-02-20 03:19:35 +00002969 Diag(New->getLocation(), diag::err_redefinition_different_type)
David Blaikie65902202012-09-20 18:38:57 +00002970 << New->getDeclName() << New->getType() << Old->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00002971 Diag(Old->getLocation(), diag::note_previous_definition);
2972 return New->setInvalidDecl();
2973 }
John McCallb65e8fe2013-04-01 18:34:28 +00002974
2975 // Don't actually update the type on the new declaration if the old
Richard Smith3c785782013-09-03 21:00:58 +00002976 // declaration was an extern declaration in a different scope.
Richard Smith1c34fb72013-08-13 18:18:50 +00002977 if (MergeTypeWithOld)
John McCallb65e8fe2013-04-01 18:34:28 +00002978 New->setType(MergedT);
Richard Smith30482bc2011-02-20 03:19:35 +00002979}
2980
Richard Smith3c785782013-09-03 21:00:58 +00002981static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2982 LookupResult &Previous) {
2983 // C11 6.2.7p4:
2984 // For an identifier with internal or external linkage declared
2985 // in a scope in which a prior declaration of that identifier is
2986 // visible, if the prior declaration specifies internal or
2987 // external linkage, the type of the identifier at the later
2988 // declaration becomes the composite type.
2989 //
2990 // If the variable isn't visible, we do not merge with its type.
2991 if (Previous.isShadowed())
2992 return false;
2993
2994 if (S.getLangOpts().CPlusPlus) {
2995 // C++11 [dcl.array]p3:
2996 // If there is a preceding declaration of the entity in the same
2997 // scope in which the bound was specified, an omitted array bound
2998 // is taken to be the same as in that earlier declaration.
2999 return NewVD->isPreviousDeclInSameBlockScope() ||
3000 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3001 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3002 } else {
3003 // If the old declaration was function-local, don't merge with its
3004 // type unless we're in the same function.
3005 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3006 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3007 }
3008}
3009
Chris Lattner01564d92007-01-27 19:27:06 +00003010/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3011/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3012/// situation, merging decls or emitting diagnostics as appropriate.
3013///
Mike Stump11289f42009-09-09 15:08:12 +00003014/// Tentative definition rules (C99 6.9.2p2) are checked by
3015/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00003016/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00003017///
Richard Smith3c785782013-09-03 21:00:58 +00003018void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
John McCall1f82f242009-11-18 22:49:29 +00003019 // If the new decl is already invalid, don't do any other checking.
3020 if (New->isInvalidDecl())
3021 return;
Mike Stump11289f42009-09-09 15:08:12 +00003022
Richard Smithbeef3452014-01-16 23:39:20 +00003023 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3024
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003025 // Verify the old decl was also a variable or variable template.
Craig Topperc3ec1492014-05-26 06:22:03 +00003026 VarDecl *Old = nullptr;
3027 VarTemplateDecl *OldTemplate = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003028 if (Previous.isSingleResult()) {
3029 if (NewTemplate) {
3030 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003031 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00003032 } else
3033 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
Larisse Voufod8dd97c2013-08-14 03:09:19 +00003034 }
3035 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003036 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003037 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00003038 Diag(Previous.getRepresentativeDecl()->getLocation(),
3039 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003040 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00003041 }
Chris Lattner84966392008-03-03 03:28:21 +00003042
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00003043 if (!shouldLinkPossiblyHiddenDecl(Old, New))
3044 return;
3045
Richard Smithbeef3452014-01-16 23:39:20 +00003046 // Ensure the template parameters are compatible.
3047 if (NewTemplate &&
3048 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3049 OldTemplate->getTemplateParameters(),
3050 /*Complain=*/true, TPL_TemplateMatch))
3051 return;
3052
Douglas Gregor2c7d9292010-08-30 14:32:14 +00003053 // C++ [class.mem]p1:
3054 // A member shall not be declared twice in the member-specification [...]
3055 //
3056 // Here, we need only consider static data members.
3057 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3058 Diag(New->getLocation(), diag::err_duplicate_member)
3059 << New->getIdentifier();
3060 Diag(Old->getLocation(), diag::note_previous_declaration);
3061 New->setInvalidDecl();
3062 }
3063
Douglas Gregor32c17572012-01-01 20:30:41 +00003064 mergeDeclAttributes(New, Old);
David Blaikie30d15442011-10-19 22:56:21 +00003065 // Warn if an already-declared variable is made a weak_import in a subsequent
3066 // declaration
Aaron Ballman9ead1242013-12-19 02:39:40 +00003067 if (New->hasAttr<WeakImportAttr>() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00003068 Old->getStorageClass() == SC_None &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00003069 !Old->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003070 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3071 Diag(Old->getLocation(), diag::note_previous_definition);
3072 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00003073 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00003074 }
Chris Lattner84966392008-03-03 03:28:21 +00003075
Richard Smith30482bc2011-02-20 03:19:35 +00003076 // Merge the types.
Richard Smith3c785782013-09-03 21:00:58 +00003077 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3078
Richard Smith30482bc2011-02-20 03:19:35 +00003079 if (New->isInvalidDecl())
3080 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00003081
David Majnemer5b63fa02014-06-18 23:26:25 +00003082 diag::kind PrevDiag;
3083 SourceLocation OldLocation;
3084 std::tie(PrevDiag, OldLocation) =
3085 getNoteDiagForInvalidRedeclaration(Old, New);
3086
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003087 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
John McCall8e7d6562010-08-26 03:08:43 +00003088 if (New->getStorageClass() == SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003089 !New->isStaticDataMember() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00003090 Old->hasExternalFormalLinkage()) {
David Majnemer5b63fa02014-06-18 23:26:25 +00003091 if (getLangOpts().MicrosoftExt) {
3092 Diag(New->getLocation(), diag::ext_static_non_static)
3093 << New->getDeclName();
3094 Diag(OldLocation, PrevDiag);
3095 } else {
3096 Diag(New->getLocation(), diag::err_static_non_static)
3097 << New->getDeclName();
3098 Diag(OldLocation, PrevDiag);
3099 return New->setInvalidDecl();
3100 }
Steve Naroff1e787362008-01-30 00:44:01 +00003101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00003103 // For an identifier declared with the storage-class specifier
3104 // extern in a scope in which a prior declaration of that
3105 // identifier is visible,23) if the prior declaration specifies
3106 // internal or external linkage, the linkage of the identifier at
3107 // the later declaration is the same as the linkage specified at
3108 // the prior declaration. If no prior declaration is visible, or
3109 // if the prior declaration specifies no linkage, then the
3110 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00003111 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00003112 /* Okay */;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003113 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
Rafael Espindola8ac2f592013-04-04 21:21:25 +00003114 !New->isStaticDataMember() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003115 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003116 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003117 Diag(OldLocation, PrevDiag);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003118 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00003119 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003120
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003121 // Check if extern is followed by non-extern and vice-versa.
3122 if (New->hasExternalStorage() &&
3123 !Old->hasLinkage() && Old->isLocalVarDecl()) {
3124 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003125 Diag(OldLocation, PrevDiag);
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003126 return New->setInvalidDecl();
3127 }
Rafael Espindola869fe042013-04-04 02:47:57 +00003128 if (Old->hasLinkage() && New->isLocalVarDecl() &&
3129 !New->hasExternalStorage()) {
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003130 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003131 Diag(OldLocation, PrevDiag);
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00003132 return New->setInvalidDecl();
3133 }
3134
Steve Naroffa5629372008-09-17 14:05:40 +00003135 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00003136
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003137 // FIXME: The test for external storage here seems wrong? We still
3138 // need to check for mismatches.
3139 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00003140 // Don't complain about out-of-line definitions of static members.
3141 !(Old->getLexicalDeclContext()->isRecord() &&
3142 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00003143 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003144 Diag(OldLocation, PrevDiag);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003145 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00003146 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00003147
Richard Smithfd3834f2013-04-13 02:43:54 +00003148 if (New->getTLSKind() != Old->getTLSKind()) {
3149 if (!Old->getTLSKind()) {
3150 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003151 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003152 } else if (!New->getTLSKind()) {
3153 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
David Majnemer5b63fa02014-06-18 23:26:25 +00003154 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003155 } else {
3156 // Do not allow redeclaration to change the variable between requiring
3157 // static and dynamic initialization.
3158 // FIXME: GCC allows this, but uses the TLS keyword on the first
3159 // declaration to determine the kind. Do we need to be compatible here?
3160 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3161 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
David Majnemer5b63fa02014-06-18 23:26:25 +00003162 Diag(OldLocation, PrevDiag);
Richard Smithfd3834f2013-04-13 02:43:54 +00003163 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003164 }
3165
Sebastian Redlf1842912010-02-02 18:35:11 +00003166 // C++ doesn't have tentative definitions, so go right ahead and check here.
3167 const VarDecl *Def;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003168 if (getLangOpts().CPlusPlus &&
Sebastian Redld85be0c2010-02-03 02:08:48 +00003169 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00003170 (Def = Old->getDefinition())) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003171 Diag(New->getLocation(), diag::err_redefinition) << New;
Sebastian Redlf1842912010-02-02 18:35:11 +00003172 Diag(Def->getLocation(), diag::note_previous_definition);
3173 New->setInvalidDecl();
3174 return;
3175 }
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003176
Rafael Espindolaf4187652013-02-14 01:18:37 +00003177 if (haveIncompatibleLanguageLinkages(Old, New)) {
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003178 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
David Majnemer5b63fa02014-06-18 23:26:25 +00003179 Diag(OldLocation, PrevDiag);
Rafael Espindolacffa95d2012-12-27 03:56:20 +00003180 New->setInvalidDecl();
3181 return;
3182 }
3183
Rafael Espindolabefe1302012-11-25 14:07:59 +00003184 // Merge "used" flag.
Rafael Espindolae4865d22013-10-23 16:46:34 +00003185 if (Old->getMostRecentDecl()->isUsed(false))
3186 New->setIsUsed();
Rafael Espindolabefe1302012-11-25 14:07:59 +00003187
Douglas Gregor0760fa12009-03-10 23:43:53 +00003188 // Keep a chain of previous declarations.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003189 New->setPreviousDecl(Old);
Richard Smithbeef3452014-01-16 23:39:20 +00003190 if (NewTemplate)
3191 NewTemplate->setPreviousDecl(OldTemplate);
John McCall401982f2010-01-20 21:53:11 +00003192
3193 // Inherit access appropriately.
3194 New->setAccess(Old->getAccess());
Richard Smithbeef3452014-01-16 23:39:20 +00003195 if (NewTemplate)
3196 NewTemplate->setAccess(New->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00003197}
3198
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003199/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3200/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00003201Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00003202 DeclSpec &DS) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003203 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003204}
3205
David Majnemer2206bf52014-03-05 08:57:59 +00003206static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003207 if (!S.Context.getLangOpts().CPlusPlus)
3208 return;
3209
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003210 if (isa<CXXRecordDecl>(Tag->getParent())) {
3211 // If this tag is the direct child of a class, number it if
3212 // it is anonymous.
3213 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3214 return;
3215 MangleNumberingContext &MCtx =
3216 S.Context.getManglingNumberContext(Tag->getParent());
David Majnemerf27217f2014-03-05 18:55:38 +00003217 S.Context.setManglingNumber(
3218 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003219 return;
3220 }
3221
3222 // If this tag isn't a direct child of a class, number it if it is local.
3223 Decl *ManglingContextDecl;
3224 if (MangleNumberingContext *MCtx =
3225 S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3226 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003227 S.Context.setManglingNumber(
3228 Tag,
3229 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00003230 }
3231}
3232
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003233/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
Richard Smithb1402ae2013-03-18 22:52:47 +00003234/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003235/// parameters to cope with template friend declarations.
3236Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3237 DeclSpec &DS,
Richard Smithb1402ae2013-03-18 22:52:47 +00003238 MultiTemplateParamsArg TemplateParams,
3239 bool IsExplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003240 Decl *TagD = nullptr;
3241 TagDecl *Tag = nullptr;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003242 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3243 DS.getTypeSpecType() == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003244 DS.getTypeSpecType() == DeclSpec::TST_interface ||
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003245 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003246 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00003247 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00003248
3249 if (!TagD) // We probably had an error
Craig Topperc3ec1492014-05-26 06:22:03 +00003250 return nullptr;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003251
John McCall07e91c02009-08-06 02:15:43 +00003252 // Note that the above type specs guarantee that the
3253 // type rep is a Decl, whereas in many of the others
3254 // it's a Type.
Peter Collingbournee109a2c2011-10-23 17:07:16 +00003255 if (isa<TagDecl>(TagD))
3256 Tag = cast<TagDecl>(TagD);
3257 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3258 Tag = CTD->getTemplatedDecl();
Douglas Gregor1b57ff32009-05-12 23:25:50 +00003259 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003260
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003261 if (Tag) {
David Majnemer2206bf52014-03-05 08:57:59 +00003262 HandleTagNumbering(*this, Tag, S);
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003263 Tag->setFreeStanding();
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +00003264 if (Tag->isInvalidDecl())
3265 return Tag;
3266 }
Argyrios Kyrtzidis201d3772011-09-30 22:11:31 +00003267
Nuno Lopese9823fa2009-12-17 11:35:26 +00003268 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3269 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3270 // or incomplete types shall not be restrict-qualified."
3271 if (TypeQuals & DeclSpec::TQ_restrict)
3272 Diag(DS.getRestrictSpecLoc(),
3273 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3274 << DS.getSourceRange();
3275 }
3276
Richard Smitha77a0a62011-08-15 21:04:07 +00003277 if (DS.isConstexprSpecified()) {
3278 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3279 // and definitions of functions and variables.
3280 if (Tag)
3281 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3282 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3283 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003284 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3285 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
Richard Smitha77a0a62011-08-15 21:04:07 +00003286 else
3287 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3288 // Don't emit warnings after this error.
3289 return TagD;
3290 }
3291
Richard Smithb1402ae2013-03-18 22:52:47 +00003292 DiagnoseFunctionSpecifiers(DS);
3293
Douglas Gregor3dad8422009-09-26 06:47:28 +00003294 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00003295 // If we're dealing with a decl but not a TagDecl, assume that
3296 // whatever routines created it handled the friendship aspect.
3297 if (TagD && !Tag)
Craig Topperc3ec1492014-05-26 06:22:03 +00003298 return nullptr;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00003299 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00003300 }
John McCallaa017372011-03-22 23:00:04 +00003301
Richard Smithb1402ae2013-03-18 22:52:47 +00003302 CXXScopeSpec &SS = DS.getTypeSpecScope();
3303 bool IsExplicitSpecialization =
3304 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3305 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3306 !IsExplicitInstantiation && !IsExplicitSpecialization) {
3307 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3308 // nested-name-specifier unless it is an explicit instantiation
3309 // or an explicit specialization.
3310 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3311 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3312 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3313 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3314 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3315 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3316 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00003317 return nullptr;
Richard Smithb1402ae2013-03-18 22:52:47 +00003318 }
3319
3320 // Track whether this decl-specifier declares anything.
3321 bool DeclaresAnything = true;
3322
3323 // Handle anonymous struct definitions.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003324 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCallf937c022011-10-07 06:10:15 +00003325 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003326 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003327 if (getLangOpts().CPlusPlus ||
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003328 Record->getDeclContext()->isRecord())
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003329 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003330
Richard Smithb1402ae2013-03-18 22:52:47 +00003331 DeclaresAnything = false;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00003332 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003333 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003334
Richard Smithb1402ae2013-03-18 22:52:47 +00003335 // Check for Microsoft C extension: anonymous struct member.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003336 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003337 CurContext->isRecord() &&
3338 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3339 // Handle 2 kinds of anonymous struct:
3340 // struct STRUCT;
3341 // and
3342 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3343 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
John McCallf937c022011-10-07 06:10:15 +00003344 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003345 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3346 DS.getRepAsType().get()->isStructureType())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003347 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003348 << DS.getSourceRange();
3349 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3350 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003351 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003352
3353 // Skip all the checks below if we have a type error.
3354 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3355 (TagD && TagD->isInvalidDecl()))
3356 return TagD;
3357
3358 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa8c9722010-07-13 06:24:26 +00003359 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3360 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3361 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
Richard Smithb1402ae2013-03-18 22:52:47 +00003362 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3363 DeclaresAnything = false;
John McCallaa017372011-03-22 23:00:04 +00003364
John McCallaa017372011-03-22 23:00:04 +00003365 if (!DS.isMissingDeclaratorOk()) {
Richard Smithb1402ae2013-03-18 22:52:47 +00003366 // Customize diagnostic for a typedef missing a name.
3367 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003368 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00003369 << DS.getSourceRange();
Richard Smithb1402ae2013-03-18 22:52:47 +00003370 else
3371 DeclaresAnything = false;
Sebastian Redla2b5e312008-12-28 15:28:59 +00003372 }
Mike Stump11289f42009-09-09 15:08:12 +00003373
Richard Smithb1402ae2013-03-18 22:52:47 +00003374 if (DS.isModulePrivateSpecified() &&
Douglas Gregor41866812011-09-12 18:37:38 +00003375 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3376 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3377 << Tag->getTagKind()
3378 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3379
Richard Smithb1402ae2013-03-18 22:52:47 +00003380 ActOnDocumentableDecl(TagD);
3381
3382 // C 6.7/2:
3383 // A declaration [...] shall declare at least a declarator [...], a tag,
3384 // or the members of an enumeration.
3385 // C++ [dcl.dcl]p3:
3386 // [If there are no declarators], and except for the declaration of an
3387 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3388 // names into the program, or shall redeclare a name introduced by a
3389 // previous declaration.
3390 if (!DeclaresAnything) {
3391 // In C, we allow this as a (popular) extension / bug. Don't bother
3392 // producing further diagnostics for redundant qualifiers after this.
3393 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3394 return TagD;
3395 }
3396
3397 // C++ [dcl.stc]p1:
3398 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3399 // init-declarator-list of the declaration shall not be empty.
3400 // C++ [dcl.fct.spec]p1:
3401 // If a cv-qualifier appears in a decl-specifier-seq, the
3402 // init-declarator-list of the declaration shall not be empty.
3403 //
3404 // Spurious qualifiers here appear to be valid in C.
3405 unsigned DiagID = diag::warn_standalone_specifier;
3406 if (getLangOpts().CPlusPlus)
3407 DiagID = diag::ext_standalone_specifier;
3408
3409 // Note that a linkage-specification sets a storage class, but
3410 // 'extern "C" struct foo;' is actually valid and not theoretically
3411 // useless.
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003412 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3413 if (SCS == DeclSpec::SCS_mutable)
3414 // Since mutable is not a viable storage class specifier in C, there is
3415 // no reason to treat it as an extension. Instead, diagnose as an error.
3416 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3417 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
Richard Smithb1402ae2013-03-18 22:52:47 +00003418 Diag(DS.getStorageClassSpecLoc(), DiagID)
3419 << DeclSpec::getSpecifierName(SCS);
Aaron Ballman5a1ef6b2014-05-26 17:03:54 +00003420 }
Richard Smithb1402ae2013-03-18 22:52:47 +00003421
Richard Smithb4a9e862013-04-12 22:46:28 +00003422 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3423 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3424 << DeclSpec::getSpecifierName(TSCS);
Richard Smithb1402ae2013-03-18 22:52:47 +00003425 if (DS.getTypeQualifiers()) {
3426 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3427 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3428 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3429 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3430 // Restrict is covered above.
Richard Smith8e1ac332013-03-28 01:55:44 +00003431 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3432 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
Richard Smithb1402ae2013-03-18 22:52:47 +00003433 }
3434
Eli Friedmane3217952011-12-17 00:36:09 +00003435 // Warn about ignored type attributes, for example:
3436 // __attribute__((aligned)) struct A;
Bill Wendling44426052012-12-20 19:22:21 +00003437 // Attributes should be placed after tag to apply to type declaration.
Eli Friedmane3217952011-12-17 00:36:09 +00003438 if (!DS.getAttributes().empty()) {
3439 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3440 if (TypeSpecType == DeclSpec::TST_class ||
3441 TypeSpecType == DeclSpec::TST_struct ||
Joao Matosdc86f942012-08-31 18:45:21 +00003442 TypeSpecType == DeclSpec::TST_interface ||
Eli Friedmane3217952011-12-17 00:36:09 +00003443 TypeSpecType == DeclSpec::TST_union ||
3444 TypeSpecType == DeclSpec::TST_enum) {
3445 AttributeList* attrs = DS.getAttributes().getList();
3446 while (attrs) {
Michael Han360d2252012-10-04 16:42:52 +00003447 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
Eli Friedmane3217952011-12-17 00:36:09 +00003448 << attrs->getName()
3449 << (TypeSpecType == DeclSpec::TST_class ? 0 :
3450 TypeSpecType == DeclSpec::TST_struct ? 1 :
Joao Matosdc86f942012-08-31 18:45:21 +00003451 TypeSpecType == DeclSpec::TST_union ? 2 :
3452 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
Eli Friedmane3217952011-12-17 00:36:09 +00003453 attrs = attrs->getNext();
3454 }
3455 }
3456 }
John McCallaa017372011-03-22 23:00:04 +00003457
John McCall48871652010-08-21 09:40:31 +00003458 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003459}
3460
John McCallea305ed2009-12-18 10:40:03 +00003461/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00003462/// check if there's an existing declaration that can't be overloaded.
3463///
3464/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00003465static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3466 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00003467 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00003468 DeclarationName Name,
3469 SourceLocation NameLoc,
3470 unsigned diagnostic) {
3471 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3472 Sema::ForRedeclaration);
3473 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00003474
John McCallea305ed2009-12-18 10:40:03 +00003475 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00003476 return false;
3477
3478 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00003479 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00003480 assert(PrevDecl && "Expected a non-null Decl");
3481
3482 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3483 return false;
John McCall1f82f242009-11-18 22:49:29 +00003484
John McCallea305ed2009-12-18 10:40:03 +00003485 SemaRef.Diag(NameLoc, diagnostic) << Name;
3486 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00003487
3488 return true;
3489}
3490
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003491/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3492/// anonymous struct or union AnonRecord into the owning context Owner
3493/// and scope S. This routine will be invoked just after we realize
3494/// that an unnamed union or struct is actually an anonymous union or
3495/// struct, e.g.,
3496///
3497/// @code
3498/// union {
3499/// int i;
3500/// float f;
3501/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3502/// // f into the surrounding scope.x
3503/// @endcode
3504///
3505/// This routine is recursive, injecting the names of nested anonymous
3506/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00003507static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
Craig Topper5603df42013-07-05 19:34:19 +00003508 DeclContext *Owner,
3509 RecordDecl *AnonRecord,
3510 AccessSpecifier AS,
3511 SmallVectorImpl<NamedDecl *> &Chaining,
3512 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00003513 unsigned diagKind
3514 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3515 : diag::err_anonymous_struct_member_redecl;
3516
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003517 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003518
3519 // Look every FieldDecl and IndirectFieldDecl with a name.
Aaron Ballman629afae2014-03-07 19:56:05 +00003520 for (auto *D : AnonRecord->decls()) {
3521 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3522 cast<NamedDecl>(D)->getDeclName()) {
3523 ValueDecl *VD = cast<ValueDecl>(D);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003524 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3525 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003526 // C++ [class.union]p2:
3527 // The names of the members of an anonymous union shall be
3528 // distinct from the names of any other entity in the
3529 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003530 Invalid = true;
3531 } else {
3532 // C++ [class.union]p2:
3533 // For the purpose of name lookup, after the anonymous union
3534 // definition, the members of the anonymous union are
3535 // considered to have been defined in the scope in which the
3536 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003537 unsigned OldChainingSize = Chaining.size();
3538 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Aaron Ballman29c94602014-03-07 18:36:15 +00003539 for (auto *PI : IF->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00003540 Chaining.push_back(PI);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003541 else
3542 Chaining.push_back(VD);
3543
Francois Pichet783dd6e2010-11-21 06:08:52 +00003544 assert(Chaining.size() >= 2);
3545 NamedDecl **NamedChain =
3546 new (SemaRef.Context)NamedDecl*[Chaining.size()];
3547 for (unsigned i = 0; i < Chaining.size(); i++)
3548 NamedChain[i] = Chaining[i];
3549
3550 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003551 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3552 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00003553 NamedChain, Chaining.size());
3554
3555 IndirectField->setAccess(AS);
3556 IndirectField->setImplicit();
3557 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00003558
3559 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003560 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003561
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003562 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003563 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003564 }
3565 }
3566
3567 return Invalid;
3568}
3569
Douglas Gregorc4df4072010-04-19 22:54:31 +00003570/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3571/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00003572/// illegal input values are mapped to SC_None.
3573static StorageClass
Rafael Espindolabff59562013-04-25 12:11:36 +00003574StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3575 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3576 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3577 "Parser allowed 'typedef' as storage class VarDecl.");
Douglas Gregorc4df4072010-04-19 22:54:31 +00003578 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00003579 case DeclSpec::SCS_unspecified: return SC_None;
Rafael Espindolabff59562013-04-25 12:11:36 +00003580 case DeclSpec::SCS_extern:
3581 if (DS.isExternInLinkageSpec())
3582 return SC_None;
3583 return SC_Extern;
John McCall8e7d6562010-08-26 03:08:43 +00003584 case DeclSpec::SCS_static: return SC_Static;
3585 case DeclSpec::SCS_auto: return SC_Auto;
3586 case DeclSpec::SCS_register: return SC_Register;
3587 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003588 // Illegal SCSs map to None: error reporting is up to the caller.
3589 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00003590 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00003591 }
3592 llvm_unreachable("unknown storage class specifier");
3593}
3594
Richard Smithab44d5b2013-12-10 08:25:00 +00003595static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3596 assert(Record->hasInClassInitializer());
3597
Aaron Ballman629afae2014-03-07 19:56:05 +00003598 for (const auto *I : Record->decls()) {
3599 const auto *FD = dyn_cast<FieldDecl>(I);
3600 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Richard Smithab44d5b2013-12-10 08:25:00 +00003601 FD = IFD->getAnonField();
3602 if (FD && FD->hasInClassInitializer())
3603 return FD->getLocation();
3604 }
3605
3606 llvm_unreachable("couldn't find in-class initializer");
3607}
3608
3609static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3610 SourceLocation DefaultInitLoc) {
3611 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3612 return;
3613
3614 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3615 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3616}
3617
3618static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3619 CXXRecordDecl *AnonUnion) {
3620 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3621 return;
3622
3623 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3624}
3625
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003626/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003627/// anonymous structure or union. Anonymous unions are a C++ feature
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003628/// (C++ [class.union]) and a C11 feature; anonymous structures
3629/// are a C11 feature and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00003630Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003631 AccessSpecifier AS,
3632 RecordDecl *Record,
3633 const PrintingPolicy &Policy) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003634 DeclContext *Owner = Record->getDeclContext();
3635
3636 // Diagnose whether this anonymous struct/union is an extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003637 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003638 Diag(Record->getLocation(), diag::ext_anonymous_union);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003639 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003640 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003641 else if (!Record->isUnion() && !getLangOpts().C11)
Hans Wennborgb64a1fa2012-02-03 15:47:04 +00003642 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00003643
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003644 // C and C++ require different kinds of checks for anonymous
3645 // structs/unions.
3646 bool Invalid = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003647 if (getLangOpts().CPlusPlus) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003648 const char *PrevSpec = nullptr;
John McCall49bfce42009-08-03 20:12:06 +00003649 unsigned DiagID;
David Blaikie0a8e8992011-10-19 22:43:29 +00003650 if (Record->isUnion()) {
3651 // C++ [class.union]p6:
3652 // Anonymous unions declared in a named namespace or in the
3653 // global namespace shall be declared static.
3654 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3655 (isa<TranslationUnitDecl>(Owner) ||
3656 (isa<NamespaceDecl>(Owner) &&
3657 cast<NamespaceDecl>(Owner)->getDeclName()))) {
David Blaikie733f7bb2011-10-20 02:49:08 +00003658 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3659 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
David Blaikie0a8e8992011-10-19 22:43:29 +00003660
3661 // Recover by adding 'static'.
3662 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003663 PrevSpec, DiagID, Policy);
David Blaikie0a8e8992011-10-19 22:43:29 +00003664 }
3665 // C++ [class.union]p6:
3666 // A storage class is not allowed in a declaration of an
3667 // anonymous union in a class scope.
3668 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3669 isa<RecordDecl>(Owner)) {
3670 Diag(DS.getStorageClassSpecLoc(),
David Blaikie6f686fc2011-10-20 02:10:55 +00003671 diag::err_anonymous_union_with_storage_spec)
3672 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
David Blaikie0a8e8992011-10-19 22:43:29 +00003673
3674 // Recover by removing the storage specifier.
David Blaikie30d15442011-10-19 22:56:21 +00003675 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3676 SourceLocation(),
Erik Verbruggen888d52a2014-01-15 09:15:43 +00003677 PrevSpec, DiagID, Context.getPrintingPolicy());
David Blaikie0a8e8992011-10-19 22:43:29 +00003678 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003679 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003680
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003681 // Ignore const/volatile/restrict qualifiers.
3682 if (DS.getTypeQualifiers()) {
3683 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3684 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003685 << Record->isUnion() << "const"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003686 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3687 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Richard Smith8e1ac332013-03-28 01:55:44 +00003688 Diag(DS.getVolatileSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003689 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003690 << Record->isUnion() << "volatile"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003691 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3692 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Richard Smith8e1ac332013-03-28 01:55:44 +00003693 Diag(DS.getRestrictSpecLoc(),
David Blaikie30d15442011-10-19 22:56:21 +00003694 diag::ext_anonymous_struct_union_qualified)
Richard Smith8e1ac332013-03-28 01:55:44 +00003695 << Record->isUnion() << "restrict"
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003696 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
Richard Smith8e1ac332013-03-28 01:55:44 +00003697 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3698 Diag(DS.getAtomicSpecLoc(),
3699 diag::ext_anonymous_struct_union_qualified)
3700 << Record->isUnion() << "_Atomic"
3701 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
Douglas Gregor0f8bc972011-05-09 23:05:33 +00003702
3703 DS.ClearTypeQualifiers();
3704 }
3705
Mike Stump11289f42009-09-09 15:08:12 +00003706 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00003707 // The member-specification of an anonymous union shall only
3708 // define non-static data members. [Note: nested types and
3709 // functions cannot be declared within an anonymous union. ]
Aaron Ballman629afae2014-03-07 19:56:05 +00003710 for (auto *Mem : Record->decls()) {
3711 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003712 // C++ [class.union]p3:
3713 // An anonymous union shall not have private or protected
3714 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00003715 assert(FD->getAccess() != AS_none);
3716 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003717 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3718 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3719 Invalid = true;
3720 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003721
Alexis Hunt97ab5542011-05-16 22:41:40 +00003722 // C++ [class.union]p1
3723 // An object of a class with a non-trivial constructor, a non-trivial
3724 // copy constructor, a non-trivial destructor, or a non-trivial copy
3725 // assignment operator cannot be a member of a union, nor can an
3726 // array of such objects.
Richard Smithf720df02011-10-19 20:41:51 +00003727 if (CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00003728 Invalid = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00003729 } else if (Mem->isImplicit()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003730 // Any implicit members are fine.
Aaron Ballman629afae2014-03-07 19:56:05 +00003731 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
Douglas Gregor8761da52009-02-03 00:34:39 +00003732 // This is a type that showed up in an
3733 // elaborated-type-specifier inside the anonymous struct or
3734 // union, but which actually declares a type outside of the
3735 // anonymous struct or union. It's okay.
Aaron Ballman629afae2014-03-07 19:56:05 +00003736 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003737 if (!MemRecord->isAnonymousStructOrUnion() &&
3738 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00003739 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003740 if (getLangOpts().MicrosoftExt)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003741 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3742 << (int)Record->isUnion();
3743 else {
3744 // This is a nested type declaration.
3745 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3746 << (int)Record->isUnion();
3747 Invalid = true;
3748 }
Richard Smith254d2662013-01-28 00:54:05 +00003749 } else {
3750 // This is an anonymous type definition within another anonymous type.
3751 // This is a popular extension, provided by Plan9, MSVC and GCC, but
3752 // not part of standard C++.
3753 Diag(MemRecord->getLocation(),
Richard Smithd2029242013-01-31 03:11:12 +00003754 diag::ext_anonymous_record_with_anonymous_type)
3755 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003756 }
Aaron Ballman629afae2014-03-07 19:56:05 +00003757 } else if (isa<AccessSpecDecl>(Mem)) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00003758 // Any access specifier is fine.
Aaron Ballmanf93ef4e2014-06-24 16:22:41 +00003759 } else if (isa<StaticAssertDecl>(Mem)) {
3760 // In C++1z, static_assert declarations are also fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00003761 } else {
3762 // We have something that isn't a non-static data
3763 // member. Complain about it.
3764 unsigned DK = diag::err_anonymous_record_bad_member;
Aaron Ballman629afae2014-03-07 19:56:05 +00003765 if (isa<TypeDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003766 DK = diag::err_anonymous_record_with_type;
Aaron Ballman629afae2014-03-07 19:56:05 +00003767 else if (isa<FunctionDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003768 DK = diag::err_anonymous_record_with_function;
Aaron Ballman629afae2014-03-07 19:56:05 +00003769 else if (isa<VarDecl>(Mem))
Douglas Gregorf4d33272009-01-07 19:46:03 +00003770 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003771
3772 // Visual C++ allows type definition in anonymous struct or union.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003773 if (getLangOpts().MicrosoftExt &&
Francois Pichet4ad4b582010-09-08 11:32:25 +00003774 DK == diag::err_anonymous_record_with_type)
Aaron Ballman629afae2014-03-07 19:56:05 +00003775 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003776 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00003777 else {
Aaron Ballman629afae2014-03-07 19:56:05 +00003778 Diag(Mem->getLocation(), DK)
Francois Pichet4ad4b582010-09-08 11:32:25 +00003779 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003780 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00003781 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003782 }
3783 }
Richard Smithab44d5b2013-12-10 08:25:00 +00003784
3785 // C++11 [class.union]p8 (DR1460):
3786 // At most one variant member of a union may have a
3787 // brace-or-equal-initializer.
3788 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3789 Owner->isRecord())
3790 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3791 cast<CXXRecordDecl>(Record));
Mike Stump11289f42009-09-09 15:08:12 +00003792 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003793
3794 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003795 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003796 << (int)getLangOpts().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003797 Invalid = true;
3798 }
3799
John McCallfa2d6922009-10-22 23:31:08 +00003800 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00003801 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00003802 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00003803 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00003804
Mike Stump11289f42009-09-09 15:08:12 +00003805 // Create a declaration for this anonymous struct/union.
Craig Topperc3ec1492014-05-26 06:22:03 +00003806 NamedDecl *Anon = nullptr;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003807 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003808 Anon = FieldDecl::Create(Context, OwningClass,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003809 DS.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003810 Record->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003811 /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003812 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00003813 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00003814 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003815 /*InitStyle=*/ICIS_NoInit);
John McCallb54367d2010-05-21 20:45:30 +00003816 Anon->setAccess(AS);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003817 if (getLangOpts().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00003818 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003819 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00003820 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00003821 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003822 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003823 // mutable can only appear on non-static class members, so it's always
3824 // an error here
3825 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3826 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00003827 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003828 }
3829
Abramo Bagnaradff19302011-03-08 08:55:46 +00003830 Anon = VarDecl::Create(Context, Owner,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003831 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003832 Record->getLocation(), /*IdentifierInfo=*/nullptr,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00003833 Context.getTypeDeclType(Record),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003834 TInfo, SC);
Richard Smith40372352011-09-18 00:06:34 +00003835
3836 // Default-initialize the implicit variable. This initialization will be
3837 // trivial in almost all cases, except if a union member has an in-class
3838 // initializer:
3839 // union { int n = 0; };
3840 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003841 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00003842 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003843
Richard Smithab44d5b2013-12-10 08:25:00 +00003844 // Mark this as an anonymous struct/union type.
3845 Record->setAnonymousStructOrUnion(true);
3846
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003847 // Add the anonymous struct/union object to the current
3848 // context. We'll be referencing this object when we refer to one of
3849 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003850 Owner->addDecl(Anon);
Richard Smithab44d5b2013-12-10 08:25:00 +00003851
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003852 // Inject the members of the anonymous struct/union into the owning
3853 // context and into the identifier resolver chain for name lookup
3854 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003855 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet783dd6e2010-11-21 06:08:52 +00003856 Chain.push_back(Anon);
3857
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003858 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3859 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003860 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003861
David Majnemer2206bf52014-03-05 08:57:59 +00003862 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3863 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3864 Decl *ManglingContextDecl;
3865 if (MangleNumberingContext *MCtx =
3866 getCurrentMangleNumberContext(NewVD->getDeclContext(),
3867 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00003868 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00003869 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3870 }
3871 }
3872 }
3873
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003874 if (Invalid)
3875 Anon->setInvalidDecl();
3876
John McCall48871652010-08-21 09:40:31 +00003877 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00003878}
3879
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003880/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3881/// Microsoft C anonymous structure.
3882/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3883/// Example:
3884///
3885/// struct A { int a; };
3886/// struct B { struct A; int b; };
3887///
3888/// void foo() {
3889/// B var;
3890/// var.a = 3;
3891/// }
3892///
3893Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3894 RecordDecl *Record) {
3895
3896 // If there is no Record, get the record via the typedef.
3897 if (!Record)
3898 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3899
3900 // Mock up a declarator.
3901 Declarator Dc(DS, Declarator::TypeNameContext);
3902 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3903 assert(TInfo && "couldn't build declarator info for anonymous struct");
3904
3905 // Create a declaration for this anonymous struct.
Craig Topperc3ec1492014-05-26 06:22:03 +00003906 NamedDecl *Anon = FieldDecl::Create(Context,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003907 cast<RecordDecl>(CurContext),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003908 DS.getLocStart(),
3909 DS.getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003910 /*IdentifierInfo=*/nullptr,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003911 Context.getTypeDeclType(Record),
3912 TInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00003913 /*BitWidth=*/nullptr, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003914 /*InitStyle=*/ICIS_NoInit);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003915 Anon->setImplicit();
3916
3917 // Add the anonymous struct object to the current context.
3918 CurContext->addDecl(Anon);
3919
3920 // Inject the members of the anonymous struct into the current
3921 // context and into the identifier resolver chain for name lookup
3922 // purposes.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003923 SmallVector<NamedDecl*, 2> Chain;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003924 Chain.push_back(Anon);
3925
Nico Weberf8bb3de2012-02-01 00:41:00 +00003926 RecordDecl *RecordDef = Record->getDefinition();
3927 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3928 RecordDef, AS_none,
3929 Chain, true))
Francois Pichet0c71f6c2010-11-23 06:07:27 +00003930 Anon->setInvalidDecl();
3931
3932 return Anon;
3933}
Steve Naroff2fea1392007-09-02 02:04:30 +00003934
Douglas Gregor92751d42008-11-17 22:58:34 +00003935/// GetNameForDeclarator - Determine the full declaration name for the
3936/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003937DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00003938 return GetNameFromUnqualifiedId(D.getName());
3939}
3940
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003941/// \brief Retrieves the declaration name from a parsed unqualified-id.
3942DeclarationNameInfo
3943Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3944 DeclarationNameInfo NameInfo;
3945 NameInfo.setLoc(Name.StartLocation);
3946
Douglas Gregor7861a802009-11-03 01:35:08 +00003947 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00003948
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00003949 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003950 case UnqualifiedId::IK_Identifier:
3951 NameInfo.setName(Name.Identifier);
3952 NameInfo.setLoc(Name.StartLocation);
3953 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00003954
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003955 case UnqualifiedId::IK_OperatorFunctionId:
3956 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3957 Name.OperatorFunctionId.Operator));
3958 NameInfo.setLoc(Name.StartLocation);
3959 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3960 = Name.OperatorFunctionId.SymbolLocations[0];
3961 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3962 = Name.EndLocation.getRawEncoding();
3963 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003964
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003965 case UnqualifiedId::IK_LiteralOperatorId:
3966 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3967 Name.Identifier));
3968 NameInfo.setLoc(Name.StartLocation);
3969 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3970 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003971
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003972 case UnqualifiedId::IK_ConversionFunctionId: {
3973 TypeSourceInfo *TInfo;
3974 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3975 if (Ty.isNull())
3976 return DeclarationNameInfo();
3977 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3978 Context.getCanonicalType(Ty)));
3979 NameInfo.setLoc(Name.StartLocation);
3980 NameInfo.setNamedTypeInfo(TInfo);
3981 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00003982 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003983
3984 case UnqualifiedId::IK_ConstructorName: {
3985 TypeSourceInfo *TInfo;
3986 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3987 if (Ty.isNull())
3988 return DeclarationNameInfo();
3989 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3990 Context.getCanonicalType(Ty)));
3991 NameInfo.setLoc(Name.StartLocation);
3992 NameInfo.setNamedTypeInfo(TInfo);
3993 return NameInfo;
3994 }
3995
3996 case UnqualifiedId::IK_ConstructorTemplateId: {
3997 // In well-formed code, we can only have a constructor
3998 // template-id that refers to the current context, so go there
3999 // to find the actual type being constructed.
4000 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4001 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4002 return DeclarationNameInfo();
4003
4004 // Determine the type of the class being constructed.
4005 QualType CurClassType = Context.getTypeDeclType(CurClass);
4006
4007 // FIXME: Check two things: that the template-id names the same type as
4008 // CurClassType, and that the template-id does not occur when the name
4009 // was qualified.
4010
4011 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4012 Context.getCanonicalType(CurClassType)));
4013 NameInfo.setLoc(Name.StartLocation);
4014 // FIXME: should we retrieve TypeSourceInfo?
Craig Topperc3ec1492014-05-26 06:22:03 +00004015 NameInfo.setNamedTypeInfo(nullptr);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004016 return NameInfo;
4017 }
4018
4019 case UnqualifiedId::IK_DestructorName: {
4020 TypeSourceInfo *TInfo;
4021 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4022 if (Ty.isNull())
4023 return DeclarationNameInfo();
4024 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4025 Context.getCanonicalType(Ty)));
4026 NameInfo.setLoc(Name.StartLocation);
4027 NameInfo.setNamedTypeInfo(TInfo);
4028 return NameInfo;
4029 }
4030
4031 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00004032 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004033 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4034 return Context.getNameForTemplate(TName, TNameLoc);
4035 }
4036
4037 } // switch (Name.getKind())
4038
David Blaikie83d382b2011-09-23 05:06:16 +00004039 llvm_unreachable("Unknown name kind");
Douglas Gregor92751d42008-11-17 22:58:34 +00004040}
4041
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004042static QualType getCoreType(QualType Ty) {
4043 do {
4044 if (Ty->isPointerType() || Ty->isReferenceType())
4045 Ty = Ty->getPointeeType();
4046 else if (Ty->isArrayType())
4047 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4048 else
4049 return Ty.withoutLocalFastQualifiers();
4050 } while (true);
4051}
4052
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00004053/// hasSimilarParameters - Determine whether the C++ functions Declaration
4054/// and Definition have "nearly" matching parameters. This heuristic is
4055/// used to improve diagnostics in the case where an out-of-line function
4056/// definition doesn't match any declaration within the class or namespace.
4057/// Also sets Params to the list of indices to the parameters that differ
4058/// between the declaration and the definition. If hasSimilarParameters
4059/// returns true and Params is empty, then all of the parameters match.
4060static bool hasSimilarParameters(ASTContext &Context,
Douglas Gregor8af63e42009-02-06 17:46:57 +00004061 FunctionDecl *Declaration,
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004062 FunctionDecl *Definition,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004063 SmallVectorImpl<unsigned> &Params) {
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004064 Params.clear();
Douglas Gregorad590502008-12-15 23:53:10 +00004065 if (Declaration->param_size() != Definition->param_size())
4066 return false;
4067 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4068 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4069 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4070
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004071 // The parameter types are identical
Matt Beaumont-Gay56381b82011-08-23 01:35:51 +00004072 if (Context.hasSameType(DefParamTy, DeclParamTy))
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00004073 continue;
4074
4075 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4076 QualType DefParamBaseTy = getCoreType(DefParamTy);
4077 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4078 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4079
4080 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4081 (DeclTyName && DeclTyName == DefTyName))
4082 Params.push_back(Idx);
4083 else // The two parameters aren't even close
Douglas Gregorad590502008-12-15 23:53:10 +00004084 return false;
4085 }
4086
4087 return true;
4088}
4089
John McCall99b2fe52010-04-29 23:50:39 +00004090/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4091/// declarator needs to be rebuilt in the current instantiation.
4092/// Any bits of declarator which appear before the name are valid for
4093/// consideration here. That's specifically the type in the decl spec
4094/// and the base type in any member-pointer chunks.
4095static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4096 DeclarationName Name) {
4097 // The types we specifically need to rebuild are:
4098 // - typenames, typeofs, and decltypes
4099 // - types which will become injected class names
4100 // Of course, we also need to rebuild any type referencing such a
4101 // type. It's safest to just say "dependent", but we call out a
4102 // few cases here.
4103
4104 DeclSpec &DS = D.getMutableDeclSpec();
4105 switch (DS.getTypeSpecType()) {
4106 case DeclSpec::TST_typename:
4107 case DeclSpec::TST_typeofType:
Eli Friedman0dfb8892011-10-06 23:00:33 +00004108 case DeclSpec::TST_underlyingType:
4109 case DeclSpec::TST_atomic: {
John McCall99b2fe52010-04-29 23:50:39 +00004110 // Grab the type from the parser.
Craig Topperc3ec1492014-05-26 06:22:03 +00004111 TypeSourceInfo *TSI = nullptr;
John McCallba7bf592010-08-24 05:47:05 +00004112 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00004113 if (T.isNull() || !T->isDependentType()) break;
4114
4115 // Make sure there's a type source info. This isn't really much
4116 // of a waste; most dependent types should have type source info
4117 // attached already.
4118 if (!TSI)
4119 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4120
4121 // Rebuild the type in the current instantiation.
4122 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4123 if (!TSI) return true;
4124
4125 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00004126 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4127 DS.UpdateTypeRep(LocType);
4128 break;
4129 }
4130
Richard Smith1620ebd2012-10-01 20:35:07 +00004131 case DeclSpec::TST_decltype:
John McCallba7bf592010-08-24 05:47:05 +00004132 case DeclSpec::TST_typeofExpr: {
4133 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00004134 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00004135 if (Result.isInvalid()) return true;
4136 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00004137 break;
4138 }
4139
4140 default:
4141 // Nothing to do for these decl specs.
4142 break;
4143 }
4144
4145 // It doesn't matter what order we do this in.
4146 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4147 DeclaratorChunk &Chunk = D.getTypeObject(I);
4148
4149 // The only type information in the declarator which can come
4150 // before the declaration name is the base type of a member
4151 // pointer.
4152 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4153 continue;
4154
4155 // Rebuild the scope specifier in-place.
4156 CXXScopeSpec &SS = Chunk.Mem.Scope();
4157 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4158 return true;
4159 }
4160
4161 return false;
4162}
4163
Anders Carlsson1052fd72011-07-04 16:28:17 +00004164Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00004165 D.setFunctionDefinitionKind(FDK_Declaration);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004166 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004167
4168 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Douglas Gregor205b0682012-04-30 18:13:01 +00004169 Dcl && Dcl->getDeclContext()->isFileContext())
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004170 Dcl->setTopLevelDeclInObjCContainer();
4171
4172 return Dcl;
John McCallde6836a2010-08-24 07:21:54 +00004173}
4174
Richard Smithdda56e42011-04-15 14:24:37 +00004175/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4176/// If T is the name of a class, then each of the following shall have a
4177/// name different from T:
4178/// - every static data member of class T;
4179/// - every member function of class T
4180/// - every member of class T that is itself a type;
4181/// \returns true if the declaration name violates these rules.
4182bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4183 DeclarationNameInfo NameInfo) {
4184 DeclarationName Name = NameInfo.getName();
4185
4186 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4187 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4188 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4189 return true;
4190 }
4191
4192 return false;
4193}
Douglas Gregor31feb332012-03-17 23:06:31 +00004194
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004195/// \brief Diagnose a declaration whose declarator-id has the given
4196/// nested-name-specifier.
4197///
4198/// \param SS The nested-name-specifier of the declarator-id.
4199///
4200/// \param DC The declaration context to which the nested-name-specifier
4201/// resolves.
4202///
4203/// \param Name The name of the entity being declared.
4204///
4205/// \param Loc The location of the name of the entity being declared.
Douglas Gregor31feb332012-03-17 23:06:31 +00004206///
4207/// \returns true if we cannot safely recover from this error, false otherwise.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004208bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
Douglas Gregor31feb332012-03-17 23:06:31 +00004209 DeclarationName Name,
Richard Smitha2302242013-12-05 07:51:02 +00004210 SourceLocation Loc) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004211 DeclContext *Cur = CurContext;
Eli Friedmane2358c12013-08-12 21:54:01 +00004212 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004213 Cur = Cur->getParent();
Richard Smitha2302242013-12-05 07:51:02 +00004214
4215 // If the user provided a superfluous scope specifier that refers back to the
4216 // class in which the entity is already declared, diagnose and ignore it.
Douglas Gregor31feb332012-03-17 23:06:31 +00004217 //
4218 // class X {
4219 // void X::f();
4220 // };
Richard Smitha2302242013-12-05 07:51:02 +00004221 //
4222 // Note, it was once ill-formed to give redundant qualification in all
4223 // contexts, but that rule was removed by DR482.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004224 if (Cur->Equals(DC)) {
Richard Smitha2302242013-12-05 07:51:02 +00004225 if (Cur->isRecord()) {
4226 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4227 : diag::err_member_extra_qualification)
4228 << Name << FixItHint::CreateRemoval(SS.getRange());
4229 SS.clear();
4230 } else {
4231 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4232 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004233 return false;
Richard Smitha2302242013-12-05 07:51:02 +00004234 }
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004235
4236 // Check whether the qualifying scope encloses the scope of the original
4237 // declaration.
4238 if (!Cur->Encloses(DC)) {
4239 if (Cur->isRecord())
4240 Diag(Loc, diag::err_member_qualification)
4241 << Name << SS.getRange();
4242 else if (isa<TranslationUnitDecl>(DC))
4243 Diag(Loc, diag::err_invalid_declarator_global_scope)
4244 << Name << SS.getRange();
4245 else if (isa<FunctionDecl>(Cur))
4246 Diag(Loc, diag::err_invalid_declarator_in_function)
4247 << Name << SS.getRange();
Eli Friedmane2358c12013-08-12 21:54:01 +00004248 else if (isa<BlockDecl>(Cur))
4249 Diag(Loc, diag::err_invalid_declarator_in_block)
4250 << Name << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004251 else
4252 Diag(Loc, diag::err_invalid_declarator_scope)
Richard Smith82269842012-04-13 04:07:40 +00004253 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004254
Douglas Gregor31feb332012-03-17 23:06:31 +00004255 return true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004256 }
4257
4258 if (Cur->isRecord()) {
4259 // Cannot qualify members within a class.
4260 Diag(Loc, diag::err_member_qualification)
4261 << Name << SS.getRange();
4262 SS.clear();
4263
4264 // C++ constructors and destructors with incorrect scopes can break
4265 // our AST invariants by having the wrong underlying types. If
4266 // that's the case, then drop this declaration entirely.
4267 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4268 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4269 !Context.hasSameType(Name.getCXXNameType(),
4270 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4271 return true;
4272
4273 return false;
4274 }
Douglas Gregor31feb332012-03-17 23:06:31 +00004275
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004276 // C++11 [dcl.meaning]p1:
4277 // [...] "The nested-name-specifier of the qualified declarator-id shall
4278 // not begin with a decltype-specifer"
4279 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4280 while (SpecLoc.getPrefix())
4281 SpecLoc = SpecLoc.getPrefix();
4282 if (dyn_cast_or_null<DecltypeType>(
4283 SpecLoc.getNestedNameSpecifier()->getAsType()))
4284 Diag(Loc, diag::err_decltype_in_declarator)
4285 << SpecLoc.getTypeLoc().getSourceRange();
4286
Douglas Gregor31feb332012-03-17 23:06:31 +00004287 return false;
4288}
4289
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00004290NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4291 MultiTemplateParamsArg TemplateParamLists) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004292 // TODO: consider using NameInfo for diagnostic.
4293 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4294 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00004295
Chris Lattner02c04392007-07-25 00:24:17 +00004296 // All of these full declarators require an identifier. If it doesn't have
4297 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00004298 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004299 if (!D.isInvalidType()) // Reject this if we think it is valid.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004300 Diag(D.getDeclSpec().getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004301 diag::err_declarator_need_ident)
4302 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004303 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00004304 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
Craig Topperc3ec1492014-05-26 06:22:03 +00004305 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004306
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004307 // The scope passed in may not be a decl scope. Zip up the scope tree until
4308 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00004309 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00004310 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00004311 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004312
John McCall99b2fe52010-04-29 23:50:39 +00004313 DeclContext *DC = CurContext;
4314 if (D.getCXXScopeSpec().isInvalid())
4315 D.setInvalidType();
4316 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00004317 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4318 UPPC_DeclarationQualifier))
Craig Topperc3ec1492014-05-26 06:22:03 +00004319 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +00004320
John McCall99b2fe52010-04-29 23:50:39 +00004321 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4322 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
Richard Smith8ac1c922013-11-25 21:30:29 +00004323 if (!DC || isa<EnumDecl>(DC)) {
John McCall99b2fe52010-04-29 23:50:39 +00004324 // If we could not compute the declaration context, it's because the
4325 // declaration context is dependent but does not refer to a class,
4326 // class template, or class template partial specialization. Complain
4327 // and return early, to avoid the coming semantic disaster.
4328 Diag(D.getIdentifierLoc(),
4329 diag::err_template_qualified_declarator_no_match)
Aaron Ballman4a979672014-01-03 13:56:08 +00004330 << D.getCXXScopeSpec().getScopeRep()
John McCall99b2fe52010-04-29 23:50:39 +00004331 << D.getCXXScopeSpec().getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004332 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004333 }
John McCall99b2fe52010-04-29 23:50:39 +00004334 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00004335
John McCall99b2fe52010-04-29 23:50:39 +00004336 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00004337 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00004338 return nullptr;
John McCall99b2fe52010-04-29 23:50:39 +00004339
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004340 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4341 Diag(D.getIdentifierLoc(),
4342 diag::err_member_def_undefined_record)
4343 << Name << DC << D.getCXXScopeSpec().getRange();
4344 D.setInvalidType();
4345 } else if (!D.getDeclSpec().isFriendSpecified()) {
4346 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4347 Name, D.getIdentifierLoc())) {
4348 if (DC->isRecord())
Craig Topperc3ec1492014-05-26 06:22:03 +00004349 return nullptr;
4350
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004351 D.setInvalidType();
Douglas Gregora007d362010-10-13 22:19:53 +00004352 }
John McCall99b2fe52010-04-29 23:50:39 +00004353 }
4354
4355 // Check whether we need to rebuild the type of the given
4356 // declaration in the current instantiation.
4357 if (EnteringContext && IsDependentContext &&
4358 TemplateParamLists.size() != 0) {
4359 ContextRAII SavedContext(*this, DC);
4360 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4361 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00004362 }
4363 }
Richard Smithdda56e42011-04-15 14:24:37 +00004364
4365 if (DiagnoseClassNameShadow(DC, NameInfo))
4366 // If this is a typedef, we'll end up spewing multiple diagnostics.
4367 // Just return early; it's safer.
4368 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Craig Topperc3ec1492014-05-26 06:22:03 +00004369 return nullptr;
4370
John McCall8cb7bdf2010-06-04 23:28:52 +00004371 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4372 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00004373
Douglas Gregor506bd562010-12-13 22:49:22 +00004374 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4375 UPPC_DeclarationType))
4376 D.setInvalidType();
4377
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004378 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00004379 ForRedeclaration);
4380
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004381 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00004382 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00004383 bool IsLinkageLookup = false;
Richard Smith1c34fb72013-08-13 18:18:50 +00004384 bool CreateBuiltins = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00004385
4386 // If the declaration we're planning to build will be a function
4387 // or object with linkage, then look for another declaration with
4388 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
Richard Smith1c34fb72013-08-13 18:18:50 +00004389 //
4390 // If the declaration we're planning to build will be declared with
4391 // external linkage in the translation unit, create any builtin with
4392 // the same name.
Douglas Gregoreddf4332009-02-24 20:03:32 +00004393 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4394 /* Do nothing*/;
Richard Smith1c34fb72013-08-13 18:18:50 +00004395 else if (CurContext->isFunctionOrMethod() &&
4396 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4397 R->isFunctionType())) {
John McCall1f82f242009-11-18 22:49:29 +00004398 IsLinkageLookup = true;
Richard Smith1c34fb72013-08-13 18:18:50 +00004399 CreateBuiltins =
4400 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4401 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4402 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4403 CreateBuiltins = true;
John McCall1f82f242009-11-18 22:49:29 +00004404
4405 if (IsLinkageLookup)
4406 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004407
Richard Smith1c34fb72013-08-13 18:18:50 +00004408 LookupName(Previous, S, CreateBuiltins);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004409 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00004410 LookupQualifiedName(Previous, DC);
4411
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004412 // C++ [dcl.meaning]p1:
4413 // When the declarator-id is qualified, the declaration shall refer to a
4414 // previously declared member of the class or namespace to which the
4415 // qualifier refers (or, in the case of a namespace, of an element of the
4416 // inline namespace set of that namespace (7.3.1)) or to a specialization
4417 // thereof; [...]
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004418 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004419 // Note that we already checked the context above, and that we do not have
4420 // enough information to make sure that Previous contains the declaration
4421 // we want to match. For example, given:
Douglas Gregorad590502008-12-15 23:53:10 +00004422 //
Douglas Gregor4287b372008-12-12 08:25:50 +00004423 // class X {
4424 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00004425 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00004426 // };
4427 //
Douglas Gregorad590502008-12-15 23:53:10 +00004428 // void X::f(int) { } // ill-formed
4429 //
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004430 // In this case, Previous will point to the overload set
Douglas Gregorad590502008-12-15 23:53:10 +00004431 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00004432 // matches.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00004433
4434 // C++ [dcl.meaning]p1:
4435 // [...] the member shall not merely have been introduced by a
4436 // using-declaration in the scope of the class or namespace nominated by
4437 // the nested-name-specifier of the declarator-id.
4438 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00004439 }
4440
John McCall1f82f242009-11-18 22:49:29 +00004441 if (Previous.isSingleResult() &&
4442 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00004443 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004444 if (!D.isInvalidType())
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00004445 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4446 Previous.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004447
Douglas Gregor5101c242008-12-05 18:15:24 +00004448 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00004449 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00004450 }
4451
Douglas Gregor83a586e2008-04-13 21:07:44 +00004452 // In C++, the previous declaration we find might be a tag type
4453 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00004454 // tag type. Note that this does does not apply if we're declaring a
4455 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00004456 if (Previous.isSingleTagDecl() &&
Kaelyn Uhrain5dfc94b2013-12-16 19:25:47 +00004457 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00004458 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00004459
Richard Smith5afcdf3f2013-03-06 01:37:38 +00004460 // Check that there are no default arguments other than in the parameters
4461 // of a function declaration (C++ only).
4462 if (getLangOpts().CPlusPlus)
4463 CheckExtraCXXDefaultArguments(D);
4464
Nico Webercb4c7f42012-12-23 00:40:46 +00004465 NamedDecl *New;
4466
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004467 bool AddToScope = true;
Chris Lattner01a7c532007-01-25 23:09:03 +00004468 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004469 if (TemplateParamLists.size()) {
4470 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
Craig Topperc3ec1492014-05-26 06:22:03 +00004471 return nullptr;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004472 }
Mike Stump11289f42009-09-09 15:08:12 +00004473
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004474 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
Douglas Gregoreddf4332009-02-24 20:03:32 +00004475 } else if (R->isFunctionType()) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004476 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004477 TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004478 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004479 } else {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004480 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4481 AddToScope);
Chris Lattner01a7c532007-01-25 23:09:03 +00004482 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004483
Craig Topperc3ec1492014-05-26 06:22:03 +00004484 if (!New)
4485 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004487 // If this has an identifier and is not an invalid redeclaration or
4488 // function template specialization, add it to the scope stack.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004489 if (New->getDeclName() && AddToScope &&
Richard Smith541b38b2013-09-20 01:15:31 +00004490 !(D.isRedeclaration() && New->isInvalidDecl())) {
4491 // Only make a locally-scoped extern declaration visible if it is the first
4492 // declaration of this entity. Qualified lookup for such an entity should
4493 // only find this declaration if there is no visible declaration of it.
4494 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4495 PushOnScopeChains(New, S, AddToContext);
4496 if (!AddToContext)
4497 CurContext->addHiddenDecl(New);
4498 }
Mike Stump11289f42009-09-09 15:08:12 +00004499
John McCall48871652010-08-21 09:40:31 +00004500 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00004501}
4502
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004503/// Helper method to turn variable array types into constant array
4504/// types in certain situations which would otherwise be errors (for
4505/// GCC compatibility).
Eli Friedmana3b1d032009-02-21 00:44:51 +00004506static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4507 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004508 bool &SizeIsNegative,
4509 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004510 // This method tries to turn a variable array into a constant
4511 // array even when the size isn't an ICE. This is necessary
4512 // for compatibility with code that depends on gcc's buggy
4513 // constant expression folding, like struct {char x[(int)(char*)2];}
4514 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004515 Oversized = 0;
4516
4517 if (T->isDependentType())
4518 return QualType();
4519
John McCall8ccfcb52009-09-24 19:53:00 +00004520 QualifierCollector Qs;
4521 const Type *Ty = Qs.strip(T);
4522
4523 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004524 QualType Pointee = PTy->getPointeeType();
4525 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004526 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4527 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004528 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00004529 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00004530 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004531 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004532 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4533 QualType Inner = PTy->getInnerType();
4534 QualType FixedType =
4535 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4536 Oversized);
4537 if (FixedType.isNull()) return FixedType;
4538 FixedType = Context.getParenType(FixedType);
4539 return Qs.apply(Context, FixedType);
4540 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004541
4542 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00004543 if (!VLATy)
4544 return QualType();
4545 // FIXME: We should probably handle this case
4546 if (VLATy->getElementType()->isVariablyModifiedType())
4547 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004548
Richard Smith42d3af92011-12-07 00:43:50 +00004549 llvm::APSInt Res;
Eli Friedmana3b1d032009-02-21 00:44:51 +00004550 if (!VLATy->getSizeExpr() ||
Richard Smith42d3af92011-12-07 00:43:50 +00004551 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
Eli Friedmana3b1d032009-02-21 00:44:51 +00004552 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00004553
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004554 // Check whether the array size is negative.
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004555 if (Res.isSigned() && Res.isNegative()) {
4556 SizeIsNegative = true;
4557 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00004558 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00004559
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004560 // Check whether the array is too large to be addressed.
4561 unsigned ActiveSizeBits
4562 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4563 Res);
4564 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4565 Oversized = Res;
4566 return QualType();
4567 }
4568
4569 return Context.getConstantArrayType(VLATy->getElementType(),
4570 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004571}
4572
Abramo Bagnara341ab732012-11-08 14:44:42 +00004573static void
4574FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
David Blaikie6adc78e2013-02-18 22:06:02 +00004575 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4576 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4577 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4578 DstPTL.getPointeeLoc());
4579 DstPTL.setStarLoc(SrcPTL.getStarLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004580 return;
4581 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004582 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4583 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4584 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4585 DstPTL.getInnerLoc());
4586 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4587 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004588 return;
4589 }
David Blaikie6adc78e2013-02-18 22:06:02 +00004590 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4591 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4592 TypeLoc SrcElemTL = SrcATL.getElementLoc();
4593 TypeLoc DstElemTL = DstATL.getElementLoc();
Abramo Bagnara341ab732012-11-08 14:44:42 +00004594 DstElemTL.initializeFullCopy(SrcElemTL);
David Blaikie6adc78e2013-02-18 22:06:02 +00004595 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4596 DstATL.setSizeExpr(SrcATL.getSizeExpr());
4597 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
Abramo Bagnara341ab732012-11-08 14:44:42 +00004598}
4599
Abramo Bagnaraad9f2e22012-11-08 16:27:30 +00004600/// Helper method to turn variable array types into constant array
4601/// types in certain situations which would otherwise be errors (for
4602/// GCC compatibility).
Abramo Bagnara341ab732012-11-08 14:44:42 +00004603static TypeSourceInfo*
4604TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4605 ASTContext &Context,
4606 bool &SizeIsNegative,
4607 llvm::APSInt &Oversized) {
4608 QualType FixedTy
4609 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4610 SizeIsNegative, Oversized);
4611 if (FixedTy.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00004612 return nullptr;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004613 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4614 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4615 FixedTInfo->getTypeLoc());
4616 return FixedTInfo;
4617}
4618
Richard Smith78165b52013-01-10 23:43:47 +00004619/// \brief Register the given locally-scoped extern "C" declaration so
Richard Smith39b79682013-06-18 20:15:12 +00004620/// that it can be found later for redeclarations. We include any extern "C"
4621/// declaration that is not visible in the translation unit here, not just
4622/// function-scope declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004623void
Richard Smith39b79682013-06-18 20:15:12 +00004624Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
Richard Smithac974a32013-06-30 09:48:50 +00004625 if (!getLangOpts().CPlusPlus &&
4626 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4627 // Don't need to track declarations in the TU in C.
4628 return;
4629
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004630 // Note that we have a locally-scoped external with this name.
Richard Smithac974a32013-06-30 09:48:50 +00004631 // FIXME: There can be multiple such declarations if they are functions marked
4632 // __attribute__((overloadable)) declared in function scope in C.
Richard Smith78165b52013-01-10 23:43:47 +00004633 LocallyScopedExternCDecls[ND->getDeclName()] = ND;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004634}
4635
Richard Smith39b79682013-06-18 20:15:12 +00004636NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
Douglas Gregordc5c9582011-07-28 14:20:37 +00004637 if (ExternalSource) {
4638 // Load locally-scoped external decls from the external source.
Richard Smith39b79682013-06-18 20:15:12 +00004639 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
Douglas Gregordc5c9582011-07-28 14:20:37 +00004640 SmallVector<NamedDecl *, 4> Decls;
Richard Smith78165b52013-01-10 23:43:47 +00004641 ExternalSource->ReadLocallyScopedExternCDecls(Decls);
Douglas Gregordc5c9582011-07-28 14:20:37 +00004642 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4643 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Richard Smith78165b52013-01-10 23:43:47 +00004644 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4645 if (Pos == LocallyScopedExternCDecls.end())
4646 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
Douglas Gregordc5c9582011-07-28 14:20:37 +00004647 }
4648 }
Richard Smith39b79682013-06-18 20:15:12 +00004649
4650 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00004651 return D ? D->getMostRecentDecl() : nullptr;
Douglas Gregordc5c9582011-07-28 14:20:37 +00004652}
4653
Eli Friedman574c7452009-04-07 19:37:57 +00004654/// \brief Diagnose function specifiers on a declaration of an identifier that
4655/// does not identify a function.
Richard Smithb1402ae2013-03-18 22:52:47 +00004656void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
Eli Friedman574c7452009-04-07 19:37:57 +00004657 // FIXME: We should probably indicate the identifier in question to avoid
4658 // confusion for constructs like "inline int a(), b;"
Richard Smithb1402ae2013-03-18 22:52:47 +00004659 if (DS.isInlineSpecified())
4660 Diag(DS.getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004661 diag::err_inline_non_function);
4662
Richard Smithb1402ae2013-03-18 22:52:47 +00004663 if (DS.isVirtualSpecified())
4664 Diag(DS.getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004665 diag::err_virtual_non_function);
4666
Richard Smithb1402ae2013-03-18 22:52:47 +00004667 if (DS.isExplicitSpecified())
4668 Diag(DS.getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00004669 diag::err_explicit_non_function);
Richard Smith0015f092013-01-17 22:16:11 +00004670
Richard Smithb1402ae2013-03-18 22:52:47 +00004671 if (DS.isNoreturnSpecified())
4672 Diag(DS.getNoreturnSpecLoc(),
Richard Smith0015f092013-01-17 22:16:11 +00004673 diag::err_noreturn_non_function);
Eli Friedman574c7452009-04-07 19:37:57 +00004674}
4675
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004676NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004677Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004678 TypeSourceInfo *TInfo, LookupResult &Previous) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004679 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4680 if (D.getCXXScopeSpec().isSet()) {
4681 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4682 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004683 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004684 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00004685 DC = CurContext;
4686 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004687 }
4688
Richard Smithb1402ae2013-03-18 22:52:47 +00004689 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +00004690
Richard Smitha77a0a62011-08-15 21:04:07 +00004691 if (D.getDeclSpec().isConstexprSpecified())
4692 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4693 << 1;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004694
Douglas Gregord8f446f2010-07-13 06:37:01 +00004695 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4696 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4697 << D.getName().getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00004698 return nullptr;
Douglas Gregord8f446f2010-07-13 06:37:01 +00004699 }
4700
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004701 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
Craig Topperc3ec1492014-05-26 06:22:03 +00004702 if (!NewTD) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004703
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004704 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00004705 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00004706
Richard Smith3f1b5d02011-05-05 21:57:07 +00004707 CheckTypedefForVariablyModifiedType(S, NewTD);
4708
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00004709 bool Redeclaration = D.isRedeclaration();
4710 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4711 D.setRedeclaration(Redeclaration);
4712 return ND;
Richard Smithdda56e42011-04-15 14:24:37 +00004713}
4714
Richard Smith3f1b5d02011-05-05 21:57:07 +00004715void
4716Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00004717 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4718 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00004719 // Note that variably modified types must be fixed before merging the decl so
4720 // that redeclarations will match.
Abramo Bagnara341ab732012-11-08 14:44:42 +00004721 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4722 QualType T = TInfo->getType();
Chris Lattner9fecd742009-04-19 05:21:20 +00004723 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00004724 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00004725
Craig Topperc3ec1492014-05-26 06:22:03 +00004726 if (S->getFnParent() == nullptr) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00004727 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004728 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00004729 TypeSourceInfo *FixedTInfo =
4730 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4731 SizeIsNegative,
4732 Oversized);
4733 if (FixedTInfo) {
Richard Smithdda56e42011-04-15 14:24:37 +00004734 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +00004735 NewTD->setTypeSourceInfo(FixedTInfo);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004736 } else {
4737 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00004738 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004739 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00004740 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00004741 else if (Oversized.getBoolValue())
David Blaikie30d15442011-10-19 22:56:21 +00004742 Diag(NewTD->getLocation(), diag::err_array_too_large)
4743 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00004744 else
Richard Smithdda56e42011-04-15 14:24:37 +00004745 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004746 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00004747 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004748 }
4749 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00004750}
Douglas Gregor27821ce2009-07-07 16:35:42 +00004751
Richard Smith3f1b5d02011-05-05 21:57:07 +00004752
4753/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4754/// declares a typedef-name, either using the 'typedef' type specifier or via
4755/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4756NamedDecl*
4757Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4758 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00004759 // Merge the decl with the existing one if appropriate. If the decl is
4760 // in an outer scope, it isn't the same thing.
Richard Smith72bcaec2013-12-05 04:30:04 +00004761 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4762 /*AllowInlineNamespace*/false);
Douglas Gregor3552dab2013-01-09 00:47:56 +00004763 filterNonConflictingPreviousDecls(Context, NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004764 if (!Previous.empty()) {
4765 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00004766 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00004767 }
4768
Douglas Gregor27821ce2009-07-07 16:35:42 +00004769 // If this is the C FILE type, notify the AST context.
4770 if (IdentifierInfo *II = NewTD->getIdentifier())
4771 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004772 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00004773 if (II->isStr("FILE"))
4774 Context.setFILEDecl(NewTD);
4775 else if (II->isStr("jmp_buf"))
4776 Context.setjmp_bufDecl(NewTD);
4777 else if (II->isStr("sigjmp_buf"))
4778 Context.setsigjmp_bufDecl(NewTD);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004779 else if (II->isStr("ucontext_t"))
4780 Context.setucontext_tDecl(NewTD);
Mike Stumpa4de80b2009-07-28 02:25:19 +00004781 }
4782
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00004783 return NewTD;
4784}
4785
Douglas Gregor5d68a202009-02-24 19:23:27 +00004786/// \brief Determines whether the given declaration is an out-of-scope
4787/// previous declaration.
4788///
4789/// This routine should be invoked when name lookup has found a
4790/// previous declaration (PrevDecl) that is not in the scope where a
4791/// new declaration by the same name is being introduced. If the new
4792/// declaration occurs in a local scope, previous declarations with
4793/// linkage may still be considered previous declarations (C99
4794/// 6.2.2p4-5, C++ [basic.link]p6).
4795///
4796/// \param PrevDecl the previous declaration found by name
4797/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00004798///
Douglas Gregor5d68a202009-02-24 19:23:27 +00004799/// \param DC the context in which the new declaration is being
4800/// declared.
4801///
4802/// \returns true if PrevDecl is an out-of-scope previous declaration
4803/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00004804static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00004805isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4806 ASTContext &Context) {
4807 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00004808 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004809
Douglas Gregoreddf4332009-02-24 20:03:32 +00004810 if (!PrevDecl->hasLinkage())
4811 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004812
David Blaikiebbafb8a2012-03-11 07:00:24 +00004813 if (Context.getLangOpts().CPlusPlus) {
Douglas Gregor5d68a202009-02-24 19:23:27 +00004814 // C++ [basic.link]p6:
4815 // If there is a visible declaration of an entity with linkage
4816 // having the same name and type, ignoring entities declared
4817 // outside the innermost enclosing namespace scope, the block
4818 // scope declaration declares that same entity and receives the
4819 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00004820 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00004821 if (!OuterContext->isFunctionOrMethod())
4822 // This rule only applies to block-scope declarations.
4823 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00004824
4825 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4826 if (PrevOuterContext->isRecord())
4827 // We found a member function: ignore it.
4828 return false;
4829
4830 // Find the innermost enclosing namespace for the new and
4831 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00004832 OuterContext = OuterContext->getEnclosingNamespaceContext();
4833 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregorfcee9462010-08-27 22:55:10 +00004835 // The previous declaration is in a different namespace, so it
4836 // isn't the same function.
4837 if (!OuterContext->Equals(PrevOuterContext))
4838 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00004839 }
4840
Douglas Gregor5d68a202009-02-24 19:23:27 +00004841 return true;
4842}
4843
John McCall3e11ebe2010-03-15 10:12:16 +00004844static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4845 CXXScopeSpec &SS = D.getCXXScopeSpec();
4846 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00004847 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00004848}
4849
John McCall31168b02011-06-15 23:02:42 +00004850bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4851 QualType type = decl->getType();
4852 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4853 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4854 // Various kinds of declaration aren't allowed to be __autoreleasing.
4855 unsigned kind = -1U;
4856 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4857 if (var->hasAttr<BlocksAttr>())
4858 kind = 0; // __block
4859 else if (!var->hasLocalStorage())
4860 kind = 1; // global
4861 } else if (isa<ObjCIvarDecl>(decl)) {
4862 kind = 3; // ivar
4863 } else if (isa<FieldDecl>(decl)) {
4864 kind = 2; // field
4865 }
4866
4867 if (kind != -1U) {
4868 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4869 << kind;
4870 }
4871 } else if (lifetime == Qualifiers::OCL_None) {
4872 // Try to infer lifetime.
4873 if (!type->isObjCLifetimeType())
4874 return false;
4875
4876 lifetime = type->getObjCARCImplicitLifetime();
4877 type = Context.getLifetimeQualifiedType(type, lifetime);
4878 decl->setType(type);
4879 }
4880
4881 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4882 // Thread-local variables cannot have lifetime.
4883 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
Richard Smithfd3834f2013-04-13 02:43:54 +00004884 var->getTLSKind()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004885 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00004886 << var->getType();
4887 return true;
4888 }
4889 }
4890
4891 return false;
4892}
4893
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004894static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00004895 // Ensure that an auto decl is deduced otherwise the checks below might cache
4896 // the wrong linkage.
4897 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4898
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004899 // 'weak' only applies to declarations with external linkage.
Rafael Espindolab3069002013-01-16 23:49:06 +00004900 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004901 if (!ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004902 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4903 ND.dropAttr<WeakAttr>();
4904 }
4905 }
4906 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00004907 if (ND.isExternallyVisible()) {
Rafael Espindolab3069002013-01-16 23:49:06 +00004908 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4909 ND.dropAttr<WeakRefAttr>();
4910 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004911 }
Reid Klecknerb144d362013-05-20 14:02:37 +00004912
4913 // 'selectany' only applies to externally visible varable declarations.
4914 // It does not apply to functions.
4915 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4916 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4917 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4918 ND.dropAttr<SelectAnyAttr>();
4919 }
4920 }
Nico Rieck8ca0bfc2014-03-31 14:56:58 +00004921
4922 // dll attributes require external linkage.
4923 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4924 if (!ND.isExternallyVisible()) {
4925 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4926 << &ND << Attr;
4927 ND.setInvalidDecl();
4928 }
4929 }
4930 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4931 if (!ND.isExternallyVisible()) {
4932 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4933 << &ND << Attr;
4934 ND.setInvalidDecl();
4935 }
4936 }
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00004937}
4938
Nico Rieck82f0b062014-03-31 14:56:15 +00004939static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4940 NamedDecl *NewDecl,
4941 bool IsSpecialization) {
4942 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4943 OldDecl = OldTD->getTemplatedDecl();
4944 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4945 NewDecl = NewTD->getTemplatedDecl();
4946
4947 if (!OldDecl || !NewDecl)
4948 return;
4949
4950 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4951 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4952 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4953 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4954
4955 // dllimport and dllexport are inheritable attributes so we have to exclude
4956 // inherited attribute instances.
4957 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4958 (NewExportAttr && !NewExportAttr->isInherited());
4959
4960 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4961 // the only exception being explicit specializations.
4962 // Implicitly generated declarations are also excluded for now because there
4963 // is no other way to switch these to use dllimport or dllexport.
4964 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4965 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4966 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4967 << NewDecl
4968 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4969 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4970 NewDecl->setInvalidDecl();
4971 return;
4972 }
4973
4974 // A redeclaration is not allowed to drop a dllimport attribute, the only
4975 // exception being inline function definitions.
Nico Rieck82f0b062014-03-31 14:56:15 +00004976 // NB: MSVC converts such a declaration to dllexport.
Nico Rieck078d2f82014-05-29 16:50:20 +00004977 bool IsInline = false, IsStaticDataMember = false;
4978 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
4979 // Ignore static data because out-of-line definitions are diagnosed
4980 // separately.
4981 IsStaticDataMember = VD->isStaticDataMember();
4982 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl))
4983 IsInline = FD->isInlined();
Hans Wennborgf436b282014-05-22 15:46:15 +00004984
Nico Rieck078d2f82014-05-29 16:50:20 +00004985 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember) {
Nico Rieck82f0b062014-03-31 14:56:15 +00004986 S.Diag(NewDecl->getLocation(),
4987 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4988 << NewDecl << OldImportAttr;
4989 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4990 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4991 OldDecl->dropAttr<DLLImportAttr>();
4992 NewDecl->dropAttr<DLLImportAttr>();
4993 }
4994}
4995
John McCallc87d9722013-04-02 02:48:58 +00004996/// Given that we are within the definition of the given function,
4997/// will that definition behave like C99's 'inline', where the
4998/// definition is discarded except for optimization purposes?
4999static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5000 // Try to avoid calling GetGVALinkageForFunction.
5001
5002 // All cases of this require the 'inline' keyword.
5003 if (!FD->isInlined()) return false;
5004
5005 // This is only possible in C++ with the gnu_inline attribute.
5006 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5007 return false;
5008
5009 // Okay, go ahead and call the relatively-more-expensive function.
5010
5011#ifndef NDEBUG
5012 // AST quite reasonably asserts that it's working on a function
5013 // definition. We don't really have a way to tell it that we're
5014 // currently defining the function, so just lie to it in +Asserts
5015 // builds. This is an awful hack.
5016 FD->setLazyBody(1);
5017#endif
5018
David Majnemer27d69db2014-04-28 22:17:59 +00005019 bool isC99Inline =
5020 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
John McCallc87d9722013-04-02 02:48:58 +00005021
5022#ifndef NDEBUG
5023 FD->setLazyBody(0);
5024#endif
5025
5026 return isC99Inline;
5027}
5028
Richard Smithac974a32013-06-30 09:48:50 +00005029/// Determine whether a variable is extern "C" prior to attaching
5030/// an initializer. We can't just call isExternC() here, because that
5031/// will also compute and cache whether the declaration is externally
5032/// visible, which might change when we attach the initializer.
5033///
5034/// This can only be used if the declaration is known to not be a
5035/// redeclaration of an internal linkage declaration.
5036///
5037/// For instance:
5038///
5039/// auto x = []{};
5040///
5041/// Attaching the initializer here makes this declaration not externally
5042/// visible, because its type has internal linkage.
5043///
5044/// FIXME: This is a hack.
5045template<typename T>
5046static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5047 if (S.getLangOpts().CPlusPlus) {
5048 // In C++, the overloadable attribute negates the effects of extern "C".
5049 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5050 return false;
5051 }
5052 return D->isExternC();
5053}
5054
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005055static bool shouldConsiderLinkage(const VarDecl *VD) {
5056 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5057 if (DC->isFunctionOrMethod())
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005058 return VD->hasExternalStorage();
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005059 if (DC->isFileContext())
5060 return true;
5061 if (DC->isRecord())
5062 return false;
5063 llvm_unreachable("Unexpected context");
5064}
5065
5066static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5067 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5068 if (DC->isFileContext() || DC->isFunctionOrMethod())
5069 return true;
5070 if (DC->isRecord())
5071 return false;
5072 llvm_unreachable("Unexpected context");
5073}
5074
Nico Riecke84f8db2014-03-23 21:24:01 +00005075static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5076 AttributeList::Kind Kind) {
5077 for (const AttributeList *L = AttrList; L; L = L->getNext())
5078 if (L->getKind() == Kind)
5079 return true;
5080 return false;
5081}
5082
5083static bool hasParsedAttr(Scope *S, const Declarator &PD,
5084 AttributeList::Kind Kind) {
5085 // Check decl attributes on the DeclSpec.
5086 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5087 return true;
5088
5089 // Walk the declarator structure, checking decl attributes that were in a type
5090 // position to the decl itself.
5091 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5092 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5093 return true;
5094 }
5095
5096 // Finally, check attributes on the decl itself.
5097 return hasParsedAttr(S, PD.getAttributes(), Kind);
5098}
5099
Richard Smith541b38b2013-09-20 01:15:31 +00005100/// Adjust the \c DeclContext for a function or variable that might be a
5101/// function-local external declaration.
5102bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5103 if (!DC->isFunctionOrMethod())
5104 return false;
5105
5106 // If this is a local extern function or variable declared within a function
5107 // template, don't add it into the enclosing namespace scope until it is
5108 // instantiated; it might have a dependent type right now.
5109 if (DC->isDependentContext())
5110 return true;
5111
5112 // C++11 [basic.link]p7:
5113 // When a block scope declaration of an entity with linkage is not found to
5114 // refer to some other declaration, then that entity is a member of the
5115 // innermost enclosing namespace.
5116 //
5117 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5118 // semantically-enclosing namespace, not a lexically-enclosing one.
5119 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5120 DC = DC->getParent();
5121 return true;
5122}
5123
Larisse Voufo39a1e502013-08-06 01:03:05 +00005124NamedDecl *
Chris Lattner88fdea82010-10-10 18:16:20 +00005125Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005126 TypeSourceInfo *TInfo, LookupResult &Previous,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005127 MultiTemplateParamsArg TemplateParamLists,
5128 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005129 QualType R = TInfo->getType();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005130 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005131
Douglas Gregorc4df4072010-04-19 22:54:31 +00005132 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
Rafael Espindolabff59562013-04-25 12:11:36 +00005133 VarDecl::StorageClass SC =
5134 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
Joey Goulydd7f4562013-01-23 11:56:20 +00005135
Nico Riecke84f8db2014-03-23 21:24:01 +00005136 // dllimport globals without explicit storage class are treated as extern. We
5137 // have to change the storage class this early to get the right DeclContext.
5138 if (SC == SC_None && !DC->isRecord() &&
Nico Rieck755a36f2014-05-25 10:34:16 +00005139 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5140 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
Nico Riecke84f8db2014-03-23 21:24:01 +00005141 SC = SC_Extern;
5142
Richard Smith541b38b2013-09-20 01:15:31 +00005143 DeclContext *OriginalDC = DC;
5144 bool IsLocalExternDecl = SC == SC_Extern &&
5145 adjustContextForLocalExternDecl(DC);
5146
Pekka Jaaskelainen8690a682014-02-20 13:52:08 +00005147 if (getLangOpts().OpenCL) {
5148 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5149 QualType NR = R;
5150 while (NR->isPointerType()) {
5151 if (NR->isFunctionPointerType()) {
5152 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5153 D.setInvalidType();
5154 break;
5155 }
5156 NR = NR->getPointeeType();
5157 }
5158
5159 if (!getOpenCLOptions().cl_khr_fp16) {
5160 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5161 // half array type (unless the cl_khr_fp16 extension is enabled).
5162 if (Context.getBaseElementType(R)->isHalfType()) {
5163 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5164 D.setInvalidType();
5165 }
Joey Goulydd7f4562013-01-23 11:56:20 +00005166 }
5167 }
5168
Douglas Gregorc4df4072010-04-19 22:54:31 +00005169 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005170 // mutable can only appear on non-static class members, so it's always
5171 // an error here
5172 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005173 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005174 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005175 }
John McCallc87d9722013-04-02 02:48:58 +00005176
Richard Smithf2c9afc2013-06-17 01:34:01 +00005177 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5178 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5179 D.getDeclSpec().getStorageClassSpecLoc())) {
5180 // In C++11, the 'register' storage class specifier is deprecated.
5181 // Suppress the warning in system macros, it's used in macros in some
5182 // popular C system headers, such as in glibc's htonl() macro.
5183 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5184 diag::warn_deprecated_register)
5185 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5186 }
5187
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005188 IdentifierInfo *II = Name.getAsIdentifierInfo();
5189 if (!II) {
5190 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
Douglas Gregorbb64afc2011-10-09 18:55:59 +00005191 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00005192 return nullptr;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005193 }
5194
Richard Smithb1402ae2013-03-18 22:52:47 +00005195 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor0c880302009-03-11 23:00:04 +00005196
Craig Topperc3ec1492014-05-26 06:22:03 +00005197 if (!DC->isRecord() && S->getFnParent() == nullptr) {
Douglas Gregor212cab32009-03-11 20:22:50 +00005198 // C99 6.9p2: The storage-class specifiers auto and register shall not
5199 // appear in the declaration specifiers in an external declaration.
Renato Golin230c5eb2014-05-19 18:15:42 +00005200 // Global Register+Asm is a GNU extension we support.
5201 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5202 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005203 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005204 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005205 }
Richard Smithf2c9afc2013-06-17 01:34:01 +00005206
David Blaikiebbafb8a2012-03-11 07:00:24 +00005207 if (getLangOpts().OpenCL) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005208 // Set up the special work-group-local storage class for variables in the
5209 // OpenCL __local address space.
Rafael Espindola2be6b722012-12-21 01:21:33 +00005210 if (R.getAddressSpace() == LangAS::opencl_local) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005211 SC = SC_OpenCLWorkGroupLocal;
Rafael Espindola2be6b722012-12-21 01:21:33 +00005212 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005213
Guy Benyei61054192013-02-07 10:55:47 +00005214 // OpenCL v1.2 s6.9.b p4:
5215 // The sampler type cannot be used with the __local and __global address
5216 // space qualifiers.
5217 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5218 R.getAddressSpace() == LangAS::opencl_global)) {
5219 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5220 }
5221
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005222 // OpenCL 1.2 spec, p6.9 r:
5223 // The event type cannot be used to declare a program scope variable.
5224 // The event type cannot be used with the __local, __constant and __global
5225 // address space qualifiers.
5226 if (R->isEventT()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005227 if (S->getParent() == nullptr) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005228 Diag(D.getLocStart(), diag::err_event_t_global_var);
5229 D.setInvalidType();
5230 }
5231
5232 if (R.getAddressSpace()) {
5233 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5234 D.setInvalidType();
5235 }
5236 }
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005237 }
5238
Larisse Voufo39a1e502013-08-06 01:03:05 +00005239 bool IsExplicitSpecialization = false;
5240 bool IsVariableTemplateSpecialization = false;
5241 bool IsPartialSpecialization = false;
Larisse Voufod8dd97c2013-08-14 03:09:19 +00005242 bool IsVariableTemplate = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00005243 VarDecl *NewVD = nullptr;
5244 VarTemplateDecl *NewTemplate = nullptr;
5245 TemplateParameterList *TemplateParams = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005246 if (!getLangOpts().CPlusPlus) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005247 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005248 D.getIdentifierLoc(), II,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005249 R, TInfo, SC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005250
5251 if (D.isInvalidType())
5252 NewVD->setInvalidDecl();
5253 } else {
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005254 bool Invalid = false;
5255
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005256 if (DC->isRecord() && !CurContext->isRecord()) {
5257 // This is an out-of-line definition of a static data member.
Rafael Espindola45f96f82013-06-19 13:41:54 +00005258 switch (SC) {
5259 case SC_None:
5260 break;
5261 case SC_Static:
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005262 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5263 diag::err_static_out_of_line)
5264 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Rafael Espindola45f96f82013-06-19 13:41:54 +00005265 break;
5266 case SC_Auto:
5267 case SC_Register:
5268 case SC_Extern:
5269 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5270 // to names of variables declared in a block or to function parameters.
5271 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5272 // of class members
5273
5274 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5275 diag::err_storage_class_for_static_member)
5276 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5277 break;
5278 case SC_PrivateExtern:
5279 llvm_unreachable("C storage class in c++!");
5280 case SC_OpenCLWorkGroupLocal:
5281 llvm_unreachable("OpenCL storage class in c++!");
Rafael Espindola8ac2f592013-04-04 21:21:25 +00005282 }
Larisse Voufo21de36b2013-08-06 03:43:07 +00005283 }
5284
Richard Smith42973752012-02-16 20:41:22 +00005285 if (SC == SC_Static && CurContext->isRecord()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005286 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5287 if (RD->isLocalClass())
5288 Diag(D.getIdentifierLoc(),
5289 diag::err_static_data_member_not_allowed_in_local_class)
5290 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005291
Richard Smith42973752012-02-16 20:41:22 +00005292 // C++98 [class.union]p1: If a union contains a static data member,
5293 // the program is ill-formed. C++11 drops this restriction.
5294 if (RD->isUnion())
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005295 Diag(D.getIdentifierLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005296 getLangOpts().CPlusPlus11
Richard Smith42973752012-02-16 20:41:22 +00005297 ? diag::warn_cxx98_compat_static_data_member_in_union
5298 : diag::ext_static_data_member_in_union) << Name;
5299 // We conservatively disallow static data members in anonymous structs.
5300 else if (!RD->getDeclName())
5301 Diag(D.getIdentifierLoc(),
5302 diag::err_static_data_member_not_allowed_in_anon_struct)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005303 << Name << RD->isUnion();
5304 }
5305 }
5306
5307 // Match up the template parameter lists with the scope specifier, then
5308 // determine whether we have a template or a template specialization.
Richard Smithbeef3452014-01-16 23:39:20 +00005309 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5310 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00005311 D.getCXXScopeSpec(),
5312 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5313 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00005314 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005315 TemplateParamLists,
Richard Smithbeef3452014-01-16 23:39:20 +00005316 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005317
Richard Smithbeef3452014-01-16 23:39:20 +00005318 if (TemplateParams) {
5319 if (!TemplateParams->size() &&
5320 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5321 // There is an extraneous 'template<>' for this variable. Complain
5322 // about it, but allow the declaration of the variable.
5323 Diag(TemplateParams->getTemplateLoc(),
5324 diag::err_template_variable_noparams)
5325 << II
5326 << SourceRange(TemplateParams->getTemplateLoc(),
5327 TemplateParams->getRAngleLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00005328 TemplateParams = nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005329 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005330 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5331 // This is an explicit specialization or a partial specialization.
5332 // FIXME: Check that we can declare a specialization here.
5333 IsVariableTemplateSpecialization = true;
5334 IsPartialSpecialization = TemplateParams->size() > 0;
5335 } else { // if (TemplateParams->size() > 0)
5336 // This is a template declaration.
5337 IsVariableTemplate = true;
5338
5339 // Check that we can declare a template here.
5340 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00005341 return nullptr;
Richard Smith0d963d62014-04-17 02:56:49 +00005342
5343 // Only C++1y supports variable templates (N3651).
5344 Diag(D.getIdentifierLoc(),
5345 getLangOpts().CPlusPlus1y
5346 ? diag::warn_cxx11_compat_variable_template
5347 : diag::ext_variable_template);
Richard Smithbeef3452014-01-16 23:39:20 +00005348 }
5349 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00005350 } else {
5351 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
5352 "should have a 'template<>' for this decl");
Douglas Gregorb09f3d82009-07-22 17:18:37 +00005353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
Larisse Voufo39a1e502013-08-06 01:03:05 +00005355 if (IsVariableTemplateSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005356 SourceLocation TemplateKWLoc =
5357 TemplateParamLists.size() > 0
5358 ? TemplateParamLists[0]->getTemplateLoc()
5359 : SourceLocation();
5360 DeclResult Res = ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00005361 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005362 IsPartialSpecialization);
5363 if (Res.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00005364 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005365 NewVD = cast<VarDecl>(Res.get());
5366 AddToScope = false;
5367 } else
5368 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5369 D.getIdentifierLoc(), II, R, TInfo, SC);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005370
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005371 // If this is supposed to be a variable template, create it as such.
5372 if (IsVariableTemplate) {
5373 NewTemplate =
5374 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
Richard Smithbeef3452014-01-16 23:39:20 +00005375 TemplateParams, NewVD);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005376 NewVD->setDescribedVarTemplate(NewTemplate);
5377 }
5378
Richard Smithb2bc2e62011-02-21 20:05:19 +00005379 // If this decl has an auto type in need of deduction, make a note of the
5380 // Decl so we can diagnose uses of it in its own initializer.
Richard Smith74aeef52013-04-26 16:15:35 +00005381 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
Richard Smithb2bc2e62011-02-21 20:05:19 +00005382 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00005383
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005384 if (D.isInvalidType() || Invalid) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005385 NewVD->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005386 if (NewTemplate)
5387 NewTemplate->setInvalidDecl();
5388 }
Mike Stump11289f42009-09-09 15:08:12 +00005389
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005390 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00005391
Richard Smith72db5632014-01-25 21:32:06 +00005392 // If we have any template parameter lists that don't directly belong to
5393 // the variable (matching the scope specifier), store them.
5394 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5395 if (TemplateParamLists.size() > VDTemplateParamLists)
Larisse Voufo39a1e502013-08-06 01:03:05 +00005396 NewVD->setTemplateParameterListsInfo(
Richard Smith72db5632014-01-25 21:32:06 +00005397 Context, TemplateParamLists.size() - VDTemplateParamLists,
5398 TemplateParamLists.data());
Richard Smitha77a0a62011-08-15 21:04:07 +00005399
Richard Smith6331c402012-02-13 22:16:19 +00005400 if (D.getDeclSpec().isConstexprSpecified())
Richard Smithf0215fe2011-12-25 21:17:58 +00005401 NewVD->setConstexpr(true);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00005402 }
5403
Douglas Gregor41866812011-09-12 18:37:38 +00005404 // Set the lexical context. If the declarator has a C++ scope specifier, the
5405 // lexical context will be different from the semantic context.
5406 NewVD->setLexicalDeclContext(CurContext);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005407 if (NewTemplate)
5408 NewTemplate->setLexicalDeclContext(CurContext);
Douglas Gregor41866812011-09-12 18:37:38 +00005409
Richard Smith541b38b2013-09-20 01:15:31 +00005410 if (IsLocalExternDecl)
5411 NewVD->setLocalExternDecl();
5412
Richard Smithb4a9e862013-04-12 22:46:28 +00005413 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005414 if (NewVD->hasLocalStorage()) {
5415 // C++11 [dcl.stc]p4:
5416 // When thread_local is applied to a variable of block scope the
5417 // storage-class-specifier static is implied if it does not appear
5418 // explicitly.
5419 // Core issue: 'static' is not implied if the variable is declared
5420 // 'extern'.
5421 if (SCSpec == DeclSpec::SCS_unspecified &&
5422 TSCS == DeclSpec::TSCS_thread_local &&
5423 DC->isFunctionOrMethod())
5424 NewVD->setTSCSpec(TSCS);
5425 else
5426 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5427 diag::err_thread_non_global)
5428 << DeclSpec::getSpecifierName(TSCS);
5429 } else if (!Context.getTargetInfo().isTLSSupported())
Richard Smithb4a9e862013-04-12 22:46:28 +00005430 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5431 diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005432 else
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00005433 NewVD->setTSCSpec(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005434 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005435
John McCallc87d9722013-04-02 02:48:58 +00005436 // C99 6.7.4p3
5437 // An inline definition of a function with external linkage shall
5438 // not contain a definition of a modifiable object with static or
5439 // thread storage duration...
5440 // We only apply this when the function is required to be defined
5441 // elsewhere, i.e. when the function is not 'extern inline'. Note
5442 // that a local variable with thread storage duration still has to
5443 // be marked 'static'. Also note that it's possible to get these
5444 // semantics in C++ using __attribute__((gnu_inline)).
Craig Topperc3ec1492014-05-26 06:22:03 +00005445 if (SC == SC_Static && S->getFnParent() != nullptr &&
John McCallc87d9722013-04-02 02:48:58 +00005446 !NewVD->getType().isConstQualified()) {
5447 FunctionDecl *CurFD = getCurFunctionDecl();
5448 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5449 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5450 diag::warn_static_local_in_extern_inline);
5451 MaybeSuggestAddingStaticToDecl(CurFD);
5452 }
5453 }
5454
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005455 if (D.getDeclSpec().isModulePrivateSpecified()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005456 if (IsVariableTemplateSpecialization)
5457 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5458 << (IsPartialSpecialization ? 1 : 0)
5459 << FixItHint::CreateRemoval(
5460 D.getDeclSpec().getModulePrivateSpecLoc());
5461 else if (IsExplicitSpecialization)
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005462 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5463 << 2
5464 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Douglas Gregor41866812011-09-12 18:37:38 +00005465 else if (NewVD->hasLocalStorage())
5466 Diag(NewVD->getLocation(), diag::err_module_private_local)
5467 << 0 << NewVD->getDeclName()
5468 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5469 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005470 else {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005471 NewVD->setModulePrivate();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005472 if (NewTemplate)
5473 NewTemplate->setModulePrivate();
5474 }
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005475 }
Douglas Gregor26701a42011-09-09 02:06:17 +00005476
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005477 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00005478 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005479
Peter Collingbournec6b08572012-08-28 20:37:50 +00005480 if (getLangOpts().CUDA) {
5481 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5482 // storage [duration]."
Craig Topperc3ec1492014-05-26 06:22:03 +00005483 if (SC == SC_None && S->getFnParent() != nullptr &&
Rafael Espindola2be6b722012-12-21 01:21:33 +00005484 (NewVD->hasAttr<CUDASharedAttr>() ||
5485 NewVD->hasAttr<CUDAConstantAttr>())) {
Peter Collingbournec6b08572012-08-28 20:37:50 +00005486 NewVD->setStorageClass(SC_Static);
Rafael Espindola2be6b722012-12-21 01:21:33 +00005487 }
Peter Collingbournec6b08572012-08-28 20:37:50 +00005488 }
5489
Nico Riecke84f8db2014-03-23 21:24:01 +00005490 // Ensure that dllimport globals without explicit storage class are treated as
5491 // extern. The storage class is set above using parsed attributes. Now we can
5492 // check the VarDecl itself.
5493 assert(!NewVD->hasAttr<DLLImportAttr>() ||
5494 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5495 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5496
John McCall31168b02011-06-15 23:02:42 +00005497 // In auto-retain/release, infer strong retension for variables of
5498 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005499 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
John McCall31168b02011-06-15 23:02:42 +00005500 NewVD->setInvalidDecl();
5501
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005502 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00005503 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005504 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00005505 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005506 StringRef Label = SE->getString();
Craig Topperc3ec1492014-05-26 06:22:03 +00005507 if (S->getFnParent() != nullptr) {
Abramo Bagnara13392232011-01-11 15:16:52 +00005508 switch (SC) {
5509 case SC_None:
5510 case SC_Auto:
5511 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5512 break;
5513 case SC_Register:
Renato Golin230c5eb2014-05-19 18:15:42 +00005514 // Local Named register
Douglas Gregore8bbc122011-09-02 00:18:52 +00005515 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
Abramo Bagnara13392232011-01-11 15:16:52 +00005516 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5517 break;
5518 case SC_Static:
5519 case SC_Extern:
5520 case SC_PrivateExtern:
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00005521 case SC_OpenCLWorkGroupLocal:
Abramo Bagnara13392232011-01-11 15:16:52 +00005522 break;
5523 }
Renato Golin230c5eb2014-05-19 18:15:42 +00005524 } else if (SC == SC_Register) {
5525 // Global Named register
5526 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5527 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
Renato Golin2e31e4e2014-06-05 16:45:22 +00005528 if (!R->isIntegralType(Context) && !R->isPointerType()) {
5529 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5530 NewVD->setInvalidDecl(true);
5531 }
Abramo Bagnara13392232011-01-11 15:16:52 +00005532 }
5533
5534 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Aaron Ballman36a53502014-01-16 13:03:14 +00005535 Context, Label, 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00005536 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5537 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5538 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5539 if (I != ExtnameUndeclaredIdentifiers.end()) {
5540 NewVD->addAttr(I->second);
5541 ExtnameUndeclaredIdentifiers.erase(I);
5542 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005543 }
5544
John McCalla2a3f7d2010-03-16 21:48:18 +00005545 // Diagnose shadowed variables before filtering for scope.
Richard Smith72bcaec2013-12-05 04:30:04 +00005546 if (D.getCXXScopeSpec().isEmpty())
John McCalldf8b37c2010-03-22 09:20:08 +00005547 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00005548
John McCall1f82f242009-11-18 22:49:29 +00005549 // Don't consider existing declarations that are in a different
5550 // scope and are out-of-semantic-context declarations (if the new
5551 // declaration has linkage).
Richard Smith72bcaec2013-12-05 04:30:04 +00005552 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5553 D.getCXXScopeSpec().isNotEmpty() ||
5554 IsExplicitSpecialization ||
5555 IsVariableTemplateSpecialization);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005556
Richard Smith1c34fb72013-08-13 18:18:50 +00005557 // Check whether the previous declaration is in the same block scope. This
5558 // affects whether we merge types with it, per C++11 [dcl.array]p3.
5559 if (getLangOpts().CPlusPlus &&
5560 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5561 NewVD->setPreviousDeclInSameBlockScope(
5562 Previous.isSingleResult() && !Previous.isShadowed() &&
Richard Smith541b38b2013-09-20 01:15:31 +00005563 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
Richard Smith1c34fb72013-08-13 18:18:50 +00005564
David Blaikiebbafb8a2012-03-11 07:00:24 +00005565 if (!getLangOpts().CPlusPlus) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005566 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5567 } else {
Richard Smithbeef3452014-01-16 23:39:20 +00005568 // If this is an explicit specialization of a static data member, check it.
5569 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5570 CheckMemberSpecialization(NewVD, Previous))
5571 NewVD->setInvalidDecl();
5572
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005573 // Merge the decl with the existing one if appropriate.
5574 if (!Previous.empty()) {
5575 if (Previous.isSingleResult() &&
5576 isa<FieldDecl>(Previous.getFoundDecl()) &&
5577 D.getCXXScopeSpec().isSet()) {
5578 // The user tried to define a non-static data member
5579 // out-of-line (C++ [dcl.meaning]p1).
5580 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5581 << D.getCXXScopeSpec().getRange();
5582 Previous.clear();
5583 NewVD->setInvalidDecl();
5584 }
5585 } else if (D.getCXXScopeSpec().isSet()) {
5586 // No previous declaration in the qualifying scope.
5587 Diag(D.getIdentifierLoc(), diag::err_no_member)
5588 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005589 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005590 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005591 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005592
Richard Smithbeef3452014-01-16 23:39:20 +00005593 if (!IsVariableTemplateSpecialization)
5594 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00005595
Richard Smithbeef3452014-01-16 23:39:20 +00005596 if (NewTemplate) {
5597 VarTemplateDecl *PrevVarTemplate =
5598 NewVD->getPreviousDecl()
5599 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
Craig Topperc3ec1492014-05-26 06:22:03 +00005600 : nullptr;
Richard Smithbeef3452014-01-16 23:39:20 +00005601
5602 // Check the template parameter list of this declaration, possibly
5603 // merging in the template parameter list from the previous variable
5604 // template declaration.
5605 if (CheckTemplateParameterList(
5606 TemplateParams,
5607 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
Craig Topperc3ec1492014-05-26 06:22:03 +00005608 : nullptr,
Richard Smithbeef3452014-01-16 23:39:20 +00005609 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5610 DC->isDependentContext())
5611 ? TPC_ClassTemplateMember
5612 : TPC_VarTemplate))
5613 NewVD->setInvalidDecl();
5614
5615 // If we are providing an explicit specialization of a static variable
5616 // template, make a note of that.
5617 if (PrevVarTemplate &&
5618 PrevVarTemplate->getInstantiatedFromMemberTemplate())
5619 PrevVarTemplate->setMemberSpecialization();
5620 }
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005621 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00005622
Rafael Espindolade6a39f2013-03-02 21:41:48 +00005623 ProcessPragmaWeak(S, NewVD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00005624
Richard Smithac974a32013-06-30 09:48:50 +00005625 // If this is the first declaration of an extern C variable, update
5626 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00005627 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00005628 isIncompleteDeclExternC(*this, NewVD))
Richard Smith39b79682013-06-18 20:15:12 +00005629 RegisterLocallyScopedExternCDecl(NewVD, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005630
Reid Klecknerd8110b62013-09-10 20:14:30 +00005631 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005632 Decl *ManglingContextDecl;
5633 if (MangleNumberingContext *MCtx =
5634 getCurrentMangleNumberContext(NewVD->getDeclContext(),
5635 ManglingContextDecl)) {
David Majnemerf27217f2014-03-05 18:55:38 +00005636 Context.setManglingNumber(
5637 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
David Majnemer2206bf52014-03-05 08:57:59 +00005638 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
Eli Friedman3b7d46c2013-07-10 00:30:46 +00005639 }
5640 }
5641
Nico Rieck82f0b062014-03-31 14:56:15 +00005642 if (D.isRedeclaration() && !Previous.empty()) {
5643 checkDLLAttributeRedeclaration(
5644 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5645 IsExplicitSpecialization);
5646 }
5647
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005648 if (NewTemplate) {
Richard Smithbeef3452014-01-16 23:39:20 +00005649 if (NewVD->isInvalidDecl())
5650 NewTemplate->setInvalidDecl();
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005651 ActOnDocumentableDecl(NewTemplate);
5652 return NewTemplate;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005653 }
5654
Larisse Voufo72caf2b2013-08-22 00:59:14 +00005655 return NewVD;
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005656}
5657
John McCalldf8b37c2010-03-22 09:20:08 +00005658/// \brief Diagnose variable or built-in function shadowing. Implements
5659/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00005660///
John McCalldf8b37c2010-03-22 09:20:08 +00005661/// This method is called whenever a VarDecl is added to a "useful"
5662/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00005663///
John McCall2d8c7602010-03-20 04:12:52 +00005664/// \param S the scope in which the shadowing name is being declared
5665/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00005666///
John McCalldf8b37c2010-03-22 09:20:08 +00005667void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005668 // Return if warning is ignored.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005669 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
John McCalla2a3f7d2010-03-16 21:48:18 +00005670 return;
5671
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00005672 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005673 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00005674 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00005675
5676 DeclContext *NewDC = D->getDeclContext();
5677
John McCall2d8c7602010-03-20 04:12:52 +00005678 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00005679 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00005680 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00005681
John McCalla2a3f7d2010-03-16 21:48:18 +00005682 NamedDecl* ShadowedDecl = R.getFoundDecl();
5683 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5684 return;
5685
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00005686 // Fields are not shadowed by variables in C++ static methods.
5687 if (isa<FieldDecl>(ShadowedDecl))
5688 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5689 if (MD->isStatic())
5690 return;
5691
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005692 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5693 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005694 // For shadowing external vars, make sure that we point to the global
5695 // declaration, not a locally scoped extern declaration.
Aaron Ballman86c93902014-03-06 23:45:36 +00005696 for (auto I : shadowedVar->redecls())
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005697 if (I->isFileVarDecl()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00005698 ShadowedDecl = I;
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00005699 break;
5700 }
5701 }
5702
5703 DeclContext *OldDC = ShadowedDecl->getDeclContext();
5704
John McCall2d8c7602010-03-20 04:12:52 +00005705 // Only warn about certain kinds of shadowing for class members.
5706 if (NewDC && NewDC->isRecord()) {
5707 // In particular, don't warn about shadowing non-class members.
5708 if (!OldDC->isRecord())
5709 return;
5710
5711 // TODO: should we warn about static data members shadowing
5712 // static data members from base classes?
5713
5714 // TODO: don't diagnose for inaccessible shadowed members.
5715 // This is hard to do perfectly because we might friend the
5716 // shadowing context, but that's just a false negative.
5717 }
5718
5719 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00005720 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00005721 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00005722 if (isa<FieldDecl>(ShadowedDecl))
5723 Kind = 3; // field
5724 else
5725 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00005726 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00005727 Kind = 1; // global
5728 else
5729 Kind = 0; // local
5730
John McCall2d8c7602010-03-20 04:12:52 +00005731 DeclarationName Name = R.getLookupName();
5732
John McCalla2a3f7d2010-03-16 21:48:18 +00005733 // Emit warning and note.
Alp Toker15ab3732013-12-12 12:47:48 +00005734 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5735 return;
John McCall2d8c7602010-03-20 04:12:52 +00005736 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00005737 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5738}
5739
John McCalldf8b37c2010-03-22 09:20:08 +00005740/// \brief Check -Wshadow without the advantage of a previous lookup.
5741void Sema::CheckShadow(Scope *S, VarDecl *D) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005742 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005743 return;
5744
John McCalldf8b37c2010-03-22 09:20:08 +00005745 LookupResult R(*this, D->getDeclName(), D->getLocation(),
5746 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5747 LookupName(R, S);
5748 CheckShadow(S, D, R);
5749}
5750
Richard Smithac974a32013-06-30 09:48:50 +00005751/// Check for conflict between this global or extern "C" declaration and
5752/// previous global or extern "C" declarations. This is only used in C++.
Rafael Espindola46afb352013-01-11 19:34:23 +00005753template<typename T>
Richard Smithac974a32013-06-30 09:48:50 +00005754static bool checkGlobalOrExternCConflict(
5755 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5756 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5757 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005758
Richard Smithac974a32013-06-30 09:48:50 +00005759 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5760 // The common case: this global doesn't conflict with any extern "C"
5761 // declaration.
5762 return false;
5763 }
5764
5765 if (Prev) {
5766 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5767 // Both the old and new declarations have C language linkage. This is a
5768 // redeclaration.
5769 Previous.clear();
5770 Previous.addDecl(Prev);
5771 return true;
5772 }
5773
5774 // This is a global, non-extern "C" declaration, and there is a previous
5775 // non-global extern "C" declaration. Diagnose if this is a variable
5776 // declaration.
5777 if (!isa<VarDecl>(ND))
5778 return false;
5779 } else {
5780 // The declaration is extern "C". Check for any declaration in the
5781 // translation unit which might conflict.
5782 if (IsGlobal) {
5783 // We have already performed the lookup into the translation unit.
5784 IsGlobal = false;
5785 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5786 I != E; ++I) {
5787 if (isa<VarDecl>(*I)) {
5788 Prev = *I;
5789 break;
5790 }
5791 }
5792 } else {
5793 DeclContext::lookup_result R =
5794 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5795 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5796 I != E; ++I) {
5797 if (isa<VarDecl>(*I)) {
5798 Prev = *I;
5799 break;
5800 }
5801 // FIXME: If we have any other entity with this name in global scope,
5802 // the declaration is ill-formed, but that is a defect: it breaks the
5803 // 'stat' hack, for instance. Only variables can have mangled name
5804 // clashes with extern "C" declarations, so only they deserve a
5805 // diagnostic.
5806 }
5807 }
5808
5809 if (!Prev)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00005810 return false;
5811 }
5812
Richard Smithac974a32013-06-30 09:48:50 +00005813 // Use the first declaration's location to ensure we point at something which
5814 // is lexically inside an extern "C" linkage-spec.
5815 assert(Prev && "should have found a previous declaration to diagnose");
5816 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Rafael Espindola8db352d2013-10-17 15:37:26 +00005817 Prev = FD->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005818 else
Rafael Espindola8db352d2013-10-17 15:37:26 +00005819 Prev = cast<VarDecl>(Prev)->getFirstDecl();
Richard Smithac974a32013-06-30 09:48:50 +00005820
5821 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5822 << IsGlobal << ND;
5823 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5824 << IsGlobal;
5825 return false;
5826}
5827
5828/// Apply special rules for handling extern "C" declarations. Returns \c true
5829/// if we have found that this is a redeclaration of some prior entity.
5830///
5831/// Per C++ [dcl.link]p6:
5832/// Two declarations [for a function or variable] with C language linkage
5833/// with the same name that appear in different scopes refer to the same
5834/// [entity]. An entity with C language linkage shall not be declared with
5835/// the same name as an entity in global scope.
5836template<typename T>
5837static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5838 LookupResult &Previous) {
5839 if (!S.getLangOpts().CPlusPlus) {
5840 // In C, when declaring a global variable, look for a corresponding 'extern'
Richard Smith541b38b2013-09-20 01:15:31 +00005841 // variable declared in function scope. We don't need this in C++, because
5842 // we find local extern decls in the surrounding file-scope DeclContext.
Richard Smithac974a32013-06-30 09:48:50 +00005843 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5844 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5845 Previous.clear();
5846 Previous.addDecl(Prev);
5847 return true;
5848 }
5849 }
5850 return false;
5851 }
5852
5853 // A declaration in the translation unit can conflict with an extern "C"
5854 // declaration.
5855 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5856 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5857
5858 // An extern "C" declaration can conflict with a declaration in the
5859 // translation unit or can be a redeclaration of an extern "C" declaration
5860 // in another scope.
5861 if (isIncompleteDeclExternC(S,ND))
5862 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5863
5864 // Neither global nor extern "C": nothing to do.
5865 return false;
Rafael Espindola46afb352013-01-11 19:34:23 +00005866}
5867
Richard Smith27d807c2013-04-30 13:56:41 +00005868void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005869 // If the decl is already known invalid, don't check it.
5870 if (NewVD->isInvalidDecl())
Richard Smith27d807c2013-04-30 13:56:41 +00005871 return;
Mike Stump11289f42009-09-09 15:08:12 +00005872
Abramo Bagnara341ab732012-11-08 14:44:42 +00005873 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5874 QualType T = TInfo->getType();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005875
Richard Smith27d807c2013-04-30 13:56:41 +00005876 // Defer checking an 'auto' type until its initializer is attached.
5877 if (T->isUndeducedType())
5878 return;
5879
Richard Smithdc4ccaa2014-03-27 01:22:48 +00005880 if (NewVD->hasAttrs())
5881 CheckAlignasUnderalignment(NewVD);
5882
John McCall8b07ec22010-05-15 11:32:37 +00005883 if (T->isObjCObjectType()) {
Fariborz Jahanian9a14c212011-07-25 21:12:27 +00005884 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5885 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00005886 T = Context.getObjCObjectPointerType(T);
5887 NewVD->setType(T);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005890 // Emit an error if an address space was applied to decl with local storage.
5891 // This includes arrays of objects with address space qualifiers, but not
5892 // automatic variables that point to other address spaces.
5893 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00005894 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005895 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005896 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005897 return;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00005898 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00005899
Tanya Lattner713eef42013-04-05 20:14:50 +00005900 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5901 // __constant address space.
5902 if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5903 && T.getAddressSpace() != LangAS::opencl_constant
5904 && !T->isSamplerT()){
5905 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5906 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005907 return;
Tanya Lattner713eef42013-04-05 20:14:50 +00005908 }
5909
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005910 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5911 // scope.
5912 if ((getLangOpts().OpenCLVersion >= 120)
5913 && NewVD->isStaticLocal()) {
5914 Diag(NewVD->getLocation(), diag::err_static_function_scope);
5915 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005916 return;
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00005917 }
5918
Mike Stumpca5ae662009-04-14 00:57:29 +00005919 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005920 && !NewVD->hasAttr<BlocksAttr>()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005921 if (getLangOpts().getGC() != LangOptions::NonGC)
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005922 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005923 else {
5924 assert(!getLangOpts().ObjCAutoRefCount);
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005925 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Ted Kremenek2f88c402012-10-02 05:36:02 +00005926 }
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00005927 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005928
Chris Lattner9fecd742009-04-19 05:21:20 +00005929 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00005930 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00005931 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00005932 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00005933
Chris Lattner9fecd742009-04-19 05:21:20 +00005934 if ((isVM && NewVD->hasLinkage()) ||
5935 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005936 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00005937 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +00005938 TypeSourceInfo *FixedTInfo =
5939 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5940 SizeIsNegative, Oversized);
Craig Topperc3ec1492014-05-26 06:22:03 +00005941 if (!FixedTInfo && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00005942 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00005943 // FIXME: This won't give the correct result for
5944 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00005945 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005946
Anders Carlsson6c885802009-02-28 21:56:50 +00005947 if (NewVD->isFileVarDecl())
5948 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005949 << SizeRange;
Enea Zaffanella28f36ba2013-05-10 20:34:44 +00005950 else if (NewVD->isStaticLocal())
Anders Carlsson6c885802009-02-28 21:56:50 +00005951 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005952 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00005953 else
5954 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005955 << SizeRange;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005956 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005957 return;
Mike Stump11289f42009-09-09 15:08:12 +00005958 }
5959
Craig Topperc3ec1492014-05-26 06:22:03 +00005960 if (!FixedTInfo) {
Anders Carlsson6c885802009-02-28 21:56:50 +00005961 if (NewVD->isFileVarDecl())
5962 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5963 else
5964 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00005965 NewVD->setInvalidDecl();
Richard Smith27d807c2013-04-30 13:56:41 +00005966 return;
Anders Carlsson6c885802009-02-28 21:56:50 +00005967 }
Mike Stump11289f42009-09-09 15:08:12 +00005968
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005969 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
Abramo Bagnara3b8a9e52012-11-08 16:01:51 +00005970 NewVD->setType(FixedTInfo->getType());
Abramo Bagnara341ab732012-11-08 14:44:42 +00005971 NewVD->setTypeSourceInfo(FixedTInfo);
Anders Carlsson6c885802009-02-28 21:56:50 +00005972 }
5973
David Majnemer0ffa3312013-05-29 00:56:45 +00005974 if (T->isVoidType()) {
5975 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5976 // of objects and functions.
5977 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5978 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5979 << T;
5980 NewVD->setInvalidDecl();
5981 return;
5982 }
Richard Smith27d807c2013-04-30 13:56:41 +00005983 }
5984
5985 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5986 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5987 NewVD->setInvalidDecl();
5988 return;
5989 }
5990
5991 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5992 Diag(NewVD->getLocation(), diag::err_block_on_vm);
5993 NewVD->setInvalidDecl();
5994 return;
5995 }
5996
5997 if (NewVD->isConstexpr() && !T->isDependentType() &&
5998 RequireLiteralType(NewVD->getLocation(), T,
5999 diag::err_constexpr_var_non_literal)) {
Richard Smith27d807c2013-04-30 13:56:41 +00006000 NewVD->setInvalidDecl();
6001 return;
6002 }
6003}
6004
6005/// \brief Perform semantic checking on a newly-created variable
6006/// declaration.
6007///
6008/// This routine performs all of the type-checking required for a
6009/// variable declaration once it has been built. It is used both to
6010/// check variables after they have been parsed and their declarators
6011/// have been translated into a declaration, and to check variables
6012/// that have been instantiated from a template.
6013///
6014/// Sets NewVD->isInvalidDecl() if an error was encountered.
6015///
6016/// Returns true if the variable declaration is a redeclaration.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00006017bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
Richard Smith27d807c2013-04-30 13:56:41 +00006018 CheckVariableDeclarationType(NewVD);
6019
6020 // If the decl is already known invalid, don't check it.
6021 if (NewVD->isInvalidDecl())
6022 return false;
6023
John McCallb65e8fe2013-04-01 18:34:28 +00006024 // If we did not find anything by this name, look for a non-visible
6025 // extern "C" declaration with the same name.
Richard Smith1c34fb72013-08-13 18:18:50 +00006026 if (Previous.empty() &&
6027 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Richard Smith3c785782013-09-03 21:00:58 +00006028 Previous.setShadowed();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006029
Douglas Gregor3552dab2013-01-09 00:47:56 +00006030 // Filter out any non-conflicting previous declarations.
6031 filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6032
John McCall1f82f242009-11-18 22:49:29 +00006033 if (!Previous.empty()) {
Richard Smith3c785782013-09-03 21:00:58 +00006034 MergeVarDecl(NewVD, Previous);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006035 return true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006036 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006037 return false;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00006038}
6039
Douglas Gregor36d1b142009-10-06 17:59:45 +00006040/// \brief Data used with FindOverriddenMethod
6041struct FindOverriddenMethodData {
6042 Sema *S;
6043 CXXMethodDecl *Method;
6044};
6045
6046/// \brief Member lookup function that determines whether a given C++
6047/// method overrides a method in a base class, to be used with
6048/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00006049static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00006050 CXXBasePath &Path,
6051 void *UserData) {
6052 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00006053
Douglas Gregor36d1b142009-10-06 17:59:45 +00006054 FindOverriddenMethodData *Data
6055 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00006056
6057 DeclarationName Name = Data->Method->getDeclName();
6058
6059 // FIXME: Do we care about other names here too?
6060 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00006061 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00006062 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6063 CanQualType CT = Data->S->Context.getCanonicalType(T);
6064
Anders Carlsson5a4f7722009-11-27 01:26:58 +00006065 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00006066 }
6067
6068 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006069 !Path.Decls.empty();
6070 Path.Decls = Path.Decls.slice(1)) {
6071 NamedDecl *D = Path.Decls.front();
John McCalle9cccd82010-06-16 08:42:20 +00006072 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6073 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00006074 return true;
6075 }
6076 }
6077
6078 return false;
6079}
6080
David Blaikie7e414262012-10-17 00:47:58 +00006081namespace {
6082 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6083}
6084/// \brief Report an error regarding overriding, along with any relevant
6085/// overriden methods.
6086///
6087/// \param DiagID the primary error to report.
6088/// \param MD the overriding method.
6089/// \param OEK which overrides to include as notes.
6090static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6091 OverrideErrorKind OEK = OEK_All) {
6092 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6093 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6094 E = MD->end_overridden_methods();
6095 I != E; ++I) {
6096 // This check (& the OEK parameter) could be replaced by a predicate, but
6097 // without lambdas that would be overkill. This is still nicer than writing
6098 // out the diag loop 3 times.
6099 if ((OEK == OEK_All) ||
6100 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6101 (OEK == OEK_Deleted && (*I)->isDeleted()))
6102 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6103 }
6104}
6105
Sebastian Redld5b24532009-11-18 21:51:29 +00006106/// AddOverriddenMethods - See if a method overrides any in the base classes,
6107/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006108bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00006109 // Look for virtual methods in base classes that this method might override.
6110 CXXBasePaths Paths;
6111 FindOverriddenMethodData Data;
6112 Data.Method = MD;
6113 Data.S = this;
David Blaikie7e414262012-10-17 00:47:58 +00006114 bool hasDeletedOverridenMethods = false;
6115 bool hasNonDeletedOverridenMethods = false;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006116 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00006117 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
Aaron Ballmane6f465e2014-03-14 21:38:48 +00006118 for (auto *I : Paths.found_decls()) {
6119 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00006120 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00006121 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Aaron Ballman02df2e02012-12-09 17:45:41 +00006122 !CheckOverridingFunctionAttributes(MD, OldMD) &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00006123 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00006124 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
David Blaikie7e414262012-10-17 00:47:58 +00006125 hasDeletedOverridenMethods |= OldMD->isDeleted();
6126 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006127 AddedAny = true;
6128 }
Sebastian Redld5b24532009-11-18 21:51:29 +00006129 }
6130 }
6131 }
David Blaikie7e414262012-10-17 00:47:58 +00006132
6133 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6134 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6135 }
6136 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6137 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6138 }
6139
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00006140 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00006141}
6142
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006143namespace {
6144 // Struct for holding all of the extra arguments needed by
6145 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6146 struct ActOnFDArgs {
6147 Scope *S;
6148 Declarator &D;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006149 MultiTemplateParamsArg TemplateParamLists;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006150 bool AddToScope;
6151 };
6152}
6153
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006154namespace {
6155
6156// Callback to only accept typo corrections that have a non-zero edit distance.
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006157// Also only accept corrections that have the same parent decl.
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006158class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6159 public:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006160 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6161 CXXRecordDecl *Parent)
6162 : Context(Context), OriginalFD(TypoFD),
Craig Topperc3ec1492014-05-26 06:22:03 +00006163 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006164
Craig Toppere14c0f82014-03-12 04:55:44 +00006165 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006166 if (candidate.getEditDistance() == 0)
6167 return false;
6168
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006169 SmallVector<unsigned, 1> MismatchedParams;
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006170 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6171 CDeclEnd = candidate.end();
6172 CDecl != CDeclEnd; ++CDecl) {
6173 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6174
6175 if (FD && !FD->hasBody() &&
6176 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6177 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6178 CXXRecordDecl *Parent = MD->getParent();
6179 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6180 return true;
6181 } else if (!ExpectedParent) {
6182 return true;
6183 }
6184 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006185 }
6186
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006187 return false;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006188 }
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006189
6190 private:
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006191 ASTContext &Context;
6192 FunctionDecl *OriginalFD;
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006193 CXXRecordDecl *ExpectedParent;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +00006194};
6195
6196}
6197
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006198/// \brief Generate diagnostics for an invalid function redeclaration.
6199///
6200/// This routine handles generating the diagnostic messages for an invalid
6201/// function redeclaration, including finding possible similar declarations
6202/// or performing typo correction if there are no previous declarations with
6203/// the same name.
6204///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006205/// Returns a NamedDecl iff typo correction was performed and substituting in
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006206/// the new declaration name does not cause new errors.
Richard Smith114394f2013-08-09 04:35:01 +00006207static NamedDecl *DiagnoseInvalidRedeclaration(
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006208 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
Richard Smith114394f2013-08-09 04:35:01 +00006209 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006210 DeclarationName Name = NewFD->getDeclName();
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006211 DeclContext *NewDC = NewFD->getDeclContext();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006212 SmallVector<unsigned, 1> MismatchedParams;
6213 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006214 TypoCorrection Correction;
Richard Smithf9b15102013-08-17 00:46:16 +00006215 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
Richard Smith114394f2013-08-09 04:35:01 +00006216 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6217 : diag::err_member_decl_does_not_match;
6218 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6219 IsLocalFriend ? Sema::LookupLocalFriendName
6220 : Sema::LookupOrdinaryName,
6221 Sema::ForRedeclaration);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006222
6223 NewFD->setInvalidDecl();
Richard Smith114394f2013-08-09 04:35:01 +00006224 if (IsLocalFriend)
6225 SemaRef.LookupName(Prev, S);
6226 else
6227 SemaRef.LookupQualifiedName(Prev, NewDC);
John McCallf7cfb222010-10-13 05:45:15 +00006228 assert(!Prev.isAmbiguous() &&
6229 "Cannot have an ambiguity in previous-declaration lookup");
Kaelyn Uhrain7c019172012-02-16 22:40:59 +00006230 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006231 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00006232 MD ? MD->getParent() : nullptr);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006233 if (!Prev.empty()) {
6234 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6235 Func != FuncEnd; ++Func) {
6236 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006237 if (FD &&
6238 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006239 // Add 1 to the index so that 0 can mean the mismatch didn't
6240 // involve a parameter
6241 unsigned ParamNum =
6242 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6243 NearMatches.push_back(std::make_pair(FD, ParamNum));
6244 }
Kaelyn Uhrain7d9bc632011-08-04 17:40:00 +00006245 }
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006246 // If the qualified name lookup yielded nothing, try typo correction
Richard Smith114394f2013-08-09 04:35:01 +00006247 } else if ((Correction = SemaRef.CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00006248 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6249 &ExtraArgs.D.getCXXScopeSpec(), Validator,
Craig Topperc3ec1492014-05-26 06:22:03 +00006250 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006251 // Set up everything for the call to ActOnFunctionDeclarator
6252 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6253 ExtraArgs.D.getIdentifierLoc());
6254 Previous.clear();
6255 Previous.setLookupName(Correction.getCorrection());
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006256 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6257 CDeclEnd = Correction.end();
6258 CDecl != CDeclEnd; ++CDecl) {
6259 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
Kaelyn Uhrain389e9c22012-06-07 23:57:08 +00006260 if (FD && !FD->hasBody() &&
6261 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006262 Previous.addDecl(FD);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006263 }
6264 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006265 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
Richard Smithf9b15102013-08-17 00:46:16 +00006266
6267 NamedDecl *Result;
6268 // Retry building the function declaration with the new previous
6269 // declarations, and with errors suppressed.
6270 {
6271 // Trap errors.
6272 Sema::SFINAETrap Trap(SemaRef);
6273
6274 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6275 // pieces need to verify the typo-corrected C++ declaration and hopefully
6276 // eliminate the need for the parameter pack ExtraArgs.
6277 Result = SemaRef.ActOnFunctionDeclarator(
6278 ExtraArgs.S, ExtraArgs.D,
6279 Correction.getCorrectionDecl()->getDeclContext(),
6280 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6281 ExtraArgs.AddToScope);
6282
6283 if (Trap.hasErrorOccurred())
Craig Topperc3ec1492014-05-26 06:22:03 +00006284 Result = nullptr;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006285 }
Richard Smithf9b15102013-08-17 00:46:16 +00006286
6287 if (Result) {
6288 // Determine which correction we picked.
6289 Decl *Canonical = Result->getCanonicalDecl();
6290 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6291 I != E; ++I)
6292 if ((*I)->getCanonicalDecl() == Canonical)
6293 Correction.setCorrectionDecl(*I);
6294
6295 SemaRef.diagnoseTypo(
6296 Correction,
6297 SemaRef.PDiag(IsLocalFriend
6298 ? diag::err_no_matching_local_friend_suggest
6299 : diag::err_member_decl_does_not_match_suggest)
6300 << Name << NewDC << IsDefinition);
6301 return Result;
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00006302 }
Richard Smithf9b15102013-08-17 00:46:16 +00006303
6304 // Pretend the typo correction never occurred
6305 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6306 ExtraArgs.D.getIdentifierLoc());
6307 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6308 Previous.clear();
6309 Previous.setLookupName(Name);
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006310 }
6311
Richard Smithf9b15102013-08-17 00:46:16 +00006312 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6313 << Name << NewDC << IsDefinition << NewFD->getLocation();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006314
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006315 bool NewFDisConst = false;
6316 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
David Blaikief5697e52012-08-10 00:55:35 +00006317 NewFDisConst = NewMD->isConst();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006318
Craig Topperaf6bd1b2013-07-04 03:15:42 +00006319 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006320 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6321 NearMatch != NearMatchEnd; ++NearMatch) {
6322 FunctionDecl *FD = NearMatch->first;
Richard Smith114394f2013-08-09 04:35:01 +00006323 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6324 bool FDisConst = MD && MD->isConst();
6325 bool IsMember = MD || !IsLocalFriend;
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006326
Richard Smith541b38b2013-09-20 01:15:31 +00006327 // FIXME: These notes are poorly worded for the local friend case.
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006328 if (unsigned Idx = NearMatch->second) {
6329 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006330 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6331 if (Loc.isInvalid()) Loc = FD->getLocation();
Richard Smith114394f2013-08-09 04:35:01 +00006332 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6333 : diag::note_local_decl_close_param_match)
6334 << Idx << FDParam->getType()
6335 << NewFD->getParamDecl(Idx - 1)->getType();
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006336 } else if (FDisConst != NewFDisConst) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00006337 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
Kaelyn Uhrain1a6eb992011-10-10 18:01:37 +00006338 << NewFDisConst << FD->getSourceRange().getEnd();
Kaelyn Uhrainfd81a352011-08-18 18:19:12 +00006339 } else
Richard Smith114394f2013-08-09 04:35:01 +00006340 SemaRef.Diag(FD->getLocation(),
6341 IsMember ? diag::note_member_def_close_match
6342 : diag::note_local_decl_close_match);
John McCallf7cfb222010-10-13 05:45:15 +00006343 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006344 return nullptr;
John McCallf7cfb222010-10-13 05:45:15 +00006345}
6346
David Blaikie30d15442011-10-19 22:56:21 +00006347static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6348 Declarator &D) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006349 switch (D.getDeclSpec().getStorageClassSpec()) {
6350 default: llvm_unreachable("Unknown storage class!");
6351 case DeclSpec::SCS_auto:
6352 case DeclSpec::SCS_register:
6353 case DeclSpec::SCS_mutable:
6354 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6355 diag::err_typecheck_sclass_func);
6356 D.setInvalidType();
6357 break;
6358 case DeclSpec::SCS_unspecified: break;
Rafael Espindolabff59562013-04-25 12:11:36 +00006359 case DeclSpec::SCS_extern:
6360 if (D.getDeclSpec().isExternInLinkageSpec())
6361 return SC_None;
6362 return SC_Extern;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006363 case DeclSpec::SCS_static: {
6364 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6365 // C99 6.7.1p5:
6366 // The declaration of an identifier for a function that has
6367 // block scope shall have no explicit storage-class specifier
6368 // other than extern
6369 // See also (C++ [dcl.stc]p4).
6370 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6371 diag::err_static_block_func);
6372 break;
6373 } else
6374 return SC_Static;
6375 }
6376 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6377 }
6378
6379 // No explicit storage class has already been returned
6380 return SC_None;
6381}
6382
6383static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6384 DeclContext *DC, QualType &R,
6385 TypeSourceInfo *TInfo,
6386 FunctionDecl::StorageClass SC,
6387 bool &IsVirtualOkay) {
6388 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6389 DeclarationName Name = NameInfo.getName();
6390
Craig Topperc3ec1492014-05-26 06:22:03 +00006391 FunctionDecl *NewFD = nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006392 bool isInline = D.getDeclSpec().isInlineSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006393
David Blaikiebbafb8a2012-03-11 07:00:24 +00006394 if (!SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006395 // Determine whether the function was written with a
6396 // prototype. This true when:
6397 // - there is a prototype in the declarator, or
6398 // - the type R of the function is some kind of typedef or other reference
6399 // to a type name (which eventually refers to a function type).
6400 bool HasPrototype =
6401 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6402 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6403
David Blaikie30d15442011-10-19 22:56:21 +00006404 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006405 D.getLocStart(), NameInfo, R,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006406 TInfo, SC, isInline,
6407 HasPrototype, false);
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006408 if (D.isInvalidType())
6409 NewFD->setInvalidDecl();
6410
6411 // Set the lexical context.
6412 NewFD->setLexicalDeclContext(SemaRef.CurContext);
6413
6414 return NewFD;
6415 }
6416
6417 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6418 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6419
6420 // Check that the return type is not an abstract class type.
6421 // For record types, this is done by the AbstractClassUsageDiagnoser once
6422 // the class has been completely parsed.
6423 if (!DC->isRecord() &&
Alp Toker314cc812014-01-25 16:55:45 +00006424 SemaRef.RequireNonAbstractType(
6425 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6426 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006427 D.setInvalidType();
6428
6429 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6430 // This is a C++ constructor declaration.
6431 assert(DC->isRecord() &&
6432 "Constructors can only be declared in a member context");
6433
6434 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6435 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006436 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006437 R, TInfo, isExplicit, isInline,
6438 /*isImplicitlyDeclared=*/false,
6439 isConstexpr);
6440
6441 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6442 // This is a C++ destructor declaration.
6443 if (DC->isRecord()) {
6444 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6445 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6446 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6447 SemaRef.Context, Record,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006448 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006449 NameInfo, R, TInfo, isInline,
6450 /*isImplicitlyDeclared=*/false);
6451
6452 // If the class is complete, then we now create the implicit exception
6453 // specification. If the class is incomplete or dependent, we can't do
6454 // it yet.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006455 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006456 Record->getDefinition() && !Record->isBeingDefined() &&
6457 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6458 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6459 }
6460
6461 IsVirtualOkay = true;
6462 return NewDD;
6463
6464 } else {
6465 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6466 D.setInvalidType();
6467
6468 // Create a FunctionDecl to satisfy the function definition parsing
6469 // code path.
6470 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006471 D.getLocStart(),
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006472 D.getIdentifierLoc(), Name, R, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006473 SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006474 /*hasPrototype=*/true, isConstexpr);
6475 }
6476
6477 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6478 if (!DC->isRecord()) {
6479 SemaRef.Diag(D.getIdentifierLoc(),
6480 diag::err_conv_function_not_member);
Craig Topperc3ec1492014-05-26 06:22:03 +00006481 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006482 }
6483
6484 SemaRef.CheckConversionDeclarator(D, R, SC);
6485 IsVirtualOkay = true;
6486 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006487 D.getLocStart(), NameInfo,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006488 R, TInfo, isInline, isExplicit,
6489 isConstexpr, SourceLocation());
6490
6491 } else if (DC->isRecord()) {
6492 // If the name of the function is the same as the name of the record,
6493 // then this must be an invalid constructor that has a return type.
6494 // (The parser checks for a return type and makes the declarator a
6495 // constructor if it has no return type).
6496 if (Name.getAsIdentifierInfo() &&
6497 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6498 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6499 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6500 << SourceRange(D.getIdentifierLoc());
Craig Topperc3ec1492014-05-26 06:22:03 +00006501 return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006502 }
6503
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006504 // This is a C++ method declaration.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006505 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6506 cast<CXXRecordDecl>(DC),
6507 D.getLocStart(), NameInfo, R,
6508 TInfo, SC, isInline,
6509 isConstexpr, SourceLocation());
6510 IsVirtualOkay = !Ret->isStatic();
6511 return Ret;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006512 } else {
6513 // Determine whether the function was written with a
6514 // prototype. This true when:
6515 // - we're in C++ (where every function has a prototype),
6516 return FunctionDecl::Create(SemaRef.Context, DC,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006517 D.getLocStart(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006518 NameInfo, R, TInfo, SC, isInline,
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006519 true/*HasPrototype*/, isConstexpr);
6520 }
6521}
6522
Matt Arsenaultefb38192013-07-23 01:23:36 +00006523enum OpenCLParamType {
6524 ValidKernelParam,
6525 PtrPtrKernelParam,
6526 PtrKernelParam,
David Tweedababa8f2014-03-27 16:34:11 +00006527 PrivatePtrKernelParam,
Matt Arsenaultefb38192013-07-23 01:23:36 +00006528 InvalidKernelParam,
6529 RecordKernelParam
6530};
6531
6532static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6533 if (PT->isPointerType()) {
6534 QualType PointeeType = PT->getPointeeType();
David Tweedababa8f2014-03-27 16:34:11 +00006535 if (PointeeType->isPointerType())
6536 return PtrPtrKernelParam;
6537 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6538 : PtrKernelParam;
Matt Arsenaultefb38192013-07-23 01:23:36 +00006539 }
6540
6541 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6542 // be used as builtin types.
6543
6544 if (PT->isImageType())
6545 return PtrKernelParam;
6546
6547 if (PT->isBooleanType())
6548 return InvalidKernelParam;
6549
6550 if (PT->isEventT())
6551 return InvalidKernelParam;
6552
6553 if (PT->isHalfType())
6554 return InvalidKernelParam;
6555
6556 if (PT->isRecordType())
6557 return RecordKernelParam;
6558
6559 return ValidKernelParam;
6560}
6561
6562static void checkIsValidOpenCLKernelParameter(
6563 Sema &S,
6564 Declarator &D,
6565 ParmVarDecl *Param,
6566 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6567 QualType PT = Param->getType();
6568
6569 // Cache the valid types we encounter to avoid rechecking structs that are
6570 // used again
6571 if (ValidTypes.count(PT.getTypePtr()))
6572 return;
6573
6574 switch (getOpenCLKernelParameterType(PT)) {
6575 case PtrPtrKernelParam:
6576 // OpenCL v1.2 s6.9.a:
6577 // A kernel function argument cannot be declared as a
6578 // pointer to a pointer type.
6579 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6580 D.setInvalidType();
6581 return;
6582
David Tweedababa8f2014-03-27 16:34:11 +00006583 case PrivatePtrKernelParam:
6584 // OpenCL v1.2 s6.9.a:
6585 // A kernel function argument cannot be declared as a
6586 // pointer to the private address space.
6587 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6588 D.setInvalidType();
6589 return;
6590
Matt Arsenaultefb38192013-07-23 01:23:36 +00006591 // OpenCL v1.2 s6.9.k:
6592 // Arguments to kernel functions in a program cannot be declared with the
6593 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6594 // uintptr_t or a struct and/or union that contain fields declared to be
6595 // one of these built-in scalar types.
6596
6597 case InvalidKernelParam:
6598 // OpenCL v1.2 s6.8 n:
6599 // A kernel function argument cannot be declared
6600 // of event_t type.
6601 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6602 D.setInvalidType();
6603 return;
6604
6605 case PtrKernelParam:
6606 case ValidKernelParam:
6607 ValidTypes.insert(PT.getTypePtr());
6608 return;
6609
6610 case RecordKernelParam:
6611 break;
6612 }
6613
6614 // Track nested structs we will inspect
6615 SmallVector<const Decl *, 4> VisitStack;
6616
6617 // Track where we are in the nested structs. Items will migrate from
6618 // VisitStack to HistoryStack as we do the DFS for bad field.
6619 SmallVector<const FieldDecl *, 4> HistoryStack;
Craig Topperc3ec1492014-05-26 06:22:03 +00006620 HistoryStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006621
6622 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6623 VisitStack.push_back(PD);
6624
6625 assert(VisitStack.back() && "First decl null?");
6626
6627 do {
6628 const Decl *Next = VisitStack.pop_back_val();
6629 if (!Next) {
6630 assert(!HistoryStack.empty());
6631 // Found a marker, we have gone up a level
6632 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6633 ValidTypes.insert(Hist->getType().getTypePtr());
6634
6635 continue;
6636 }
6637
6638 // Adds everything except the original parameter declaration (which is not a
6639 // field itself) to the history stack.
6640 const RecordDecl *RD;
6641 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6642 HistoryStack.push_back(Field);
6643 RD = Field->getType()->castAs<RecordType>()->getDecl();
6644 } else {
6645 RD = cast<RecordDecl>(Next);
6646 }
6647
6648 // Add a null marker so we know when we've gone back up a level
Craig Topperc3ec1492014-05-26 06:22:03 +00006649 VisitStack.push_back(nullptr);
Matt Arsenaultefb38192013-07-23 01:23:36 +00006650
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006651 for (const auto *FD : RD->fields()) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006652 QualType QT = FD->getType();
6653
6654 if (ValidTypes.count(QT.getTypePtr()))
6655 continue;
6656
6657 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6658 if (ParamType == ValidKernelParam)
6659 continue;
6660
6661 if (ParamType == RecordKernelParam) {
6662 VisitStack.push_back(FD);
6663 continue;
6664 }
6665
6666 // OpenCL v1.2 s6.9.p:
6667 // Arguments to kernel functions that are declared to be a struct or union
6668 // do not allow OpenCL objects to be passed as elements of the struct or
6669 // union.
David Tweedababa8f2014-03-27 16:34:11 +00006670 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6671 ParamType == PrivatePtrKernelParam) {
Matt Arsenaultefb38192013-07-23 01:23:36 +00006672 S.Diag(Param->getLocation(),
6673 diag::err_record_with_pointers_kernel_param)
6674 << PT->isUnionType()
6675 << PT;
6676 } else {
6677 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6678 }
6679
6680 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6681 << PD->getDeclName();
6682
6683 // We have an error, now let's go back up through history and show where
6684 // the offending field came from
6685 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6686 E = HistoryStack.end(); I != E; ++I) {
6687 const FieldDecl *OuterField = *I;
6688 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6689 << OuterField->getType();
6690 }
6691
6692 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6693 << QT->isPointerType()
6694 << QT;
6695 D.setInvalidType();
6696 return;
6697 }
6698 } while (!VisitStack.empty());
6699}
6700
Mike Stump11289f42009-09-09 15:08:12 +00006701NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00006702Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006703 TypeSourceInfo *TInfo, LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006704 MultiTemplateParamsArg TemplateParamLists,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006705 bool &AddToScope) {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006706 QualType R = TInfo->getType();
6707
Zhongxing Xubece5d62009-01-16 01:13:29 +00006708 assert(R.getTypePtr()->isFunctionType());
6709
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006710 // TODO: consider using NameInfo for diagnostic.
6711 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6712 DeclarationName Name = NameInfo.getName();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006713 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
Zhongxing Xubece5d62009-01-16 01:13:29 +00006714
Richard Smithb4a9e862013-04-12 22:46:28 +00006715 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6716 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6717 diag::err_invalid_thread)
6718 << DeclSpec::getSpecifierName(TSCS);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006719
Reid Kleckner9a7f3e62013-10-08 00:58:57 +00006720 if (D.isFirstDeclarationOfMember())
6721 adjustMemberFunctionCC(R, D.isStaticMember());
Reid Kleckner78af0702013-08-27 23:08:25 +00006722
Douglas Gregor513e63c2010-12-10 19:28:19 +00006723 bool isFriend = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00006724 FunctionTemplateDecl *FunctionTemplate = nullptr;
Douglas Gregor513e63c2010-12-10 19:28:19 +00006725 bool isExplicitSpecialization = false;
6726 bool isFunctionTemplateSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006727
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006728 bool isDependentClassScopeExplicitSpecialization = false;
Nico Weber7b5a7162012-06-25 17:21:05 +00006729 bool HasExplicitTemplateArgs = false;
6730 TemplateArgumentListInfo TemplateArgs;
6731
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006732 bool isVirtualOkay = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006733
Richard Smith541b38b2013-09-20 01:15:31 +00006734 DeclContext *OriginalDC = DC;
6735 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6736
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006737 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6738 isVirtualOkay);
Craig Topperc3ec1492014-05-26 06:22:03 +00006739 if (!NewFD) return nullptr;
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006740
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00006741 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6742 NewFD->setTopLevelDeclInObjCContainer();
6743
Richard Smith541b38b2013-09-20 01:15:31 +00006744 // Set the lexical context. If this is a function-scope declaration, or has a
6745 // C++ scope specifier, or is the object of a friend declaration, the lexical
6746 // context will be different from the semantic context.
6747 NewFD->setLexicalDeclContext(CurContext);
6748
6749 if (IsLocalExternDecl)
6750 NewFD->setLocalExternDecl();
6751
David Blaikiebbafb8a2012-03-11 07:00:24 +00006752 if (getLangOpts().CPlusPlus) {
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006753 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00006754 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6755 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
Richard Smitha77a0a62011-08-15 21:04:07 +00006756 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006757 isFriend = D.getDeclSpec().isFriendSpecified();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00006758 if (isFriend && !isInline && D.isFunctionDefinition()) {
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00006759 // C++ [class.friend]p5
6760 // A function can be defined in a friend declaration of a
6761 // class . . . . Such a function is implicitly inline.
6762 NewFD->setImplicitlyInline();
6763 }
6764
John McCalldb632ac2012-09-25 07:32:39 +00006765 // If this is a method defined in an __interface, and is not a constructor
6766 // or an overloaded operator, then set the pure flag (isVirtual will already
6767 // return true).
6768 if (const CXXRecordDecl *Parent =
6769 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6770 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
Joao Matosdc86f942012-08-31 18:45:21 +00006771 NewFD->setPure(true);
6772 }
6773
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006774 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006775 isExplicitSpecialization = false;
6776 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006777 if (D.isInvalidType())
6778 NewFD->setInvalidDecl();
Richard Smith541b38b2013-09-20 01:15:31 +00006779
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006780 // Match up the template parameter lists with the scope specifier, then
6781 // determine whether we have a template or a template specialization.
6782 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006783 if (TemplateParameterList *TemplateParams =
6784 MatchTemplateParametersToScopeSpecifier(
6785 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
Richard Smith4b55a9c2014-04-17 03:29:33 +00006786 D.getCXXScopeSpec(),
6787 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6788 ? D.getName().TemplateId
Craig Topperc3ec1492014-05-26 06:22:03 +00006789 : nullptr,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006790 TemplateParamLists, isFriend, isExplicitSpecialization,
6791 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00006792 if (TemplateParams->size() > 0) {
6793 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006794
Abramo Bagnara60804e12011-03-18 15:16:37 +00006795 // Check that we can declare a template here.
6796 if (CheckTemplateDeclScope(S, TemplateParams))
Craig Topperc3ec1492014-05-26 06:22:03 +00006797 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006798
Abramo Bagnara60804e12011-03-18 15:16:37 +00006799 // A destructor cannot be a template.
6800 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6801 Diag(NewFD->getLocation(), diag::err_destructor_template);
Craig Topperc3ec1492014-05-26 06:22:03 +00006802 return nullptr;
John McCall1f0479e2010-03-24 08:27:58 +00006803 }
Douglas Gregor041b0842011-10-14 15:31:12 +00006804
6805 // If we're adding a template to a dependent context, we may need to
David Blaikie30d15442011-10-19 22:56:21 +00006806 // rebuilding some of the types used within the template parameter list,
Douglas Gregor041b0842011-10-14 15:31:12 +00006807 // now that we know what the current instantiation is.
6808 if (DC->isDependentContext()) {
6809 ContextRAII SavedContext(*this, DC);
6810 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6811 Invalid = true;
6812 }
6813
John McCall1f0479e2010-03-24 08:27:58 +00006814
Abramo Bagnara60804e12011-03-18 15:16:37 +00006815 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6816 NewFD->getLocation(),
6817 Name, TemplateParams,
6818 NewFD);
6819 FunctionTemplate->setLexicalDeclContext(CurContext);
6820 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6821
6822 // For source fidelity, store the other template param lists.
6823 if (TemplateParamLists.size() > 1) {
6824 NewFD->setTemplateParameterListsInfo(Context,
6825 TemplateParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006826 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006827 }
6828 } else {
6829 // This is a function template specialization.
6830 isFunctionTemplateSpecialization = true;
6831 // For source fidelity, store all the template param lists.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006832 if (TemplateParamLists.size() > 0)
6833 NewFD->setTemplateParameterListsInfo(Context,
6834 TemplateParamLists.size(),
6835 TemplateParamLists.data());
Abramo Bagnara60804e12011-03-18 15:16:37 +00006836
6837 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6838 if (isFriend) {
6839 // We want to remove the "template<>", found here.
6840 SourceRange RemoveRange = TemplateParams->getSourceRange();
6841
6842 // If we remove the template<> and the name is not a
6843 // template-id, we're actually silently creating a problem:
6844 // the friend declaration will refer to an untemplated decl,
6845 // and clearly the user wants a template specialization. So
6846 // we need to insert '<>' after the name.
6847 SourceLocation InsertLoc;
6848 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6849 InsertLoc = D.getName().getSourceRange().getEnd();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006850 InsertLoc = getLocForEndOfToken(InsertLoc);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006851 }
6852
6853 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6854 << Name << RemoveRange
6855 << FixItHint::CreateRemoval(RemoveRange)
6856 << FixItHint::CreateInsertion(InsertLoc, "<>");
6857 }
6858 }
6859 }
6860 else {
6861 // All template param lists were matched against the scope specifier:
6862 // this is NOT (an explicit specialization of) a template.
6863 if (TemplateParamLists.size() > 0)
6864 // For source fidelity, store all the template param lists.
6865 NewFD->setTemplateParameterListsInfo(Context,
6866 TemplateParamLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006867 TemplateParamLists.data());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006868 }
6869
6870 if (Invalid) {
6871 NewFD->setInvalidDecl();
6872 if (FunctionTemplate)
6873 FunctionTemplate->setInvalidDecl();
6874 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006875
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006876 // C++ [dcl.fct.spec]p5:
6877 // The virtual specifier shall only be used in declarations of
6878 // nonstatic class member functions that appear within a
6879 // member-specification of a class declaration; see 10.3.
6880 //
6881 if (isVirtual && !NewFD->isInvalidDecl()) {
6882 if (!isVirtualOkay) {
6883 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6884 diag::err_virtual_non_function);
6885 } else if (!CurContext->isRecord()) {
6886 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00006887 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6888 diag::err_virtual_out_of_class)
6889 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6890 } else if (NewFD->getDescribedFunctionTemplate()) {
6891 // C++ [temp.mem]p3:
6892 // A member function template shall not be virtual.
6893 Diag(D.getDeclSpec().getVirtualSpecLoc(),
6894 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006895 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6896 } else {
6897 // Okay: Add virtual to the method.
6898 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00006899 }
Richard Smith2a7d4812013-05-04 07:00:32 +00006900
6901 if (getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00006902 NewFD->getReturnType()->isUndeducedType())
Richard Smith2a7d4812013-05-04 07:00:32 +00006903 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
Douglas Gregorc1da0f02009-06-24 00:23:40 +00006904 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006905
Richard Smithc1564702013-11-15 02:58:23 +00006906 if (getLangOpts().CPlusPlus1y &&
6907 (NewFD->isDependentContext() ||
6908 (isFriend && CurContext->isDependentContext())) &&
Alp Toker314cc812014-01-25 16:55:45 +00006909 NewFD->getReturnType()->isUndeducedType()) {
Richard Smithc58f38f2013-08-14 20:16:31 +00006910 // If the function template is referenced directly (for instance, as a
6911 // member of the current instantiation), pretend it has a dependent type.
6912 // This is not really justified by the standard, but is the only sane
6913 // thing to do.
Richard Smithc1564702013-11-15 02:58:23 +00006914 // FIXME: For a friend function, we have not marked the function as being
6915 // a friend yet, so 'isDependentContext' on the FD doesn't work.
Richard Smithc58f38f2013-08-14 20:16:31 +00006916 const FunctionProtoType *FPT =
6917 NewFD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006918 QualType Result =
6919 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00006920 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smithc58f38f2013-08-14 20:16:31 +00006921 FPT->getExtProtoInfo()));
6922 }
6923
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006924 // C++ [dcl.fct.spec]p3:
David Blaikie30d15442011-10-19 22:56:21 +00006925 // The inline specifier shall not appear on a block scope function
6926 // declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006927 if (isInline && !NewFD->isInvalidDecl()) {
6928 if (CurContext->isFunctionOrMethod()) {
6929 // 'inline' is not allowed on block scope function declaration.
6930 Diag(D.getDeclSpec().getInlineSpecLoc(),
6931 diag::err_inline_declaration_block_scope) << Name
6932 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6933 }
6934 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00006935
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006936 // C++ [dcl.fct.spec]p6:
6937 // The explicit specifier shall be used only in the declaration of a
David Blaikie30d15442011-10-19 22:56:21 +00006938 // constructor or conversion function within its class definition;
6939 // see 12.3.1 and 12.3.2.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006940 if (isExplicit && !NewFD->isInvalidDecl()) {
6941 if (!CurContext->isRecord()) {
6942 // 'explicit' was specified outside of the class.
6943 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6944 diag::err_explicit_out_of_class)
6945 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6946 } else if (!isa<CXXConstructorDecl>(NewFD) &&
6947 !isa<CXXConversionDecl>(NewFD)) {
6948 // 'explicit' was specified on a function that wasn't a constructor
6949 // or conversion function.
6950 Diag(D.getDeclSpec().getExplicitSpecLoc(),
6951 diag::err_explicit_non_ctor_or_conv_function)
6952 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6953 }
6954 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006955
Richard Smitha77a0a62011-08-15 21:04:07 +00006956 if (isConstexpr) {
Richard Smith574f4f62013-01-14 05:37:29 +00006957 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
Richard Smitha77a0a62011-08-15 21:04:07 +00006958 // are implicitly inline.
6959 NewFD->setImplicitlyInline();
6960
Richard Smith574f4f62013-01-14 05:37:29 +00006961 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
Richard Smitha77a0a62011-08-15 21:04:07 +00006962 // be either constructors or to return a literal type. Therefore,
6963 // destructors cannot be declared constexpr.
6964 if (isa<CXXDestructorDecl>(NewFD))
Richard Smitheb3c10c2011-10-01 02:31:28 +00006965 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
Richard Smitha77a0a62011-08-15 21:04:07 +00006966 }
6967
Douglas Gregor26701a42011-09-09 02:06:17 +00006968 // If __module_private__ was specified, mark the function accordingly.
6969 if (D.getDeclSpec().isModulePrivateSpecified()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006970 if (isFunctionTemplateSpecialization) {
6971 SourceLocation ModulePrivateLoc
6972 = D.getDeclSpec().getModulePrivateSpecLoc();
6973 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6974 << 0
6975 << FixItHint::CreateRemoval(ModulePrivateLoc);
6976 } else {
6977 NewFD->setModulePrivate();
6978 if (FunctionTemplate)
6979 FunctionTemplate->setModulePrivate();
6980 }
Douglas Gregor26701a42011-09-09 02:06:17 +00006981 }
Richard Smitha77a0a62011-08-15 21:04:07 +00006982
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006983 if (isFriend) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006984 if (FunctionTemplate) {
Richard Smith64017682013-07-17 23:53:16 +00006985 FunctionTemplate->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006986 FunctionTemplate->setAccess(AS_public);
6987 }
Richard Smith64017682013-07-17 23:53:16 +00006988 NewFD->setObjectOfFriendDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00006989 NewFD->setAccess(AS_public);
6990 }
6991
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006992 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithb63b6ee2014-01-22 01:43:19 +00006993 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6994 // definition kind to FDK_Definition.
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006995 switch (D.getFunctionDefinitionKind()) {
6996 case FDK_Declaration:
6997 case FDK_Definition:
6998 break;
6999
7000 case FDK_Defaulted:
7001 NewFD->setDefaulted();
7002 break;
7003
7004 case FDK_Deleted:
7005 NewFD->setDeletedAsWritten();
7006 break;
7007 }
7008
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007009 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7010 D.isFunctionDefinition()) {
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00007011 // C++ [class.mfct]p2:
7012 // A member function may be defined (8.4) in its class definition, in
7013 // which case it is an inline member function (7.1.2)
John McCall357d0f32010-12-15 04:00:32 +00007014 NewFD->setImplicitlyInline();
7015 }
7016
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007017 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7018 !CurContext->isRecord()) {
7019 // C++ [class.static]p1:
7020 // A data or function member of a class may be declared static
7021 // in a class definition, in which case it is a static member of
7022 // the class.
7023
7024 // Complain about the 'static' specifier if it's on an out-of-line
7025 // member function definition.
7026 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7027 diag::err_static_out_of_line)
7028 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7029 }
Richard Smith66f3ac92012-10-20 08:26:51 +00007030
7031 // C++11 [except.spec]p15:
7032 // A deallocation function with no exception-specification is treated
7033 // as if it were specified with noexcept(true).
7034 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7035 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7036 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007037 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
Richard Smith66f3ac92012-10-20 08:26:51 +00007038 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7039 EPI.ExceptionSpecType = EST_BasicNoexcept;
Alp Toker314cc812014-01-25 16:55:45 +00007040 NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007041 FPT->getParamTypes(), EPI));
Richard Smith66f3ac92012-10-20 08:26:51 +00007042 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00007043 }
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007044
7045 // Filter out previous declarations that don't match the scope.
Richard Smith541b38b2013-09-20 01:15:31 +00007046 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
Richard Smith72bcaec2013-12-05 04:30:04 +00007047 D.getCXXScopeSpec().isNotEmpty() ||
Kaelyn Uhraine1a9ff72011-10-11 00:28:49 +00007048 isExplicitSpecialization ||
7049 isFunctionTemplateSpecialization);
Richard Smith1c34fb72013-08-13 18:18:50 +00007050
Zhongxing Xubece5d62009-01-16 01:13:29 +00007051 // Handle GNU asm-label extension (encoded as an attribute).
7052 if (Expr *E = (Expr*) D.getAsmLabel()) {
7053 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00007054 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00007055 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00007056 SE->getString(), 0));
David Chisnall0867d9c2012-02-18 16:12:34 +00007057 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7058 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7059 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7060 if (I != ExtnameUndeclaredIdentifiers.end()) {
7061 NewFD->addAttr(I->second);
7062 ExtnameUndeclaredIdentifiers.erase(I);
7063 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007064 }
7065
Chris Lattner9af40c12009-04-25 06:12:16 +00007066 // Copy the parameter declarations from the declarator D to the function
7067 // declaration NewFD, if they are available. First scavenge them into Params.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007068 SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00007069 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007070 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00007071
Zhongxing Xubece5d62009-01-16 01:13:29 +00007072 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7073 // function that takes no arguments, not a function that takes a
7074 // single void argument.
7075 // We let through "const void" here because Sema::GetTypeForDeclarator
7076 // already checks for that case.
Alp Toker4284c6e2014-05-11 16:05:55 +00007077 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
Alp Tokerc5350722014-02-26 22:27:52 +00007078 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7079 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007080 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7081 Param->setDeclContext(NewFD);
7082 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00007083
7084 if (Param->isInvalidDecl())
7085 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007086 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007087 }
Mike Stump11289f42009-09-09 15:08:12 +00007088
John McCall9dd450b2009-09-21 23:43:11 +00007089 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00007090 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00007091 // following example, we'll need to synthesize (unnamed)
7092 // parameters for use in the declaration.
7093 //
7094 // @code
7095 // typedef void fn(int);
7096 // fn f;
7097 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00007098
Chris Lattner47c0d002009-04-25 06:03:53 +00007099 // Synthesize a parameter for each argument type.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007100 for (const auto &AI : FT->param_types()) {
John McCalla3ccba02010-06-04 11:21:44 +00007101 ParmVarDecl *Param =
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007102 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00007103 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00007104 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00007105 }
Chris Lattner49303b22009-04-25 18:38:18 +00007106 } else {
7107 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7108 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00007109 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00007110
Chris Lattner9af40c12009-04-25 06:12:16 +00007111 // Finally, we know we have the right number of parameters, install them.
David Blaikie9c70e042011-09-21 18:16:56 +00007112 NewFD->setParams(Params);
Mike Stump11289f42009-09-09 15:08:12 +00007113
James Molloy6f8780b2012-02-29 10:24:19 +00007114 // Find all anonymous symbols defined during the declaration of this function
7115 // and add to NewFD. This lets us track decls such 'enum Y' in:
7116 //
7117 // void f(enum Y {AA} x) {}
7118 //
7119 // which would otherwise incorrectly end up in the translation unit scope.
7120 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7121 DeclsInPrototypeScope.clear();
7122
Richard Smithdebc59d2013-01-30 05:45:05 +00007123 if (D.getDeclSpec().isNoreturnSpecified())
7124 NewFD->addAttr(
7125 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
Aaron Ballman36a53502014-01-16 13:03:14 +00007126 Context, 0));
Richard Smithdebc59d2013-01-30 05:45:05 +00007127
Richard Smith84208dc2012-03-13 05:56:40 +00007128 // Functions returning a variably modified type violate C99 6.7.5.2p2
7129 // because all functions have linkage.
7130 if (!NewFD->isInvalidDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +00007131 NewFD->getReturnType()->isVariablyModifiedType()) {
Richard Smith84208dc2012-03-13 05:56:40 +00007132 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7133 NewFD->setInvalidDecl();
7134 }
7135
Warren Huntc3b18962014-04-08 22:30:47 +00007136 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7137 !NewFD->hasAttr<SectionAttr>()) {
7138 NewFD->addAttr(
7139 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7140 CodeSegStack.CurrentValue->getString(),
7141 CodeSegStack.CurrentPragmaLocation));
7142 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7143 PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
7144 NewFD->dropAttr<SectionAttr>();
7145 }
7146
Rafael Espindolac67f2232012-05-10 02:50:16 +00007147 // Handle attributes.
Richard Smithf8a75c32013-08-29 00:47:48 +00007148 ProcessDeclAttributes(S, NewFD, D);
Rafael Espindolac67f2232012-05-10 02:50:16 +00007149
Alp Toker314cc812014-01-25 16:55:45 +00007150 QualType RetType = NewFD->getReturnType();
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007151 const CXXRecordDecl *Ret = RetType->isRecordType() ?
7152 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7153 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7154 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
Kaelyn Uhrain11370012012-11-13 21:23:31 +00007155 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
David Blaikie080a61c2014-02-09 07:24:41 +00007156 // Attach WarnUnusedResult to functions returning types with that attribute.
7157 // Don't apply the attribute to that type's own non-static member functions
7158 // (to avoid warning on things like assignment operators)
7159 if (!MD || MD->getParent() != Ret)
Aaron Ballman36a53502014-01-16 13:03:14 +00007160 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
Kaelyn Uhrain8681f9d2012-11-12 23:48:05 +00007161 }
7162
Joey Gouly16cb99d2014-01-06 11:26:18 +00007163 if (getLangOpts().OpenCL) {
7164 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7165 // type declaration will generate a compilation error.
7166 unsigned AddressSpace = RetType.getAddressSpace();
7167 if (AddressSpace == LangAS::opencl_local ||
7168 AddressSpace == LangAS::opencl_global ||
7169 AddressSpace == LangAS::opencl_constant) {
7170 Diag(NewFD->getLocation(),
7171 diag::err_opencl_return_value_with_address_space);
7172 NewFD->setInvalidDecl();
7173 }
7174 }
7175
David Blaikiebbafb8a2012-03-11 07:00:24 +00007176 if (!getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007177 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007178 bool isExplicitSpecialization=false;
David Majnemer027f9c42013-07-06 02:13:46 +00007179 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7180 CheckMain(NewFD, D.getDeclSpec());
7181
David Majnemerc729b0b2013-09-16 22:44:20 +00007182 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7183 CheckMSVCRTEntryPoint(NewFD);
7184
David Majnemer027f9c42013-07-06 02:13:46 +00007185 if (!NewFD->isInvalidDecl())
Richard Smith84208dc2012-03-13 05:56:40 +00007186 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7187 isExplicitSpecialization));
Fariborz Jahanianaaf376b2012-09-05 17:52:12 +00007188 else if (!Previous.empty())
Richard Smith1c34fb72013-08-13 18:18:50 +00007189 // Make graceful recovery from an invalid redeclaration.
7190 D.setRedeclaration(true);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007191 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007192 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7193 "previous declaration set still overloaded");
7194 } else {
Richard Smithfa27bc42013-11-16 01:57:09 +00007195 // C++11 [replacement.functions]p3:
7196 // The program's definitions shall not be specified as inline.
7197 //
7198 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7199 //
7200 // Suppress the diagnostic if the function is __attribute__((used)), since
7201 // that forces an external definition to be emitted.
7202 if (D.getDeclSpec().isInlineSpecified() &&
7203 NewFD->isReplaceableGlobalAllocationFunction() &&
7204 !NewFD->hasAttr<UsedAttr>())
7205 Diag(D.getDeclSpec().getInlineSpecLoc(),
7206 diag::ext_operator_new_delete_declared_inline)
7207 << NewFD->getDeclName();
7208
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007209 // If the declarator is a template-id, translate the parser's template
7210 // argument list into our AST format.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007211 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7212 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7213 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7214 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007215 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007216 TemplateId->NumArgs);
7217 translateTemplateArguments(TemplateArgsPtr,
7218 TemplateArgs);
Douglas Gregor0e876e02009-09-25 23:53:26 +00007219
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007220 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00007221
Douglas Gregor522d5eb2011-06-06 15:22:55 +00007222 if (NewFD->isInvalidDecl()) {
7223 HasExplicitTemplateArgs = false;
7224 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00007225 // Function template with explicit template arguments.
7226 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7227 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7228
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007229 HasExplicitTemplateArgs = false;
John McCallf7cfb222010-10-13 05:45:15 +00007230 } else {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007231 assert((isFunctionTemplateSpecialization ||
7232 D.getDeclSpec().isFriendSpecified()) &&
7233 "should have a 'template<>' for this decl");
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007234 // "friend void foo<>(int);" is an implicit specialization decl.
7235 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00007236 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007237 } else if (isFriend && isFunctionTemplateSpecialization) {
7238 // This combination is only possible in a recovery case; the user
7239 // wrote something like:
7240 // template <> friend void foo(int);
7241 // which we're recovering from as if the user had written:
7242 // friend void foo<>(int);
7243 // Go ahead and fake up a template id.
7244 HasExplicitTemplateArgs = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00007245 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007246 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007247 }
John McCallf7cfb222010-10-13 05:45:15 +00007248
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007249 // If it's a friend (and only if it's a friend), it's possible
7250 // that either the specialized function type or the specialized
7251 // template is dependent, and therefore matching will fail. In
7252 // this case, don't check the specialization yet.
Douglas Gregore9d075e2011-10-09 20:59:17 +00007253 bool InstantiationDependent = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007254 if (isFunctionTemplateSpecialization && isFriend &&
Douglas Gregore9d075e2011-10-09 20:59:17 +00007255 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7256 TemplateSpecializationType::anyDependentTemplateArguments(
7257 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7258 InstantiationDependent))) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007259 assert(HasExplicitTemplateArgs &&
7260 "friend function specialization without template args");
7261 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7262 Previous))
7263 NewFD->setInvalidDecl();
7264 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00007265 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00007266 && !isFriend) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007267 isDependentClassScopeExplicitSpecialization = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007268 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007269 diag::ext_function_specialization_in_class :
7270 diag::err_function_specialization_in_class)
Douglas Gregor63fab342011-03-16 19:27:09 +00007271 << NewFD->getDeclName();
Douglas Gregor63fab342011-03-16 19:27:09 +00007272 } else if (CheckFunctionTemplateSpecialization(NewFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00007273 (HasExplicitTemplateArgs ? &TemplateArgs
7274 : nullptr),
Douglas Gregor63fab342011-03-16 19:27:09 +00007275 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007276 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007277
7278 // C++ [dcl.stc]p1:
7279 // A storage-class-specifier shall not be specified in an explicit
7280 // specialization (14.7.3)
Richard Trieub48e62f2013-05-16 02:14:08 +00007281 FunctionTemplateSpecializationInfo *Info =
7282 NewFD->getTemplateSpecializationInfo();
7283 if (Info && SC != SC_None) {
7284 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Douglas Gregor84265a02011-06-17 05:09:08 +00007285 Diag(NewFD->getLocation(),
7286 diag::err_explicit_specialization_inconsistent_storage_class)
7287 << SC
7288 << FixItHint::CreateRemoval(
7289 D.getDeclSpec().getStorageClassSpecLoc());
7290
7291 else
7292 Diag(NewFD->getLocation(),
7293 diag::ext_explicit_specialization_storage_class)
7294 << FixItHint::CreateRemoval(
7295 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007296 }
7297
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007298 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7299 if (CheckMemberSpecialization(NewFD, Previous))
7300 NewFD->setInvalidDecl();
7301 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007302
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007303 // Perform semantic checking on the function declaration.
David Blaikied937bf12011-09-08 06:33:04 +00007304 if (!isDependentClassScopeExplicitSpecialization) {
David Majnemer027f9c42013-07-06 02:13:46 +00007305 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7306 CheckMain(NewFD, D.getDeclSpec());
7307
David Majnemerc729b0b2013-09-16 22:44:20 +00007308 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7309 CheckMSVCRTEntryPoint(NewFD);
7310
Nico Weber7607fce2013-12-21 00:49:51 +00007311 if (!NewFD->isInvalidDecl())
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007312 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7313 isExplicitSpecialization));
David Blaikied937bf12011-09-08 06:33:04 +00007314 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007315
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007316 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007317 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7318 "previous declaration set still overloaded");
7319
7320 NamedDecl *PrincipalDecl = (FunctionTemplate
7321 ? cast<NamedDecl>(FunctionTemplate)
7322 : NewFD);
7323
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007324 if (isFriend && D.isRedeclaration()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007325 AccessSpecifier Access = AS_public;
7326 if (!NewFD->isInvalidDecl())
Douglas Gregorec9fd132012-01-14 16:38:05 +00007327 Access = NewFD->getPreviousDecl()->getAccess();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007328
7329 NewFD->setAccess(Access);
7330 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007331 }
7332
7333 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7334 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7335 PrincipalDecl->setNonMemberOperator();
7336
7337 // If we have a function template, check the template parameter
7338 // list. This will check and merge default template arguments.
7339 if (FunctionTemplate) {
David Blaikie30d15442011-10-19 22:56:21 +00007340 FunctionTemplateDecl *PrevTemplate =
Douglas Gregorec9fd132012-01-14 16:38:05 +00007341 FunctionTemplate->getPreviousDecl();
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007342 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007343 PrevTemplate ? PrevTemplate->getTemplateParameters()
7344 : nullptr,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007345 D.getDeclSpec().isFriendSpecified()
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007346 ? (D.isFunctionDefinition()
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007347 ? TPC_FriendFunctionTemplateDefinition
7348 : TPC_FriendFunctionTemplate)
7349 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00007350 DC && DC->isRecord() &&
7351 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00007352 ? TPC_ClassTemplateMember
7353 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007354 }
7355
7356 if (NewFD->isInvalidDecl()) {
7357 // Ignore all the rest of this.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007358 } else if (!D.isRedeclaration()) {
Kaelyn Uhrain8af2c9f2011-10-11 00:28:52 +00007359 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007360 AddToScope };
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007361 // Fake up an access specifier if it's supposed to be a class member.
7362 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7363 NewFD->setAccess(AS_public);
7364
7365 // Qualified decls generally require a previous declaration.
7366 if (D.getCXXScopeSpec().isSet()) {
7367 // ...with the major exception of templated-scope or
7368 // dependent-scope friend declarations.
7369
7370 // TODO: we currently also suppress this check in dependent
7371 // contexts because (1) the parameter depth will be off when
7372 // matching friend templates and (2) we might actually be
7373 // selecting a friend based on a dependent factor. But there
7374 // are situations where these conditions don't apply and we
7375 // can actually do this check immediately.
7376 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00007377 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007378 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7379 CurContext->isDependentContext())) {
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007380 // ignore these
7381 } else {
7382 // The user tried to provide an out-of-line definition for a
7383 // function that is a member of a class or namespace, but there
7384 // was no such member function declared (C++ [class.mfct]p2,
7385 // C++ [namespace.memdef]p2). For example:
7386 //
7387 // class X {
7388 // void f() const;
7389 // };
7390 //
7391 // void X::f() { } // ill-formed
7392 //
7393 // Complain about this problem, and attempt to suggest close
7394 // matches (e.g., those that differ only in cv-qualifiers and
7395 // whether the parameter types are references).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007396
Richard Smith114394f2013-08-09 04:35:01 +00007397 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
Craig Topperc3ec1492014-05-26 06:22:03 +00007398 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007399 AddToScope = ExtraArgs.AddToScope;
7400 return Result;
7401 }
Chandler Carruthf8b554f2011-08-19 01:38:33 +00007402 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007403
7404 // Unqualified local friend declarations are required to resolve
7405 // to something.
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007406 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
Richard Smith114394f2013-08-09 04:35:01 +00007407 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7408 *this, Previous, NewFD, ExtraArgs, true, S)) {
Kaelyn Uhrain0a32fca2011-10-11 00:28:39 +00007409 AddToScope = ExtraArgs.AddToScope;
7410 return Result;
7411 }
Chandler Carruthe92e42f2011-08-19 01:40:11 +00007412 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007413
Richard Smitha2302242013-12-05 07:51:02 +00007414 } else if (!D.isFunctionDefinition() &&
7415 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007416 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00007417 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007418 // An out-of-line member function declaration must also be a
Richard Smitha2302242013-12-05 07:51:02 +00007419 // definition (C++ [class.mfct]p2).
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007420 // Note that this is not the case for explicit specializations of
7421 // function templates or member functions of class templates, per
David Blaikie30d15442011-10-19 22:56:21 +00007422 // C++ [temp.expl.spec]p2. We also allow these declarations as an
7423 // extension for compatibility with old SWIG code which likes to
7424 // generate them.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007425 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7426 << D.getCXXScopeSpec().getRange();
7427 }
7428 }
Ryan Flynne5dc8592009-07-25 22:29:44 +00007429
Rafael Espindolade6a39f2013-03-02 21:41:48 +00007430 ProcessPragmaWeak(S, NewFD);
Rafael Espindolaf1d2f0e2013-01-16 23:11:15 +00007431 checkAttributesAfterMerging(*this, *NewFD);
7432
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007433 AddKnownFunctionAttributes(NewFD);
7434
Douglas Gregor72609052010-08-06 13:50:58 +00007435 if (NewFD->hasAttr<OverloadableAttr>() &&
7436 !NewFD->getType()->getAs<FunctionProtoType>()) {
7437 Diag(NewFD->getLocation(),
7438 diag::err_attribute_overloadable_no_prototype)
7439 << NewFD;
7440
7441 // Turn this into a variadic function with no parameters.
7442 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
Reid Kleckner78af0702013-08-27 23:08:25 +00007443 FunctionProtoType::ExtProtoInfo EPI(
7444 Context.getDefaultCallingConvention(true, false));
John McCalldb40c7f2010-12-14 08:05:40 +00007445 EPI.Variadic = true;
7446 EPI.ExtInfo = FT->getExtInfo();
7447
Alp Toker314cc812014-01-25 16:55:45 +00007448 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00007449 NewFD->setType(R);
7450 }
7451
Eli Friedman570024a2010-08-05 06:57:20 +00007452 // If there's a #pragma GCC visibility in scope, and this isn't a class
7453 // member, set the visibility of this function.
Rafael Espindola3ae00052013-05-13 00:12:11 +00007454 if (!DC->isRecord() && NewFD->isExternallyVisible())
Eli Friedman570024a2010-08-05 06:57:20 +00007455 AddPushedVisibilityAttribute(NewFD);
7456
John McCall32f5fe12011-09-30 05:12:12 +00007457 // If there's a #pragma clang arc_cf_code_audited in scope, consider
7458 // marking the function.
7459 AddCFAuditedAttribute(NewFD);
7460
Dario Domizioli13a0a382014-05-23 12:13:25 +00007461 // If this is a function definition, check if we have to apply optnone due to
7462 // a pragma.
7463 if(D.isFunctionDefinition())
7464 AddRangeBasedOptnone(NewFD);
7465
Richard Smithac974a32013-06-30 09:48:50 +00007466 // If this is the first declaration of an extern C variable, update
7467 // the map of such variables.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00007468 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
Richard Smithac974a32013-06-30 09:48:50 +00007469 isIncompleteDeclExternC(*this, NewFD))
Richard Smith39b79682013-06-18 20:15:12 +00007470 RegisterLocallyScopedExternCDecl(NewFD, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007471
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007472 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00007473 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00007474
Nico Rieck82f0b062014-03-31 14:56:15 +00007475 if (D.isRedeclaration() && !Previous.empty()) {
7476 checkDLLAttributeRedeclaration(
7477 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7478 isExplicitSpecialization || isFunctionTemplateSpecialization);
7479 }
7480
David Blaikiebbafb8a2012-03-11 07:00:24 +00007481 if (getLangOpts().CPlusPlus) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007482 if (FunctionTemplate) {
7483 if (NewFD->isInvalidDecl())
7484 FunctionTemplate->setInvalidDecl();
7485 return FunctionTemplate;
7486 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00007487 }
Mike Stump11289f42009-09-09 15:08:12 +00007488
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007489 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007490 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7491 if ((getLangOpts().OpenCLVersion >= 120)
7492 && (SC == SC_Static)) {
7493 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7494 D.setInvalidType();
7495 }
Tanya Lattner0f864332013-01-30 19:48:52 +00007496
7497 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
Alp Toker314cc812014-01-25 16:55:45 +00007498 if (!NewFD->getReturnType()->isVoidType()) {
Alp Tokerd0787eb2014-07-02 01:47:15 +00007499 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7500 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7501 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7502 : FixItHint());
Tanya Lattner0f864332013-01-30 19:48:52 +00007503 D.setInvalidType();
7504 }
Matt Arsenaultefb38192013-07-23 01:23:36 +00007505
7506 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00007507 for (auto Param : NewFD->params())
Matt Arsenaultefb38192013-07-23 01:23:36 +00007508 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00007509 }
7510
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007511 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007512
David Blaikiebbafb8a2012-03-11 07:00:24 +00007513 if (getLangOpts().CUDA)
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007514 if (IdentifierInfo *II = NewFD->getIdentifier())
7515 if (!NewFD->isInvalidDecl() &&
7516 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7517 if (II->isStr("cudaConfigureCall")) {
Alp Toker314cc812014-01-25 16:55:45 +00007518 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007519 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7520
7521 Context.setcudaConfigureCallDecl(NewFD);
7522 }
7523 }
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007524
7525 // Here we have an function template explicit specialization at class scope.
7526 // The actually specialization will be postponed to template instatiation
7527 // time via the ClassScopeFunctionSpecializationDecl node.
7528 if (isDependentClassScopeExplicitSpecialization) {
7529 ClassScopeFunctionSpecializationDecl *NewSpec =
7530 ClassScopeFunctionSpecializationDecl::Create(
Nico Weber7b5a7162012-06-25 17:21:05 +00007531 Context, CurContext, SourceLocation(),
7532 cast<CXXMethodDecl>(NewFD),
7533 HasExplicitTemplateArgs, TemplateArgs);
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007534 CurContext->addDecl(NewSpec);
7535 AddToScope = false;
7536 }
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00007537
Douglas Gregorf4f296d2009-03-23 23:06:20 +00007538 return NewFD;
7539}
7540
7541/// \brief Perform semantic checking of a new function declaration.
7542///
7543/// Performs semantic analysis of the new function declaration
7544/// NewFD. This routine performs all semantic checking that does not
7545/// require the actual declarator involved in the declaration, and is
7546/// used both for the declaration of functions as they are parsed
7547/// (called via ActOnDeclarator) and for the declaration of functions
7548/// that have been instantiated via C++ template instantiation (called
7549/// via InstantiateDecl).
7550///
James Dennettffad8b72012-06-22 08:10:18 +00007551/// \param IsExplicitSpecialization whether this new function declaration is
Douglas Gregorcf915552009-10-13 16:30:37 +00007552/// an explicit specialization of the previous declaration.
7553///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007554/// This sets NewFD->isInvalidDecl() to true if there was an error.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007555///
James Dennettffad8b72012-06-22 08:10:18 +00007556/// \returns true if the function declaration is a redeclaration.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007557bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00007558 LookupResult &Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007559 bool IsExplicitSpecialization) {
Alp Toker314cc812014-01-25 16:55:45 +00007560 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7561 "Variably modified return types are not handled here");
John McCalld9baf6a2009-07-24 03:03:21 +00007562
Richard Smith1c34fb72013-08-13 18:18:50 +00007563 // Determine whether the type of this function should be merged with
7564 // a previous visible declaration. This never happens for functions in C++,
7565 // and always happens in C if the previous declaration was visible.
7566 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7567 !Previous.isShadowed();
7568
Douglas Gregor3552dab2013-01-09 00:47:56 +00007569 // Filter out any non-conflicting previous declarations.
7570 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7571
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007572 bool Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007573 NamedDecl *OldDecl = nullptr;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007574
Douglas Gregore62c0a42009-02-24 01:23:02 +00007575 // Merge or overload the declaration with an existing declaration of
7576 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00007577 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00007578 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00007579 // a declaration that requires merging. If it's an overload,
7580 // there's no more work to do here; we'll just add the new
7581 // function to the scope.
John McCalldaa3d6b2009-12-09 03:35:25 +00007582 if (!AllowOverloadingOfFunction(Previous, Context)) {
Rafael Espindola5bddd6a2013-04-15 12:49:13 +00007583 NamedDecl *Candidate = Previous.getFoundDecl();
7584 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7585 Redeclaration = true;
7586 OldDecl = Candidate;
7587 }
John McCalldaa3d6b2009-12-09 03:35:25 +00007588 } else {
John McCalle9cccd82010-06-16 08:42:20 +00007589 switch (CheckOverload(S, NewFD, Previous, OldDecl,
7590 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00007591 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007592 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00007593 break;
7594
7595 case Ovl_NonFunction:
7596 Redeclaration = true;
7597 break;
7598
7599 case Ovl_Overload:
7600 Redeclaration = false;
7601 break;
John McCall1f82f242009-11-18 22:49:29 +00007602 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007603
David Blaikiebbafb8a2012-03-11 07:00:24 +00007604 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007605 // If a function name is overloadable in C, then every function
7606 // with that name must be marked "overloadable".
7607 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7608 << Redeclaration << NewFD;
Craig Topperc3ec1492014-05-26 06:22:03 +00007609 NamedDecl *OverloadedDecl = nullptr;
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007610 if (Redeclaration)
7611 OverloadedDecl = OldDecl;
7612 else if (!Previous.empty())
7613 OverloadedDecl = Previous.getRepresentativeDecl();
7614 if (OverloadedDecl)
7615 Diag(OverloadedDecl->getLocation(),
7616 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007617 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00007618 }
John McCall1f82f242009-11-18 22:49:29 +00007619 }
Richard Smith574f4f62013-01-14 05:37:29 +00007620 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007621
Richard Smithac974a32013-06-30 09:48:50 +00007622 // Check for a previous extern "C" declaration with this name.
7623 if (!Redeclaration &&
7624 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7625 filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7626 if (!Previous.empty()) {
7627 // This is an extern "C" declaration with the same name as a previous
7628 // declaration, and thus redeclares that entity...
7629 Redeclaration = true;
7630 OldDecl = Previous.getFoundDecl();
Richard Smith1c34fb72013-08-13 18:18:50 +00007631 MergeTypeWithPrevious = false;
Richard Smithac974a32013-06-30 09:48:50 +00007632
7633 // ... except in the presence of __attribute__((overloadable)).
7634 if (OldDecl->hasAttr<OverloadableAttr>()) {
7635 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7636 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7637 << Redeclaration << NewFD;
7638 Diag(Previous.getFoundDecl()->getLocation(),
7639 diag::note_attribute_overloadable_prev_overload);
Aaron Ballman36a53502014-01-16 13:03:14 +00007640 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
Richard Smithac974a32013-06-30 09:48:50 +00007641 }
7642 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7643 Redeclaration = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00007644 OldDecl = nullptr;
Richard Smithac974a32013-06-30 09:48:50 +00007645 }
7646 }
7647 }
7648 }
7649
Richard Smith574f4f62013-01-14 05:37:29 +00007650 // C++11 [dcl.constexpr]p8:
7651 // A constexpr specifier for a non-static member function that is not
7652 // a constructor declares that member function to be const.
7653 //
7654 // This needs to be delayed until we know whether this is an out-of-line
7655 // definition of a static member function.
Richard Smith034185c2013-04-21 01:08:50 +00007656 //
7657 // This rule is not present in C++1y, so we produce a backwards
7658 // compatibility warning whenever it happens in C++11.
Richard Smith574f4f62013-01-14 05:37:29 +00007659 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
Richard Smith034185c2013-04-21 01:08:50 +00007660 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7661 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
Richard Smith574f4f62013-01-14 05:37:29 +00007662 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007663 CXXMethodDecl *OldMD = nullptr;
Alp Tokera2794f92014-01-22 07:29:52 +00007664 if (OldDecl)
7665 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
Richard Smith574f4f62013-01-14 05:37:29 +00007666 if (!OldMD || !OldMD->isStatic()) {
7667 const FunctionProtoType *FPT =
7668 MD->getType()->castAs<FunctionProtoType>();
7669 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7670 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00007671 MD->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00007672 FPT->getParamTypes(), EPI));
Richard Smith034185c2013-04-21 01:08:50 +00007673
7674 // Warn that we did this, if we're not performing template instantiation.
7675 // In that case, we'll have warned already when the template was defined.
7676 if (ActiveTemplateInstantiations.empty()) {
7677 SourceLocation AddConstLoc;
7678 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7679 .IgnoreParens().getAs<FunctionTypeLoc>())
Alp Tokerb6cc5922014-05-03 03:45:55 +00007680 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
Richard Smith034185c2013-04-21 01:08:50 +00007681
7682 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7683 << FixItHint::CreateInsertion(AddConstLoc, " const");
7684 }
Richard Smith574f4f62013-01-14 05:37:29 +00007685 }
7686 }
7687
7688 if (Redeclaration) {
7689 // NewFD and OldDecl represent declarations that need to be
7690 // merged.
Richard Smith1c34fb72013-08-13 18:18:50 +00007691 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
Richard Smith574f4f62013-01-14 05:37:29 +00007692 NewFD->setInvalidDecl();
7693 return Redeclaration;
7694 }
7695
7696 Previous.clear();
7697 Previous.addDecl(OldDecl);
7698
7699 if (FunctionTemplateDecl *OldTemplateDecl
7700 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7701 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7702 FunctionTemplateDecl *NewTemplateDecl
7703 = NewFD->getDescribedFunctionTemplate();
7704 assert(NewTemplateDecl && "Template/non-template mismatch");
7705 if (CXXMethodDecl *Method
7706 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7707 Method->setAccess(OldTemplateDecl->getAccess());
7708 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007709 }
Richard Smith574f4f62013-01-14 05:37:29 +00007710
7711 // If this is an explicit specialization of a member that is a function
7712 // template, mark it as a member specialization.
7713 if (IsExplicitSpecialization &&
7714 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7715 NewTemplateDecl->setMemberSpecialization();
7716 assert(OldTemplateDecl->isMemberSpecialization());
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00007717 }
Richard Smith574f4f62013-01-14 05:37:29 +00007718
7719 } else {
John McCall6bd2a892013-01-25 22:31:03 +00007720 // This needs to happen first so that 'inline' propagates.
Richard Smith574f4f62013-01-14 05:37:29 +00007721 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
John McCall6bd2a892013-01-25 22:31:03 +00007722
7723 if (isa<CXXMethodDecl>(NewFD)) {
7724 // A valid redeclaration of a C++ method must be out-of-line,
7725 // but (unfortunately) it's not necessarily a definition
7726 // because of templates, which means that the previous
7727 // declaration is not necessarily from the class definition.
7728
7729 // For just setting the access, that doesn't matter.
7730 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7731 NewFD->setAccess(oldMethod->getAccess());
7732
7733 // Update the key-function state if necessary for this ABI.
7734 if (NewFD->isInlined() &&
7735 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7736 // setNonKeyFunction needs to work with the original
7737 // declaration from the class definition, and isVirtual() is
7738 // just faster in that case, so map back to that now.
Rafael Espindola8db352d2013-10-17 15:37:26 +00007739 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
John McCall6bd2a892013-01-25 22:31:03 +00007740 if (oldMethod->isVirtual()) {
7741 Context.setNonKeyFunction(oldMethod);
7742 }
7743 }
7744 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007745 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00007746 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00007747
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007748 // Semantic checking for this function declaration (in isolation).
David Blaikiebbafb8a2012-03-11 07:00:24 +00007749 if (getLangOpts().CPlusPlus) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007750 // C++-specific checks.
7751 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7752 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007753 } else if (CXXDestructorDecl *Destructor =
7754 dyn_cast<CXXDestructorDecl>(NewFD)) {
7755 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007756 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007757
Douglas Gregor7454c562010-07-02 20:37:36 +00007758 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00007759 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007760 if (!ClassType->isDependentType()) {
7761 DeclarationName Name
7762 = Context.DeclarationNames.getCXXDestructorName(
7763 Context.getCanonicalType(ClassType));
7764 if (NewFD->getDeclName() != Name) {
7765 Diag(NewFD->getLocation(), diag::err_destructor_name);
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007766 NewFD->setInvalidDecl();
7767 return Redeclaration;
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007768 }
7769 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007770 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00007771 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007772 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00007773 }
7774
7775 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00007776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7777 if (!Method->isFunctionTemplateSpecialization() &&
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00007778 !Method->getDescribedFunctionTemplate() &&
7779 Method->isCanonicalDecl()) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007780 if (AddOverriddenMethods(Method->getParent(), Method)) {
7781 // If the function was marked as "static", we have a problem.
7782 if (NewFD->getStorageClass() == SC_Static) {
David Blaikie7e414262012-10-17 00:47:58 +00007783 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007784 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007785 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00007786 }
Douglas Gregor3024f072012-04-16 07:05:22 +00007787
7788 if (Method->isStatic())
7789 checkThisInStaticMemberFunctionType(Method);
Douglas Gregor6be3de32009-12-01 17:35:23 +00007790 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007791
7792 // Extra checking for C++ overloaded operators (C++ [over.oper]).
7793 if (NewFD->isOverloadedOperator() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007794 CheckOverloadedOperatorDeclaration(NewFD)) {
7795 NewFD->setInvalidDecl();
7796 return Redeclaration;
7797 }
Alexis Huntc88db062010-01-13 09:01:02 +00007798
7799 // Extra checking for C++0x literal operators (C++0x [over.literal]).
7800 if (NewFD->getLiteralIdentifier() &&
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007801 CheckLiteralOperatorDeclaration(NewFD)) {
7802 NewFD->setInvalidDecl();
7803 return Redeclaration;
7804 }
Alexis Huntc88db062010-01-13 09:01:02 +00007805
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007806 // In C++, check default arguments now that we have merged decls. Unless
7807 // the lexical context is the class, because in this case this is done
7808 // during delayed parsing anyway.
7809 if (!CurContext->isRecord())
7810 CheckCXXDefaultArguments(NewFD);
Warren Hunt445d83e2013-11-01 23:46:51 +00007811
Douglas Gregor9246b682010-12-21 19:47:46 +00007812 // If this function declares a builtin function, check the type of this
7813 // declaration against the expected type for the builtin.
7814 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7815 ASTContext::GetBuiltinTypeError Error;
Fariborz Jahanianfeb9ae52013-01-05 21:54:55 +00007816 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
Douglas Gregor9246b682010-12-21 19:47:46 +00007817 QualType T = Context.GetBuiltinType(BuiltinID, Error);
7818 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7819 // The type of this function differs from the type of the builtin,
7820 // so forget about the builtin entirely.
7821 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7822 }
7823 }
Warren Hunt445d83e2013-11-01 23:46:51 +00007824
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007825 // If this function is declared as being extern "C", then check to see if
7826 // the function returns a UDT (class, struct, or union type) that is not C
7827 // compatible, and if it does, warn the user.
Fariborz Jahanian95236b52013-03-14 23:09:00 +00007828 // But, issue any diagnostic on the first declaration only.
7829 if (NewFD->isExternC() && Previous.empty()) {
Alp Toker314cc812014-01-25 16:55:45 +00007830 QualType R = NewFD->getReturnType();
Hans Wennborg84ce6062012-07-24 17:59:41 +00007831 if (R->isIncompleteType() && !R->isVoidType())
7832 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7833 << NewFD << R;
Douglas Gregor847cea72012-08-07 06:14:34 +00007834 else if (!R.isPODType(Context) && !R->isVoidType() &&
7835 !R->isObjCObjectPointerType())
Hans Wennborg84ce6062012-07-24 17:59:41 +00007836 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
Aaron Ballmanc2a9493a2012-02-09 01:21:34 +00007837 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00007838 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00007839 return Redeclaration;
Zhongxing Xubece5d62009-01-16 01:13:29 +00007840}
7841
David Blaikied937bf12011-09-08 06:33:04 +00007842void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
Richard Smithb63b6ee2014-01-22 01:43:19 +00007843 // C++11 [basic.start.main]p3:
7844 // A program that [...] declares main to be inline, static or
7845 // constexpr is ill-formed.
Richard Smith0015f092013-01-17 22:16:11 +00007846 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
7847 // appear in a declaration of main.
John McCall02dee0a2009-07-25 04:36:53 +00007848 // static main is not an error under C99, but we should warn about it.
Richard Smith0015f092013-01-17 22:16:11 +00007849 // We accept _Noreturn main as an extension.
David Blaikied937bf12011-09-08 06:33:04 +00007850 if (FD->getStorageClass() == SC_Static)
David Blaikiebbafb8a2012-03-11 07:00:24 +00007851 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
David Blaikied937bf12011-09-08 06:33:04 +00007852 ? diag::err_static_main : diag::warn_static_main)
7853 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7854 if (FD->isInlineSpecified())
7855 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7856 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007857 if (DS.isNoreturnSpecified()) {
7858 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007859 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
Dmitri Gribenko7ec6f3d2013-01-21 11:25:03 +00007860 Diag(NoreturnLoc, diag::ext_noreturn_main);
7861 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7862 << FixItHint::CreateRemoval(NoreturnRange);
7863 }
Richard Smith3f333f22012-02-04 06:10:17 +00007864 if (FD->isConstexpr()) {
7865 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7866 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7867 FD->setConstexpr(false);
7868 }
John McCall02dee0a2009-07-25 04:36:53 +00007869
Joey Goulya7310a82013-11-05 12:30:39 +00007870 if (getLangOpts().OpenCL) {
7871 Diag(FD->getLocation(), diag::err_opencl_no_main)
7872 << FD->hasAttr<OpenCLKernelAttr>();
7873 FD->setInvalidDecl();
7874 return;
7875 }
7876
John McCall02dee0a2009-07-25 04:36:53 +00007877 QualType T = FD->getType();
7878 assert(T->isFunctionType() && "function decl is not of function type");
John McCall5ed3caf2012-02-14 19:50:52 +00007879 const FunctionType* FT = T->castAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00007880
John McCall5ed3caf2012-02-14 19:50:52 +00007881 // All the standards say that main() should should return 'int'.
Alp Toker314cc812014-01-25 16:55:45 +00007882 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
John McCall5ed3caf2012-02-14 19:50:52 +00007883 // In C and C++, main magically returns 0 if you fall off the end;
7884 // set the flag which tells us that.
7885 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7886 FD->setHasImplicitReturnZero(true);
7887
7888 // In C with GNU extensions we allow main() to have non-integer return
7889 // type, but we should warn about the extension, and we disable the
7890 // implicit-return-zero rule.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007891 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
John McCall5ed3caf2012-02-14 19:50:52 +00007892 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7893
Alp Tokerd0787eb2014-07-02 01:47:15 +00007894 SourceRange RTRange = FD->getReturnTypeSourceRange();
7895 if (RTRange.isValid())
7896 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
7897 << FixItHint::CreateReplacement(RTRange, "int");
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007898
John McCall5ed3caf2012-02-14 19:50:52 +00007899 // Otherwise, this is just a flat-out error.
7900 } else {
Alp Tokerd0787eb2014-07-02 01:47:15 +00007901 SourceRange RTRange = FD->getReturnTypeSourceRange();
7902 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7903 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
7904 : FixItHint());
Dmitri Gribenkoae734172013-01-17 00:26:13 +00007905
John McCall02dee0a2009-07-25 04:36:53 +00007906 FD->setInvalidDecl(true);
7907 }
7908
7909 // Treat protoless main() as nullary.
7910 if (isa<FunctionNoProtoType>(FT)) return;
7911
7912 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00007913 unsigned nparams = FTP->getNumParams();
John McCall02dee0a2009-07-25 04:36:53 +00007914 assert(FD->getNumParams() == nparams);
7915
John McCall0e21fcc2009-12-24 09:58:38 +00007916 bool HasExtraParameters = (nparams > 3);
7917
7918 // Darwin passes an undocumented fourth argument of type char**. If
7919 // other platforms start sprouting these, the logic below will start
7920 // getting shifty.
Douglas Gregore8bbc122011-09-02 00:18:52 +00007921 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00007922 HasExtraParameters = false;
7923
7924 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00007925 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7926 FD->setInvalidDecl(true);
7927 nparams = 3;
7928 }
7929
7930 // FIXME: a lot of the following diagnostics would be improved
7931 // if we had some location information about types.
7932
7933 QualType CharPP =
7934 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00007935 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00007936
7937 for (unsigned i = 0; i < nparams; ++i) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007938 QualType AT = FTP->getParamType(i);
John McCall02dee0a2009-07-25 04:36:53 +00007939
7940 bool mismatch = true;
7941
7942 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7943 mismatch = false;
7944 else if (Expected[i] == CharPP) {
7945 // As an extension, the following forms are okay:
7946 // char const **
7947 // char const * const *
7948 // char * const *
7949
John McCall8ccfcb52009-09-24 19:53:00 +00007950 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00007951 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007952 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7953 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Richard Smith685cef62013-01-29 02:49:47 +00007954 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7955 Context.CharTy)) {
John McCall02dee0a2009-07-25 04:36:53 +00007956 qs.removeConst();
7957 mismatch = !qs.empty();
7958 }
7959 }
7960
7961 if (mismatch) {
7962 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7963 // TODO: suggest replacing given type with expected type
7964 FD->setInvalidDecl(true);
7965 }
7966 }
7967
7968 if (nparams == 1 && !FD->isInvalidDecl()) {
7969 Diag(FD->getLocation(), diag::warn_main_one_arg);
7970 }
Douglas Gregorbff62032010-10-21 16:57:46 +00007971
7972 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007973 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
David Majnemerc729b0b2013-09-16 22:44:20 +00007974 FD->setInvalidDecl();
7975 }
7976}
7977
7978void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7979 QualType T = FD->getType();
7980 assert(T->isFunctionType() && "function decl is not of function type");
7981 const FunctionType *FT = T->castAs<FunctionType>();
7982
7983 // Set an implicit return of 'zero' if the function can return some integral,
7984 // enumeration, pointer or nullptr type.
Alp Toker314cc812014-01-25 16:55:45 +00007985 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7986 FT->getReturnType()->isAnyPointerType() ||
7987 FT->getReturnType()->isNullPtrType())
David Majnemerc729b0b2013-09-16 22:44:20 +00007988 // DllMain is exempt because a return value of zero means it failed.
7989 if (FD->getName() != "DllMain")
7990 FD->setHasImplicitReturnZero(true);
7991
7992 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Aaron Ballman6d086d72014-01-03 02:20:27 +00007993 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
Douglas Gregorbff62032010-10-21 16:57:46 +00007994 FD->setInvalidDecl();
7995 }
John McCalld9baf6a2009-07-24 03:03:21 +00007996}
7997
Eli Friedmand5a55bd2008-05-20 13:48:25 +00007998bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00007999 // FIXME: Need strict checking. In C89, we need to check for
8000 // any assignment, increment, decrement, function-calls, or
8001 // commas outside of a sizeof. In C99, it's the same list,
8002 // except that the aforementioned are allowed in unevaluated
8003 // expressions. Everything else falls under the
8004 // "may accept other forms of constant expressions" exception.
8005 // (We never end up here for C++, so the constant expression
8006 // rules there don't matter.)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008007 const Expr *Culprit;
8008 if (Init->isConstantInitializer(Context, false, &Culprit))
Eli Friedman7bfab362009-02-22 06:45:27 +00008009 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00008010 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8011 << Culprit->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00008012 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00008013}
8014
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008015namespace {
8016 // Visits an initialization expression to see if OrigDecl is evaluated in
8017 // its own initialization and throws a warning if it does.
8018 class SelfReferenceChecker
8019 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8020 Sema &S;
8021 Decl *OrigDecl;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008022 bool isRecordType;
8023 bool isPODType;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008024 bool isReferenceType;
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008025
8026 public:
8027 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8028
8029 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
Richard Trieua04ad1a2011-09-01 21:44:13 +00008030 S(S), OrigDecl(OrigDecl) {
8031 isPODType = false;
8032 isRecordType = false;
Hans Wennborge1fdb052012-08-17 10:12:33 +00008033 isReferenceType = false;
Richard Trieua04ad1a2011-09-01 21:44:13 +00008034 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8035 isPODType = VD->getType().isPODType(S.Context);
8036 isRecordType = VD->getType()->isRecordType();
Hans Wennborge1fdb052012-08-17 10:12:33 +00008037 isReferenceType = VD->getType()->isReferenceType();
Richard Trieua04ad1a2011-09-01 21:44:13 +00008038 }
8039 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008040
Richard Trieu64c51ab2012-05-09 00:21:34 +00008041 // For most expressions, the cast is directly above the DeclRefExpr.
8042 // For conditional operators, the cast can be outside the conditional
8043 // operator if both expressions are DeclRefExpr's.
8044 void HandleValue(Expr *E) {
Richard Trieu32673472012-10-01 17:39:51 +00008045 if (isReferenceType)
8046 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008047 E = E->IgnoreParenImpCasts();
8048 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8049 HandleDeclRefExpr(DRE);
8050 return;
8051 }
8052
8053 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8054 HandleValue(CO->getTrueExpr());
8055 HandleValue(CO->getFalseExpr());
Richard Trieu742c6ed2012-10-03 00:41:36 +00008056 return;
8057 }
8058
8059 if (isa<MemberExpr>(E)) {
8060 Expr *Base = E->IgnoreParenImpCasts();
8061 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8062 // Check for static member variables and don't warn on them.
8063 if (!isa<FieldDecl>(ME->getMemberDecl()))
8064 return;
8065 Base = ME->getBase()->IgnoreParenImpCasts();
8066 }
8067 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8068 HandleDeclRefExpr(DRE);
8069 return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008070 }
8071 }
8072
Richard Trieu32673472012-10-01 17:39:51 +00008073 // Reference types are handled here since all uses of references are
8074 // bad, not just r-value uses.
8075 void VisitDeclRefExpr(DeclRefExpr *E) {
8076 if (isReferenceType)
8077 HandleDeclRefExpr(E);
8078 }
8079
Richard Trieu64c51ab2012-05-09 00:21:34 +00008080 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu742c6ed2012-10-03 00:41:36 +00008081 if (E->getCastKind() == CK_LValueToRValue ||
Richard Trieu64c51ab2012-05-09 00:21:34 +00008082 (isRecordType && E->getCastKind() == CK_NoOp))
8083 HandleValue(E->getSubExpr());
8084
8085 Inherited::VisitImplicitCastExpr(E);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008086 }
8087
Richard Trieua04ad1a2011-09-01 21:44:13 +00008088 void VisitMemberExpr(MemberExpr *E) {
Richard Trieu64c51ab2012-05-09 00:21:34 +00008089 // Don't warn on arrays since they can be treated as pointers.
Richard Trieuaa5e2562011-09-07 00:58:53 +00008090 if (E->getType()->canDecayToPointerType()) return;
Richard Trieu64c51ab2012-05-09 00:21:34 +00008091
Richard Trieu742c6ed2012-10-03 00:41:36 +00008092 // Warn when a non-static method call is followed by non-static member
8093 // field accesses, which is followed by a DeclRefExpr.
8094 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8095 bool Warn = (MD && !MD->isStatic());
8096 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8097 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8098 if (!isa<FieldDecl>(ME->getMemberDecl()))
8099 Warn = false;
8100 Base = ME->getBase()->IgnoreParenImpCasts();
8101 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008102
Richard Trieu742c6ed2012-10-03 00:41:36 +00008103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8104 if (Warn)
8105 HandleDeclRefExpr(DRE);
8106 return;
8107 }
8108
8109 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8110 // Visit that expression.
8111 Visit(Base);
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008112 }
8113
Richard Trieu8fbd91d2013-03-26 03:41:40 +00008114 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8115 if (E->getNumArgs() > 0)
8116 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8117 HandleDeclRefExpr(DRE);
8118
8119 Inherited::VisitCXXOperatorCallExpr(E);
8120 }
8121
Richard Trieua04ad1a2011-09-01 21:44:13 +00008122 void VisitUnaryOperator(UnaryOperator *E) {
8123 // For POD record types, addresses of its own members are well-defined.
Richard Trieu742c6ed2012-10-03 00:41:36 +00008124 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8125 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8126 if (!isPODType)
8127 HandleValue(E->getSubExpr());
8128 return;
8129 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008130 Inherited::VisitUnaryOperator(E);
Richard Smithfa11fd62013-05-03 19:16:22 +00008131 }
Richard Trieu64c51ab2012-05-09 00:21:34 +00008132
8133 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8134
Richard Trieua04ad1a2011-09-01 21:44:13 +00008135 void HandleDeclRefExpr(DeclRefExpr *DRE) {
NAKAMURA Takumi3fef3ef2013-01-19 01:54:35 +00008136 Decl* ReferenceDecl = DRE->getDecl();
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008137 if (OrigDecl != ReferenceDecl) return;
Ted Kremeneka83b4072013-01-19 04:33:14 +00008138 unsigned diag;
8139 if (isReferenceType) {
8140 diag = diag::warn_uninit_self_reference_in_reference_init;
8141 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8142 diag = diag::warn_static_self_reference_in_init;
8143 } else {
8144 diag = diag::warn_uninit_self_reference_in_init;
8145 }
8146
Richard Trieua04ad1a2011-09-01 21:44:13 +00008147 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
Hans Wennborgd799a2b2012-08-20 08:52:22 +00008148 S.PDiag(diag)
Hans Wennborg61b2ffa2012-09-21 08:58:33 +00008149 << DRE->getNameInfo().getName()
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008150 << OrigDecl->getLocation()
Richard Trieua04ad1a2011-09-01 21:44:13 +00008151 << DRE->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008152 }
8153 };
Chandler Carruth33bf3e72011-03-27 09:46:56 +00008154
Richard Trieu32673472012-10-01 17:39:51 +00008155 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8156 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8157 bool DirectInit) {
8158 // Parameters arguments are occassionially constructed with itself,
8159 // for instance, in recursive functions. Skip them.
8160 if (isa<ParmVarDecl>(OrigDecl))
8161 return;
8162
8163 E = E->IgnoreParens();
8164
8165 // Skip checking T a = a where T is not a record or reference type.
8166 // Doing so is a way to silence uninitialized warnings.
8167 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8168 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8169 if (ICE->getCastKind() == CK_LValueToRValue)
8170 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8171 if (DRE->getDecl() == OrigDecl)
8172 return;
8173
8174 SelfReferenceChecker(S, OrigDecl).Visit(E);
8175 }
Richard Trieua04ad1a2011-09-01 21:44:13 +00008176}
8177
Douglas Gregor5fb53972009-01-14 15:45:31 +00008178/// AddInitializerToDecl - Adds the initializer Init to the
8179/// declaration dcl. If DirectInit is true, this is C++ direct
8180/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00008181void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8182 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00008183 // If there is no declaration, there was an error parsing it. Just ignore
8184 // the initializer.
Craig Topperc3ec1492014-05-26 06:22:03 +00008185 if (!RealDecl || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00008186 return;
Mike Stump11289f42009-09-09 15:08:12 +00008187
Douglas Gregor0c880302009-03-11 23:00:04 +00008188 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8189 // With declarators parsed the way they are, the parser cannot
8190 // distinguish between a normal initializer and a pure-specifier.
8191 // Thus this grotesque test.
8192 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00008193 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00008194 Context.getCanonicalType(IL->getType()) == Context.IntTy)
8195 CheckPureMethod(Method, Init->getSourceRange());
8196 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00008197 Diag(Method->getLocation(), diag::err_member_function_initialization)
8198 << Method->getDeclName() << Init->getSourceRange();
8199 Method->setInvalidDecl();
8200 }
8201 return;
8202 }
8203
Steve Naroff437b4d82007-09-12 20:13:48 +00008204 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8205 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00008206 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8207 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00008208 RealDecl->setInvalidDecl();
8209 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00008210 }
Sebastian Redla9351792012-02-11 23:51:47 +00008211 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8212
Richard Smith0cc85782011-12-15 19:20:59 +00008213 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00008214 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
Sebastian Redla9351792012-02-11 23:51:47 +00008215 Expr *DeduceInit = Init;
8216 // Initializer could be a C++ direct-initializer. Deduction only works if it
8217 // contains exactly one expression.
8218 if (CXXDirectInit) {
8219 if (CXXDirectInit->getNumExprs() == 0) {
8220 // It isn't possible to write this directly, but it is possible to
8221 // end up in this situation with "auto x(some_pack...);"
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008222 Diag(CXXDirectInit->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008223 VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8224 : diag::err_auto_var_init_no_expression)
Sebastian Redla9351792012-02-11 23:51:47 +00008225 << VDecl->getDeclName() << VDecl->getType()
8226 << VDecl->getSourceRange();
8227 RealDecl->setInvalidDecl();
8228 return;
8229 } else if (CXXDirectInit->getNumExprs() > 1) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008230 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00008231 VDecl->isInitCapture()
8232 ? diag::err_init_capture_multiple_expressions
8233 : diag::err_auto_var_init_multiple_expressions)
Sebastian Redla9351792012-02-11 23:51:47 +00008234 << VDecl->getDeclName() << VDecl->getType()
8235 << VDecl->getSourceRange();
8236 RealDecl->setInvalidDecl();
8237 return;
8238 } else {
8239 DeduceInit = CXXDirectInit->getExpr(0);
Richard Smith66204ec2014-03-12 17:42:45 +00008240 if (isa<InitListExpr>(DeduceInit))
8241 Diag(CXXDirectInit->getLocStart(),
8242 diag::err_auto_var_init_paren_braces)
8243 << VDecl->getDeclName() << VDecl->getType()
8244 << VDecl->getSourceRange();
Sebastian Redla9351792012-02-11 23:51:47 +00008245 }
8246 }
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008247
8248 // Expressions default to 'id' when we're in a debugger.
8249 bool DefaultedToAuto = false;
8250 if (getLangOpts().DebuggerCastResultToId &&
8251 Init->getType() == Context.UnknownAnyTy) {
8252 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8253 if (Result.isInvalid()) {
8254 VDecl->setInvalidDecl();
8255 return;
8256 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008257 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008258 DefaultedToAuto = true;
8259 }
Richard Smith061f1e22013-04-30 21:23:01 +00008260
8261 QualType DeducedType;
Sebastian Redla9351792012-02-11 23:51:47 +00008262 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00008263 DAR_Failed)
Sebastian Redla9351792012-02-11 23:51:47 +00008264 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
Richard Smith061f1e22013-04-30 21:23:01 +00008265 if (DeducedType.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008266 RealDecl->setInvalidDecl();
8267 return;
8268 }
Richard Smith061f1e22013-04-30 21:23:01 +00008269 VDecl->setType(DeducedType);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00008270 assert(VDecl->isLinkageValid());
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00008271
John McCall31168b02011-06-15 23:02:42 +00008272 // In ARC, infer lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008273 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
John McCall31168b02011-06-15 23:02:42 +00008274 VDecl->setInvalidDecl();
8275
Jordan Rosed8d56692012-06-08 22:46:07 +00008276 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8277 // 'id' instead of a specific object type prevents most of our usual checks.
8278 // We only want to warn outside of template instantiations, though:
8279 // inside a template, the 'id' could have come from a parameter.
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008280 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
Richard Smith061f1e22013-04-30 21:23:01 +00008281 DeducedType->isObjCIdType()) {
8282 SourceLocation Loc =
8283 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Jordan Rosed8d56692012-06-08 22:46:07 +00008284 Diag(Loc, diag::warn_auto_var_is_id)
8285 << VDecl->getDeclName() << DeduceInit->getSourceRange();
8286 }
8287
Richard Smith30482bc2011-02-20 03:19:35 +00008288 // If this is a redeclaration, check that the type we just deduced matches
8289 // the previously declared type.
Richard Smith1c34fb72013-08-13 18:18:50 +00008290 if (VarDecl *Old = VDecl->getPreviousDecl()) {
8291 // We never need to merge the type, because we cannot form an incomplete
8292 // array of auto, nor deduce such a type.
8293 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8294 }
Richard Smith27d807c2013-04-30 13:56:41 +00008295
8296 // Check the deduced type is valid for a variable declaration.
8297 CheckVariableDeclarationType(VDecl);
8298 if (VDecl->isInvalidDecl())
8299 return;
Richard Smith30482bc2011-02-20 03:19:35 +00008300 }
Richard Smith0cc85782011-12-15 19:20:59 +00008301
Nico Rieck8e9791f2014-02-26 21:27:13 +00008302 // dllimport cannot be used on variable definitions.
8303 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8304 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8305 VDecl->setInvalidDecl();
8306 return;
8307 }
8308
Richard Smith0cc85782011-12-15 19:20:59 +00008309 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8310 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8311 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8312 VDecl->setInvalidDecl();
8313 return;
8314 }
8315
Sebastian Redla9351792012-02-11 23:51:47 +00008316 if (!VDecl->getType()->isDependentType()) {
8317 // A definition must end up with a complete type, which means it must be
8318 // complete with the restriction that an array type might be completed by
8319 // the initializer; note that later code assumes this restriction.
8320 QualType BaseDeclType = VDecl->getType();
8321 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8322 BaseDeclType = Array->getElementType();
8323 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8324 diag::err_typecheck_decl_incomplete_type)) {
8325 RealDecl->setInvalidDecl();
8326 return;
8327 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00008328
Sebastian Redla9351792012-02-11 23:51:47 +00008329 // The variable can not have an abstract class type.
8330 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8331 diag::err_abstract_type_in_decl,
8332 AbstractVariableType))
8333 VDecl->setInvalidDecl();
Eli Friedman337cd3a2009-04-13 21:28:54 +00008334 }
8335
Sebastian Redl5ca79842010-02-01 20:16:42 +00008336 const VarDecl *Def;
8337 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00008338 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00008339 << VDecl->getDeclName();
8340 Diag(Def->getLocation(), diag::note_previous_definition);
8341 VDecl->setInvalidDecl();
8342 return;
8343 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008344
8345 const VarDecl *PrevInit = nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008346 if (getLangOpts().CPlusPlus) {
Douglas Gregor71f39c92010-12-16 01:31:22 +00008347 // C++ [class.static.data]p4
8348 // If a static data member is of const integral or const
8349 // enumeration type, its declaration in the class definition can
8350 // specify a constant-initializer which shall be an integral
8351 // constant expression (5.19). In that case, the member can appear
8352 // in integral constant expressions. The member shall still be
8353 // defined in a namespace scope if it is used in the program and the
8354 // namespace scope definition shall not contain an initializer.
8355 //
8356 // We already performed a redefinition check above, but for static
8357 // data members we also need to check whether there was an in-class
8358 // declaration with an initializer.
8359 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
Hans Wennborg84fe12d2013-11-21 03:17:44 +00008360 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8361 << VDecl->getDeclName();
8362 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00008363 return;
8364 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00008365
Douglas Gregor71f39c92010-12-16 01:31:22 +00008366 if (VDecl->hasLocalStorage())
8367 getCurFunction()->setHasBranchProtectedScope();
8368
8369 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8370 VDecl->setInvalidDecl();
8371 return;
8372 }
8373 }
John McCalld4e1b762010-08-01 01:24:59 +00008374
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008375 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8376 // a kernel function cannot be initialized."
8377 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8378 Diag(VDecl->getLocation(), diag::err_local_cant_init);
8379 VDecl->setInvalidDecl();
8380 return;
8381 }
8382
Steve Naroff61091402007-09-12 14:07:44 +00008383 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00008384 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00008385 QualType DclT = VDecl->getType(), SavT = DclT;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008386
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008387 // Expressions default to 'id' when we're in a debugger
8388 // and we are assigning it to a variable of Objective-C pointer type.
8389 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8390 Init->getType() == Context.UnknownAnyTy) {
8391 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8392 if (Result.isInvalid()) {
8393 VDecl->setInvalidDecl();
8394 return;
Fariborz Jahanianc8a322a2012-03-09 18:47:16 +00008395 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008396 Init = Result.get();
Douglas Gregorb5af2e92013-03-07 22:57:58 +00008397 }
Richard Smith0cc85782011-12-15 19:20:59 +00008398
8399 // Perform the initialization.
8400 if (!VDecl->isInvalidDecl()) {
8401 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8402 InitializationKind Kind
Sebastian Redl5a41f682012-02-12 16:37:24 +00008403 = DirectInit ?
8404 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8405 Init->getLocStart(),
8406 Init->getLocEnd())
8407 : InitializationKind::CreateDirectList(
8408 VDecl->getLocation())
Richard Smith0cc85782011-12-15 19:20:59 +00008409 : InitializationKind::CreateCopy(VDecl->getLocation(),
8410 Init->getLocStart());
8411
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00008412 MultiExprArg Args = Init;
8413 if (CXXDirectInit)
8414 Args = MultiExprArg(CXXDirectInit->getExprs(),
8415 CXXDirectInit->getNumExprs());
8416
8417 InitializationSequence InitSeq(*this, Entity, Kind, Args);
8418 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008419 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00008420 VDecl->setInvalidDecl();
Richard Smith0cc85782011-12-15 19:20:59 +00008421 return;
Steve Naroff61091402007-09-12 14:07:44 +00008422 }
Richard Smith0cc85782011-12-15 19:20:59 +00008423
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008424 Init = Result.getAs<Expr>();
Richard Smith0cc85782011-12-15 19:20:59 +00008425 }
8426
Richard Trieu32673472012-10-01 17:39:51 +00008427 // Check for self-references within variable initializers.
8428 // Variables declared within a function/method body (except for references)
8429 // are handled by a dataflow analysis.
8430 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8431 VDecl->getType()->isReferenceType()) {
8432 CheckSelfReference(*this, RealDecl, Init, DirectInit);
8433 }
8434
Richard Smith0cc85782011-12-15 19:20:59 +00008435 // If the type changed, it means we had an incomplete type that was
8436 // completed by the initializer. For example:
8437 // int ary[] = { 1, 3, 5 };
John McCalla59dc2f2012-01-05 00:13:19 +00008438 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
Eli Friedman91f5ae52012-02-23 02:25:10 +00008439 if (!VDecl->isInvalidDecl() && (DclT != SavT))
Richard Smith0cc85782011-12-15 19:20:59 +00008440 VDecl->setType(DclT);
Richard Smith0cc85782011-12-15 19:20:59 +00008441
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008442 if (!VDecl->isInvalidDecl()) {
Richard Smith0cc85782011-12-15 19:20:59 +00008443 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8444
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008445 if (VDecl->hasAttr<BlocksAttr>())
8446 checkRetainCycles(VDecl, Init);
Jordan Rosed3934582012-09-28 22:21:30 +00008447
8448 // It is safe to assign a weak reference into a strong variable.
8449 // Although this code can still have problems:
8450 // id x = self.weakProp;
8451 // id y = self.weakProp;
8452 // we do not warn to warn spuriously when 'x' and 'y' are on separate
8453 // paths through the function. This should be revisited if
8454 // -Wrepeated-use-of-weak is made flow-sensitive.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008455 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8456 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8457 Init->getLocStart()))
Jordan Rosed3934582012-09-28 22:21:30 +00008458 getCurFunction()->markSafeWeakUse(Init);
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008459 }
8460
Richard Smith945f8d32013-01-14 22:39:08 +00008461 // The initialization is usually a full-expression.
8462 //
8463 // FIXME: If this is a braced initialization of an aggregate, it is not
8464 // an expression, and each individual field initializer is a separate
8465 // full-expression. For instance, in:
8466 //
8467 // struct Temp { ~Temp(); };
8468 // struct S { S(Temp); };
8469 // struct T { S a, b; } t = { Temp(), Temp() }
8470 //
8471 // we should destroy the first Temp before constructing the second.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008472 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8473 false,
8474 VDecl->isConstexpr());
Richard Smith945f8d32013-01-14 22:39:08 +00008475 if (Result.isInvalid()) {
8476 VDecl->setInvalidDecl();
8477 return;
8478 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008479 Init = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00008480
Richard Smith0cc85782011-12-15 19:20:59 +00008481 // Attach the initializer to the decl.
8482 VDecl->setInit(Init);
8483
8484 if (VDecl->isLocalVarDecl()) {
8485 // C99 6.7.8p4: All the expressions in an initializer for an object that has
8486 // static storage duration shall be constant expressions or string literals.
8487 // C++ does not have this restriction.
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008488 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00008489 const Expr *Culprit;
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008490 if (VDecl->getStorageClass() == SC_Static)
8491 CheckForConstantInitializer(Init, DclT);
8492 // C89 is stricter than C99 for non-static aggregate types.
8493 // C89 6.5.7p3: All the expressions [...] in an initializer list
8494 // for an object that has aggregate or union type shall be
8495 // constant expressions.
8496 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
Enea Zaffanellac7cb48c2013-07-22 19:10:20 +00008497 isa<InitListExpr>(Init) &&
Abramo Bagnara847c6602014-05-22 19:20:46 +00008498 !Init->isConstantInitializer(Context, false, &Culprit))
8499 Diag(Culprit->getExprLoc(),
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008500 diag::ext_aggregate_init_not_constant)
Abramo Bagnara847c6602014-05-22 19:20:46 +00008501 << Culprit->getSourceRange();
Enea Zaffanella1aac5462013-07-22 10:58:26 +00008502 }
Mike Stump11289f42009-09-09 15:08:12 +00008503 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00008504 VDecl->getLexicalDeclContext()->isRecord()) {
8505 // This is an in-class initialization for a static data member, e.g.,
8506 //
8507 // struct S {
8508 // static const int value = 17;
8509 // };
8510
Douglas Gregor0c880302009-03-11 23:00:04 +00008511 // C++ [class.mem]p4:
8512 // A member-declarator can contain a constant-initializer only
8513 // if it declares a static member (9.4) of const integral or
8514 // const enumeration type, see 9.4.2.
Richard Smith2316cd82011-09-29 19:11:37 +00008515 //
Richard Smith0cc85782011-12-15 19:20:59 +00008516 // C++11 [class.static.data]p3:
Richard Smith2316cd82011-09-29 19:11:37 +00008517 // If a non-volatile const static data member is of integral or
8518 // enumeration type, its declaration in the class definition can
8519 // specify a brace-or-equal-initializer in which every initalizer-clause
8520 // that is an assignment-expression is a constant expression. A static
8521 // data member of literal type can be declared in the class definition
8522 // with the constexpr specifier; if so, its declaration shall specify a
8523 // brace-or-equal-initializer in which every initializer-clause that is
8524 // an assignment-expression is a constant expression.
John McCalldb768922010-09-10 23:21:22 +00008525
8526 // Do nothing on dependent types.
Richard Smith0cc85782011-12-15 19:20:59 +00008527 if (DclT->isDependentType()) {
John McCalldb768922010-09-10 23:21:22 +00008528
Richard Smith2316cd82011-09-29 19:11:37 +00008529 // Allow any 'static constexpr' members, whether or not they are of literal
Richard Smith3607ffe2012-02-13 03:54:03 +00008530 // type. We separately check that every constexpr variable is of literal
8531 // type.
Richard Smith2316cd82011-09-29 19:11:37 +00008532 } else if (VDecl->isConstexpr()) {
8533
John McCalldb768922010-09-10 23:21:22 +00008534 // Require constness.
Richard Smith0cc85782011-12-15 19:20:59 +00008535 } else if (!DclT.isConstQualified()) {
John McCalldb768922010-09-10 23:21:22 +00008536 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8537 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00008538 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008539
8540 // We allow integer constant expressions in all cases.
Richard Smith0cc85782011-12-15 19:20:59 +00008541 } else if (DclT->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00008542 // Check whether the expression is a constant expression.
8543 SourceLocation Loc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008544 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Richard Smith0cc85782011-12-15 19:20:59 +00008545 // In C++11, a non-constexpr const static data member with an
Richard Smithee6311d2011-09-29 21:28:14 +00008546 // in-class initializer cannot be volatile.
8547 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8548 else if (Init->isValueDependent())
Chris Lattner9925ec82011-06-14 05:46:29 +00008549 ; // Nothing to check.
8550 else if (Init->isIntegerConstantExpr(Context, &Loc))
8551 ; // Ok, it's an ICE!
8552 else if (Init->isEvaluatable(Context)) {
8553 // If we can constant fold the initializer through heroics, accept it,
8554 // but report this as a use of an extension for -pedantic.
8555 Diag(Loc, diag::ext_in_class_initializer_non_constant)
8556 << Init->getSourceRange();
8557 } else {
8558 // Otherwise, this is some crazy unknown case. Report the issue at the
8559 // location provided by the isIntegerConstantExpr failed check.
8560 Diag(Loc, diag::err_in_class_initializer_non_constant)
8561 << Init->getSourceRange();
8562 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00008563 }
8564
Richard Smith0cc85782011-12-15 19:20:59 +00008565 // We allow foldable floating-point constants as an extension.
8566 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
Richard Smithcf656382013-01-25 04:22:16 +00008567 // In C++98, this is a GNU extension. In C++11, it is not, but we support
8568 // it anyway and provide a fixit to add the 'constexpr'.
8569 if (getLangOpts().CPlusPlus11) {
David Blaikie8505c292013-01-29 22:26:08 +00008570 Diag(VDecl->getLocation(),
8571 diag::ext_in_class_initializer_float_type_cxx11)
8572 << DclT << Init->getSourceRange();
8573 Diag(VDecl->getLocStart(),
8574 diag::note_in_class_initializer_float_type_cxx11)
8575 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
Richard Smithcf656382013-01-25 04:22:16 +00008576 } else {
8577 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8578 << DclT << Init->getSourceRange();
John McCalldb768922010-09-10 23:21:22 +00008579
Richard Smithcf656382013-01-25 04:22:16 +00008580 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8581 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8582 << Init->getSourceRange();
8583 VDecl->setInvalidDecl();
8584 }
Douglas Gregor0c880302009-03-11 23:00:04 +00008585 }
Richard Smith256336d2011-09-29 23:18:34 +00008586
Richard Smith0cc85782011-12-15 19:20:59 +00008587 // Suggest adding 'constexpr' in C++11 for literal types.
Richard Smithd9f663b2013-04-22 15:31:51 +00008588 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Richard Smith256336d2011-09-29 23:18:34 +00008589 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008590 << DclT << Init->getSourceRange()
Richard Smith256336d2011-09-29 23:18:34 +00008591 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8592 VDecl->setConstexpr(true);
8593
Richard Smith2316cd82011-09-29 19:11:37 +00008594 } else {
8595 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
Richard Smith0cc85782011-12-15 19:20:59 +00008596 << DclT << Init->getSourceRange();
Richard Smith2316cd82011-09-29 19:11:37 +00008597 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00008598 }
Steve Naroff08899ff2008-04-15 22:42:06 +00008599 } else if (VDecl->isFileVarDecl()) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008600 if (VDecl->getStorageClass() == SC_Extern &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008601 (!getLangOpts().CPlusPlus ||
Rafael Espindola069ab032013-03-29 07:56:05 +00008602 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
Richard Smith8809a0c2013-09-27 20:14:12 +00008603 VDecl->isExternC())) &&
8604 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Steve Naroff437b4d82007-09-12 20:13:48 +00008605 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00008606
Richard Smith0cc85782011-12-15 19:20:59 +00008607 // C99 6.7.8p4. All file scoped initializers need to be constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008608 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
Anders Carlsson41e08812008-08-22 05:00:02 +00008609 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +00008610 }
Douglas Gregorbeecd582009-04-21 17:11:58 +00008611
Sebastian Redla9351792012-02-11 23:51:47 +00008612 // We will represent direct-initialization similarly to copy-initialization:
8613 // int x(1); -as-> int x = 1;
8614 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8615 //
8616 // Clients that want to distinguish between the two forms, can check for
8617 // direct initializer using VarDecl::getInitStyle().
8618 // A major benefit is that clients that don't particularly care about which
8619 // exactly form was it (like the CodeGen) can handle both cases without
8620 // special case code.
8621
8622 // C++ 8.5p11:
8623 // The form of initialization (using parentheses or '=') is generally
8624 // insignificant, but does matter when the entity being initialized has a
8625 // class type.
8626 if (CXXDirectInit) {
8627 assert(DirectInit && "Call-style initializer must be direct init.");
8628 VDecl->setInitStyle(VarDecl::CallInit);
8629 } else if (DirectInit) {
8630 // This must be list-initialization. No other way is direct-initialization.
8631 VDecl->setInitStyle(VarDecl::ListInit);
8632 }
8633
John McCall8b7fd8f12011-01-19 11:48:09 +00008634 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00008635}
8636
John McCalleae5acb2010-03-31 02:13:20 +00008637/// ActOnInitializerError - Given that there was an error parsing an
8638/// initializer for the given declaration, try to return to some form
8639/// of sanity.
John McCall48871652010-08-21 09:40:31 +00008640void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00008641 // Our main concern here is re-establishing invariants like "a
8642 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00008643 if (!D || D->isInvalidDecl()) return;
8644
8645 VarDecl *VD = dyn_cast<VarDecl>(D);
8646 if (!VD) return;
8647
Richard Smith30482bc2011-02-20 03:19:35 +00008648 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00008649 if (ParsingInitForAutoVars.count(D)) {
8650 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00008651 return;
8652 }
8653
John McCalleae5acb2010-03-31 02:13:20 +00008654 QualType Ty = VD->getType();
8655 if (Ty->isDependentType()) return;
8656
8657 // Require a complete type.
8658 if (RequireCompleteType(VD->getLocation(),
8659 Context.getBaseElementType(Ty),
8660 diag::err_typecheck_decl_incomplete_type)) {
8661 VD->setInvalidDecl();
8662 return;
8663 }
8664
Alp Toker48c7e172014-04-15 16:24:50 +00008665 // Require a non-abstract type.
John McCalleae5acb2010-03-31 02:13:20 +00008666 if (RequireNonAbstractType(VD->getLocation(), Ty,
8667 diag::err_abstract_type_in_decl,
8668 AbstractVariableType)) {
8669 VD->setInvalidDecl();
8670 return;
8671 }
8672
8673 // Don't bother complaining about constructors or destructors,
8674 // though.
8675}
8676
John McCall48871652010-08-21 09:40:31 +00008677void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00008678 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008679 // If there is no declaration, there was an error parsing it. Just ignore it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008680 if (!RealDecl)
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00008681 return;
8682
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008683 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8684 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00008685
Richard Smithf0215fe2011-12-25 21:17:58 +00008686 // C++11 [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00008687 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00008688 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8689 << Var->getDeclName() << Type;
8690 Var->setInvalidDecl();
8691 return;
8692 }
Mike Stump11289f42009-09-09 15:08:12 +00008693
Richard Smithf0215fe2011-12-25 21:17:58 +00008694 // C++11 [class.static.data]p3: A static data member can be declared with
Richard Smith2316cd82011-09-29 19:11:37 +00008695 // the constexpr specifier; if so, its declaration shall specify
8696 // a brace-or-equal-initializer.
Richard Smithf0215fe2011-12-25 21:17:58 +00008697 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8698 // the definition of a variable [...] or the declaration of a static data
8699 // member.
8700 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8701 if (Var->isStaticDataMember())
8702 Diag(Var->getLocation(),
8703 diag::err_constexpr_static_mem_var_requires_init)
8704 << Var->getDeclName();
8705 else
8706 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Richard Smith2316cd82011-09-29 19:11:37 +00008707 Var->setInvalidDecl();
8708 return;
8709 }
8710
Joey Gouly96b94e62014-01-03 14:16:55 +00008711 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8712 // be initialized.
8713 if (!Var->isInvalidDecl() &&
8714 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Pekka Jaaskelainenb3cdee02014-01-23 16:21:02 +00008715 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
Joey Gouly96b94e62014-01-03 14:16:55 +00008716 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8717 Var->setInvalidDecl();
8718 return;
8719 }
8720
Douglas Gregore6565622010-02-09 07:26:29 +00008721 switch (Var->isThisDeclarationADefinition()) {
8722 case VarDecl::Definition:
8723 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8724 break;
8725
8726 // We have an out-of-line definition of a static data member
8727 // that has an in-class initializer, so we type-check this like
8728 // a declaration.
8729 //
8730 // Fall through
8731
8732 case VarDecl::DeclarationOnly:
8733 // It's only a declaration.
8734
8735 // Block scope. C99 6.7p7: If an identifier for an object is
8736 // declared with no linkage (C99 6.2.2p6), the type for the
8737 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00008738 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Rafael Espindola3ae00052013-05-13 00:12:11 +00008739 !Var->hasLinkage() && !Var->isInvalidDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00008740 RequireCompleteType(Var->getLocation(), Type,
8741 diag::err_typecheck_decl_incomplete_type))
8742 Var->setInvalidDecl();
8743
8744 // Make sure that the type is not abstract.
8745 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8746 RequireNonAbstractType(Var->getLocation(), Type,
8747 diag::err_abstract_type_in_decl,
8748 AbstractVariableType))
8749 Var->setInvalidDecl();
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008750 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008751 Var->getStorageClass() == SC_PrivateExtern) {
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008752 Diag(Var->getLocation(), diag::warn_private_extern);
Fariborz Jahanianf85f3382012-08-17 21:44:55 +00008753 Diag(Var->getLocation(), diag::note_private_extern);
8754 }
Fariborz Jahanian05f4e712012-08-15 18:42:26 +00008755
Douglas Gregore6565622010-02-09 07:26:29 +00008756 return;
8757
8758 case VarDecl::TentativeDefinition:
8759 // File scope. C99 6.9.2p2: A declaration of an identifier for an
8760 // object that has file scope without an initializer, and without a
8761 // storage-class specifier or with the storage-class specifier "static",
8762 // constitutes a tentative definition. Note: A tentative definition with
8763 // external linkage is valid (C99 6.2.2p5).
8764 if (!Var->isInvalidDecl()) {
8765 if (const IncompleteArrayType *ArrayT
8766 = Context.getAsIncompleteArrayType(Type)) {
8767 if (RequireCompleteType(Var->getLocation(),
8768 ArrayT->getElementType(),
8769 diag::err_illegal_decl_array_incomplete_type))
8770 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00008771 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00008772 // C99 6.9.2p3: If the declaration of an identifier for an object is
8773 // a tentative definition and has internal linkage (C99 6.2.2p3), the
8774 // declared type shall not be an incomplete type.
8775 // NOTE: code such as the following
8776 // static struct s;
8777 // struct s { int a; };
8778 // is accepted by gcc. Hence here we issue a warning instead of
8779 // an error and we do not invalidate the static declaration.
8780 // NOTE: to avoid multiple warnings, only check the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +00008781 if (Var->isFirstDecl())
Douglas Gregore6565622010-02-09 07:26:29 +00008782 RequireCompleteType(Var->getLocation(), Type,
8783 diag::ext_typecheck_decl_incomplete_type);
8784 }
8785 }
8786
8787 // Record the tentative definition; we're done.
8788 if (!Var->isInvalidDecl())
8789 TentativeDefinitions.push_back(Var);
8790 return;
8791 }
8792
8793 // Provide a specific diagnostic for uninitialized variable
8794 // definitions with incomplete array type.
8795 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00008796 Diag(Var->getLocation(),
8797 diag::err_typecheck_incomplete_array_needs_initializer);
8798 Var->setInvalidDecl();
8799 return;
8800 }
8801
John McCalla755f0f2010-08-01 01:25:24 +00008802 // Provide a specific diagnostic for uninitialized variable
8803 // definitions with reference type.
8804 if (Type->isReferenceType()) {
8805 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8806 << Var->getDeclName()
8807 << SourceRange(Var->getLocation(), Var->getLocation());
8808 Var->setInvalidDecl();
8809 return;
8810 }
Douglas Gregore6565622010-02-09 07:26:29 +00008811
8812 // Do not attempt to type-check the default initializer for a
8813 // variable with dependent type.
8814 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00008815 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008816
Douglas Gregore6565622010-02-09 07:26:29 +00008817 if (Var->isInvalidDecl())
8818 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00008819
Douglas Gregore6565622010-02-09 07:26:29 +00008820 if (RequireCompleteType(Var->getLocation(),
8821 Context.getBaseElementType(Type),
8822 diag::err_typecheck_decl_incomplete_type)) {
8823 Var->setInvalidDecl();
8824 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008825 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008826
Douglas Gregore6565622010-02-09 07:26:29 +00008827 // The variable can not have an abstract class type.
8828 if (RequireNonAbstractType(Var->getLocation(), Type,
8829 diag::err_abstract_type_in_decl,
8830 AbstractVariableType)) {
8831 Var->setInvalidDecl();
8832 return;
8833 }
8834
Douglas Gregor9574af62011-05-21 17:52:48 +00008835 // Check for jumps past the implicit initializer. C++0x
8836 // clarifies that this applies to a "variable with automatic
8837 // storage duration", not a "local variable".
Richard Smithfe2750d2011-10-20 21:42:12 +00008838 // C++11 [stmt.dcl]p3
Douglas Gregor9574af62011-05-21 17:52:48 +00008839 // A program that jumps from a point where a variable with automatic
8840 // storage duration is not in scope to a point where it is in scope is
8841 // ill-formed unless the variable has scalar type, class type with a
8842 // trivial default constructor and a trivial destructor, a cv-qualified
8843 // version of one of these types, or an array of one of the preceding
8844 // types and is declared without an initializer.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008845 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008846 if (const RecordType *Record
8847 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00008848 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Richard Smithfe2750d2011-10-20 21:42:12 +00008849 // Mark the function for further checking even if the looser rules of
8850 // C++11 do not require such checks, so that we can diagnose
8851 // incompatibilities with C++98.
8852 if (!CXXRecord->isPOD())
Alexis Hunt466627c2011-05-11 22:50:12 +00008853 getCurFunction()->setHasBranchProtectedScope();
8854 }
Douglas Gregore6565622010-02-09 07:26:29 +00008855 }
Douglas Gregor9574af62011-05-21 17:52:48 +00008856
8857 // C++03 [dcl.init]p9:
8858 // If no initializer is specified for an object, and the
8859 // object is of (possibly cv-qualified) non-POD class type (or
8860 // array thereof), the object shall be default-initialized; if
8861 // the object is of const-qualified type, the underlying class
8862 // type shall have a user-declared default
8863 // constructor. Otherwise, if no initializer is specified for
8864 // a non- static object, the object and its subobjects, if
8865 // any, have an indeterminate initial value); if the object
8866 // or any of its subobjects are of const-qualified type, the
8867 // program is ill-formed.
8868 // C++0x [dcl.init]p11:
8869 // If no initializer is specified for an object, the object is
8870 // default-initialized; [...].
8871 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8872 InitializationKind Kind
8873 = InitializationKind::CreateDefault(Var->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00008874
8875 InitializationSequence InitSeq(*this, Entity, Kind, None);
8876 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
Douglas Gregor9574af62011-05-21 17:52:48 +00008877 if (Init.isInvalid())
8878 Var->setInvalidDecl();
Sebastian Redla9351792012-02-11 23:51:47 +00008879 else if (Init.get()) {
Douglas Gregor9574af62011-05-21 17:52:48 +00008880 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Sebastian Redla9351792012-02-11 23:51:47 +00008881 // This is important for template substitution.
8882 Var->setInitStyle(VarDecl::CallInit);
8883 }
Douglas Gregor589973b2010-03-08 02:45:10 +00008884
John McCall8b7fd8f12011-01-19 11:48:09 +00008885 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008886 }
8887}
8888
Richard Smith02e85f32011-04-14 22:09:26 +00008889void Sema::ActOnCXXForRangeDecl(Decl *D) {
8890 VarDecl *VD = dyn_cast<VarDecl>(D);
8891 if (!VD) {
8892 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8893 D->setInvalidDecl();
8894 return;
8895 }
8896
8897 VD->setCXXForRangeDecl(true);
8898
8899 // for-range-declaration cannot be given a storage class specifier.
8900 int Error = -1;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00008901 switch (VD->getStorageClass()) {
Richard Smith02e85f32011-04-14 22:09:26 +00008902 case SC_None:
8903 break;
8904 case SC_Extern:
8905 Error = 0;
8906 break;
8907 case SC_Static:
8908 Error = 1;
8909 break;
8910 case SC_PrivateExtern:
8911 Error = 2;
8912 break;
8913 case SC_Auto:
8914 Error = 3;
8915 break;
8916 case SC_Register:
8917 Error = 4;
8918 break;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00008919 case SC_OpenCLWorkGroupLocal:
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00008920 llvm_unreachable("Unexpected storage class");
Richard Smith02e85f32011-04-14 22:09:26 +00008921 }
Richard Smith2316cd82011-09-29 19:11:37 +00008922 if (VD->isConstexpr())
8923 Error = 5;
Richard Smith02e85f32011-04-14 22:09:26 +00008924 if (Error != -1) {
8925 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8926 << VD->getDeclName() << Error;
8927 D->setInvalidDecl();
8928 }
8929}
8930
Richard Smith955bf012014-06-19 11:42:00 +00008931StmtResult
8932Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
8933 IdentifierInfo *Ident,
8934 ParsedAttributes &Attrs,
8935 SourceLocation AttrEnd) {
8936 // C++1y [stmt.iter]p1:
8937 // A range-based for statement of the form
8938 // for ( for-range-identifier : for-range-initializer ) statement
8939 // is equivalent to
8940 // for ( auto&& for-range-identifier : for-range-initializer ) statement
8941 DeclSpec DS(Attrs.getPool().getFactory());
8942
8943 const char *PrevSpec;
8944 unsigned DiagID;
8945 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
8946 getPrintingPolicy());
8947
8948 Declarator D(DS, Declarator::ForContext);
8949 D.SetIdentifier(Ident, IdentLoc);
8950 D.takeAttributes(Attrs, AttrEnd);
8951
8952 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
8953 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
8954 EmptyAttrs, IdentLoc);
8955 Decl *Var = ActOnDeclarator(S, D);
8956 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
8957 FinalizeDeclaration(Var);
8958 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
8959 AttrEnd.isValid() ? AttrEnd : IdentLoc);
8960}
8961
John McCall8b7fd8f12011-01-19 11:48:09 +00008962void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8963 if (var->isInvalidDecl()) return;
8964
John McCall31168b02011-06-15 23:02:42 +00008965 // In ARC, don't allow jumps past the implicit initialization of a
8966 // local retaining variable.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008967 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00008968 var->hasLocalStorage()) {
8969 switch (var->getType().getObjCLifetime()) {
8970 case Qualifiers::OCL_None:
8971 case Qualifiers::OCL_ExplicitNone:
8972 case Qualifiers::OCL_Autoreleasing:
8973 break;
8974
8975 case Qualifiers::OCL_Weak:
8976 case Qualifiers::OCL_Strong:
8977 getCurFunction()->setHasBranchProtectedScope();
8978 break;
8979 }
8980 }
8981
John McCall8a4e2e42014-01-29 08:33:09 +00008982 // Warn about externally-visible variables being defined without a
8983 // prior declaration. We only want to do this for global
8984 // declarations, but we also specifically need to avoid doing it for
8985 // class members because the linkage of an anonymous class can
8986 // change if it's later given a typedef name.
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008987 if (var->isThisDeclarationADefinition() &&
John McCall8a4e2e42014-01-29 08:33:09 +00008988 var->getDeclContext()->getRedeclContext()->isFileContext() &&
Eli Friedman1f5d8882013-09-24 23:10:08 +00008989 var->isExternallyVisible() && var->hasLinkage() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008990 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
8991 var->getLocation())) {
Eli Friedman7d14b3c2012-10-23 20:19:32 +00008992 // Find a previous declaration that's not a definition.
8993 VarDecl *prev = var->getPreviousDecl();
8994 while (prev && prev->isThisDeclarationADefinition())
8995 prev = prev->getPreviousDecl();
8996
8997 if (!prev)
8998 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8999 }
9000
Reid Kleckner92fc0172014-04-30 17:10:18 +00009001 if (var->getTLSKind() == VarDecl::TLS_Static) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00009002 const Expr *Culprit;
Reid Kleckner92fc0172014-04-30 17:10:18 +00009003 if (var->getType().isDestructedType()) {
9004 // GNU C++98 edits for __thread, [basic.start.term]p3:
9005 // The type of an object with thread storage duration shall not
9006 // have a non-trivial destructor.
9007 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9008 if (getLangOpts().CPlusPlus11)
9009 Diag(var->getLocation(), diag::note_use_thread_local);
9010 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9011 !var->getInit()->isConstantInitializer(
Abramo Bagnara847c6602014-05-22 19:20:46 +00009012 Context, var->getType()->isReferenceType(), &Culprit)) {
Reid Kleckner92fc0172014-04-30 17:10:18 +00009013 // GNU C++98 edits for __thread, [basic.start.init]p4:
9014 // An object of thread storage duration shall not require dynamic
9015 // initialization.
9016 // FIXME: Need strict checking here.
Abramo Bagnara847c6602014-05-22 19:20:46 +00009017 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9018 << Culprit->getSourceRange();
Reid Kleckner92fc0172014-04-30 17:10:18 +00009019 if (getLangOpts().CPlusPlus11)
9020 Diag(var->getLocation(), diag::note_use_thread_local);
9021 }
9022
Richard Smith6ea1a4d2013-04-14 20:11:31 +00009023 }
9024
Warren Huntc3b18962014-04-08 22:30:47 +00009025 if (var->isThisDeclarationADefinition() &&
9026 ActiveTemplateInstantiations.empty()) {
9027 PragmaStack<StringLiteral *> *Stack = nullptr;
9028 int SectionFlags = PSF_Implicit | PSF_Read;
9029 if (var->getType().isConstQualified())
9030 Stack = &ConstSegStack;
9031 else if (!var->getInit()) {
9032 Stack = &BSSSegStack;
9033 SectionFlags |= PSF_Write;
9034 } else {
9035 Stack = &DataSegStack;
9036 SectionFlags |= PSF_Write;
9037 }
9038 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9039 var->addAttr(
9040 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9041 Stack->CurrentValue->getString(),
9042 Stack->CurrentPragmaLocation));
9043 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9044 if (UnifySection(SA->getName(), SectionFlags, var))
9045 var->dropAttr<SectionAttr>();
9046 }
9047
John McCall8b7fd8f12011-01-19 11:48:09 +00009048 // All the following checks are C++ only.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009049 if (!getLangOpts().CPlusPlus) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009050
Richard Smithde63d362012-11-09 23:03:14 +00009051 QualType type = var->getType();
9052 if (type->isDependentType()) return;
John McCall8b7fd8f12011-01-19 11:48:09 +00009053
9054 // __block variables might require us to capture a copy-initializer.
9055 if (var->hasAttr<BlocksAttr>()) {
9056 // It's currently invalid to ever have a __block variable with an
9057 // array type; should we diagnose that here?
9058
9059 // Regardless, we don't want to ignore array nesting when
9060 // constructing this copy.
John McCall8b7fd8f12011-01-19 11:48:09 +00009061 if (type->isStructureOrClassType()) {
John McCalleaef89b2013-03-22 02:10:40 +00009062 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
John McCall8b7fd8f12011-01-19 11:48:09 +00009063 SourceLocation poi = var->getLocation();
John McCall113bee02012-03-10 09:33:50 +00009064 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
Douglas Gregorca006452013-03-07 22:38:24 +00009065 ExprResult result
9066 = PerformMoveOrCopyInitialization(
9067 InitializedEntity::InitializeBlock(poi, type, false),
9068 var, var->getType(), varRef, /*AllowNRVO=*/true);
John McCall8b7fd8f12011-01-19 11:48:09 +00009069 if (!result.isInvalid()) {
9070 result = MaybeCreateExprWithCleanups(result);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009071 Expr *init = result.getAs<Expr>();
John McCall8b7fd8f12011-01-19 11:48:09 +00009072 Context.setBlockVarCopyInits(var, init);
9073 }
9074 }
9075 }
9076
Richard Smitheda3c842011-11-07 22:16:17 +00009077 Expr *Init = var->getInit();
9078 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
Richard Smithde63d362012-11-09 23:03:14 +00009079 QualType baseType = Context.getBaseElementType(type);
Richard Smitheda3c842011-11-07 22:16:17 +00009080
Richard Smithbf830092012-10-29 18:26:47 +00009081 if (!var->getDeclContext()->isDependentContext() &&
9082 Init && !Init->isValueDependent()) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009083 if (IsGlobal && !var->isConstexpr() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009084 !getDiagnostics().isIgnored(diag::warn_global_constructor,
9085 var->getLocation())) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00009086 // Warn about globals which don't have a constant initializer. Don't
9087 // warn about globals with a non-trivial destructor because we already
9088 // warned about them.
9089 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9090 if (!(RD && !RD->hasTrivialDestructor()) &&
9091 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9092 Diag(var->getLocation(), diag::warn_global_constructor)
9093 << Init->getSourceRange();
9094 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00009095
Richard Smithd0b4dd62011-12-19 06:19:21 +00009096 if (var->isConstexpr()) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009097 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00009098 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9099 SourceLocation DiagLoc = var->getLocation();
9100 // If the note doesn't add any useful information other than a source
9101 // location, fold it into the primary diagnostic.
9102 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9103 diag::note_invalid_subexpr_in_const_expr) {
9104 DiagLoc = Notes[0].first;
9105 Notes.clear();
9106 }
9107 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9108 << var << Init->getSourceRange();
9109 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9110 Diag(Notes[I].first, Notes[I].second);
9111 }
Daniel Dunbar9d355812012-03-09 01:51:51 +00009112 } else if (var->isUsableInConstantExpressions(Context)) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00009113 // Check whether the initializer of a const variable of integral or
9114 // enumeration type is an ICE now, since we can't tell whether it was
9115 // initialized by a constant expression if we check later.
9116 var->checkInitIsICE();
9117 }
Richard Smitheda3c842011-11-07 22:16:17 +00009118 }
John McCall8b7fd8f12011-01-19 11:48:09 +00009119
9120 // Require the destructor.
9121 if (const RecordType *recordType = baseType->getAs<RecordType>())
9122 FinalizeVarWithDestructor(var, recordType);
9123}
9124
Richard Smithb2bc2e62011-02-21 20:05:19 +00009125/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9126/// any semantic actions necessary after any initializer has been attached.
9127void
9128Sema::FinalizeDeclaration(Decl *ThisDecl) {
9129 // Note that we are no longer parsing the initializer for this declaration.
9130 ParsingInitForAutoVars.erase(ThisDecl);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009131
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009132 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
Rafael Espindola60470f12013-01-03 04:05:19 +00009133 if (!VD)
9134 return;
9135
Nico Rieckf8e8b5f2014-01-21 23:54:36 +00009136 checkAttributesAfterMerging(*this, *VD);
9137
Hans Wennborgef2272c2014-06-18 15:55:13 +00009138 // Static locals inherit dll attributes from their function.
9139 if (VD->isStaticLocal()) {
9140 if (FunctionDecl *FD =
9141 dyn_cast<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9142 if (Attr *A = getDLLAttr(FD)) {
9143 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9144 NewAttr->setInherited(true);
9145 VD->addAttr(NewAttr);
9146 }
9147 }
9148 }
9149
Nico Rieck078d2f82014-05-29 16:50:20 +00009150 // Imported static data members cannot be defined out-of-line.
9151 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) {
9152 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9153 VD->isThisDeclarationADefinition()) {
Hans Wennborge9af3162014-06-04 00:18:41 +00009154 // We allow definitions of dllimport class template static data members
9155 // with a warning.
Hans Wennborgcd959222014-06-09 18:30:28 +00009156 CXXRecordDecl *Context =
9157 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
Hans Wennborge9af3162014-06-04 00:18:41 +00009158 bool IsClassTemplateMember =
Hans Wennborgcd959222014-06-09 18:30:28 +00009159 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9160 Context->getDescribedClassTemplate();
Hans Wennborge9af3162014-06-04 00:18:41 +00009161
Nico Rieck078d2f82014-05-29 16:50:20 +00009162 Diag(VD->getLocation(),
Hans Wennborge9af3162014-06-04 00:18:41 +00009163 IsClassTemplateMember
9164 ? diag::warn_attribute_dllimport_static_field_definition
9165 : diag::err_attribute_dllimport_static_field_definition);
Nico Rieck078d2f82014-05-29 16:50:20 +00009166 Diag(IA->getLocation(), diag::note_attribute);
Hans Wennborge9af3162014-06-04 00:18:41 +00009167 if (!IsClassTemplateMember)
9168 VD->setInvalidDecl();
Nico Rieck078d2f82014-05-29 16:50:20 +00009169 }
9170 }
9171
Rafael Espindola87198cd2013-08-16 23:18:50 +00009172 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9173 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00009174 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
Rafael Espindola87198cd2013-08-16 23:18:50 +00009175 VD->dropAttr<UsedAttr>();
9176 }
9177 }
9178
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009179 if (!VD->isInvalidDecl() &&
9180 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9181 if (const VarDecl *Def = VD->getDefinition()) {
9182 if (Def->hasAttr<AliasAttr>()) {
9183 Diag(VD->getLocation(), diag::err_tentative_after_alias)
9184 << VD->getDeclName();
9185 Diag(Def->getLocation(), diag::note_previous_definition);
9186 VD->setInvalidDecl();
9187 }
9188 }
9189 }
9190
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009191 const DeclContext *DC = VD->getDeclContext();
9192 // If there's a #pragma GCC visibility in scope, and this isn't a class
9193 // member, set the visibility of this variable.
John McCall8a4e2e42014-01-29 08:33:09 +00009194 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
Rafael Espindoladb1a4772013-02-22 17:59:16 +00009195 AddPushedVisibilityAttribute(VD);
9196
Richard Smithc3926172014-04-02 18:28:36 +00009197 // FIXME: Warn on unused templates.
Richard Smith6c6ef822014-04-25 19:21:40 +00009198 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9199 !isa<VarTemplatePartialSpecializationDecl>(VD))
Rafael Espindolad2ecc132013-01-03 04:29:20 +00009200 MarkUnusedFileScopedDecl(VD);
9201
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009202 // Now we have parsed the initializer and can update the table of magic
9203 // tag values.
Rafael Espindola60470f12013-01-03 04:05:19 +00009204 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9205 !VD->getType()->isIntegralOrEnumerationType())
9206 return;
9207
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00009208 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
Rafael Espindola60470f12013-01-03 04:05:19 +00009209 const Expr *MagicValueExpr = VD->getInit();
9210 if (!MagicValueExpr) {
9211 continue;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009212 }
Rafael Espindola60470f12013-01-03 04:05:19 +00009213 llvm::APSInt MagicValueInt;
9214 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9215 Diag(I->getRange().getBegin(),
9216 diag::err_type_tag_for_datatype_not_ice)
9217 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9218 continue;
9219 }
9220 if (MagicValueInt.getActiveBits() > 64) {
9221 Diag(I->getRange().getBegin(),
9222 diag::err_type_tag_for_datatype_too_large)
9223 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9224 continue;
9225 }
9226 uint64_t MagicValue = MagicValueInt.getZExtValue();
9227 RegisterTypeTagForDatatype(I->getArgumentKind(),
9228 MagicValue,
9229 I->getMatchingCType(),
9230 I->getLayoutCompatible(),
9231 I->getMustBeNull());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009232 }
Richard Smithb2bc2e62011-02-21 20:05:19 +00009233}
9234
Rafael Espindolaab417692013-07-09 12:05:01 +00009235Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9236 ArrayRef<Decl *> Group) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009237 SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009238
9239 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00009240 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00009241
Craig Topperc3ec1492014-05-26 06:22:03 +00009242 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009243 for (unsigned i = 0, e = Group.size(); i != e; ++i)
David Majnemer50ce8352013-09-17 23:57:10 +00009244 if (Decl *D = Group[i]) {
9245 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9246 if (!FirstDeclaratorInGroup)
9247 FirstDeclaratorInGroup = DD;
Richard Smith2abf6762011-02-23 00:37:57 +00009248 Decls.push_back(D);
David Majnemer50ce8352013-09-17 23:57:10 +00009249 }
Richard Smith2abf6762011-02-23 00:37:57 +00009250
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009251 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
David Majnemer50ce8352013-09-17 23:57:10 +00009252 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
David Majnemer2206bf52014-03-05 08:57:59 +00009253 HandleTagNumbering(*this, Tag, S);
David Majnemer50ce8352013-09-17 23:57:10 +00009254 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9255 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9256 }
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009257 }
David Blaikie095deba2012-11-14 01:52:05 +00009258
Rafael Espindolaab417692013-07-09 12:05:01 +00009259 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
Richard Smith2abf6762011-02-23 00:37:57 +00009260}
9261
9262/// BuildDeclaratorGroup - convert a list of declarations into a declaration
9263/// group, performing any necessary semantic checking.
9264Sema::DeclGroupPtrTy
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00009265Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
Richard Smith2abf6762011-02-23 00:37:57 +00009266 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00009267 // C++0x [dcl.spec.auto]p7:
9268 // If the type deduced for the template parameter U is not the same in each
9269 // deduction, the program is ill-formed.
9270 // FIXME: When initializer-list support is added, a distinction is needed
9271 // between the deduced type U and the deduced type which 'auto' stands for.
9272 // auto a = 0, b = { 1, 2, 3 };
9273 // is legal because the deduced type U is 'int' in both cases.
Rafael Espindolaab417692013-07-09 12:05:01 +00009274 if (TypeMayContainAuto && Group.size() > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00009275 QualType Deduced;
9276 CanQualType DeducedCanon;
Craig Topperc3ec1492014-05-26 06:22:03 +00009277 VarDecl *DeducedDecl = nullptr;
Rafael Espindolaab417692013-07-09 12:05:01 +00009278 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
Richard Smith30482bc2011-02-20 03:19:35 +00009279 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9280 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00009281 // Don't reissue diagnostics when instantiating a template.
9282 if (AT && D->isInvalidDecl())
9283 break;
Richard Smith27d807c2013-04-30 13:56:41 +00009284 QualType U = AT ? AT->getDeducedType() : QualType();
9285 if (!U.isNull()) {
Richard Smith30482bc2011-02-20 03:19:35 +00009286 CanQualType UCanon = Context.getCanonicalType(U);
9287 if (Deduced.isNull()) {
9288 Deduced = U;
9289 DeducedCanon = UCanon;
9290 DeducedDecl = D;
9291 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00009292 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9293 diag::err_auto_different_deductions)
Richard Smith489e4e02013-05-04 04:19:27 +00009294 << (AT->isDecltypeAuto() ? 1 : 0)
Richard Smith30482bc2011-02-20 03:19:35 +00009295 << Deduced << DeducedDecl->getDeclName()
9296 << U << D->getDeclName()
9297 << DeducedDecl->getInit()->getSourceRange()
9298 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00009299 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00009300 break;
9301 }
9302 }
9303 }
9304 }
9305 }
9306
Rafael Espindolaab417692013-07-09 12:05:01 +00009307 ActOnDocumentableDecls(Group);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009308
Rafael Espindolaab417692013-07-09 12:05:01 +00009309 return DeclGroupPtrTy::make(
9310 DeclGroupRef::Create(Context, Group.data(), Group.size()));
Chris Lattner776fac82007-06-09 00:53:06 +00009311}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00009312
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009313void Sema::ActOnDocumentableDecl(Decl *D) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009314 ActOnDocumentableDecls(D);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009315}
9316
Rafael Espindolaab417692013-07-09 12:05:01 +00009317void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009318 // Don't parse the comment if Doxygen diagnostics are ignored.
Rafael Espindolaab417692013-07-09 12:05:01 +00009319 if (Group.empty() || !Group[0])
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009320 return;
9321
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009322 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009323 return;
9324
Rafael Espindolaab417692013-07-09 12:05:01 +00009325 if (Group.size() >= 2) {
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009326 // This is a decl group. Normally it will contain only declarations
Rafael Espindolaab417692013-07-09 12:05:01 +00009327 // produced from declarator list. But in case we have any definitions or
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009328 // additional declaration references:
9329 // 'typedef struct S {} S;'
9330 // 'typedef struct S *S;'
9331 // 'struct S *pS;'
9332 // FinalizeDeclaratorGroup adds these as separate declarations.
9333 Decl *MaybeTagDecl = Group[0];
9334 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Rafael Espindolaab417692013-07-09 12:05:01 +00009335 Group = Group.slice(1);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009336 }
9337 }
9338
9339 // See if there are any new comments that are not attached to a decl.
9340 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9341 if (!Comments.empty() &&
9342 !Comments.back()->isAttached()) {
9343 // There is at least one comment that not attached to a decl.
9344 // Maybe it should be attached to one of these decls?
9345 //
9346 // Note that this way we pick up not only comments that precede the
9347 // declaration, but also comments that *follow* the declaration -- thanks to
9348 // the lookahead in the lexer: we've consumed the semicolon and looked
9349 // ahead through comments.
Rafael Espindolaab417692013-07-09 12:05:01 +00009350 for (unsigned i = 0, e = Group.size(); i != e; ++i)
Dmitri Gribenko6743e042012-09-29 11:40:46 +00009351 Context.getCommentForDecl(Group[i], &PP);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00009352 }
9353}
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009354
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009355/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9356/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00009357Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00009358 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00009359
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009360 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Faisal Vali2b391ab2013-09-26 19:54:12 +00009361
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009362 // C++03 [dcl.stc]p2 also permits 'auto'.
John McCall8e7d6562010-08-26 03:08:43 +00009363 VarDecl::StorageClass StorageClass = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009364 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00009365 StorageClass = SC_Register;
David Blaikiebbafb8a2012-03-11 07:00:24 +00009366 } else if (getLangOpts().CPlusPlus &&
Peter Collingbourne99eddc32011-10-21 11:55:09 +00009367 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9368 StorageClass = SC_Auto;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00009369 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009370 Diag(DS.getStorageClassSpecLoc(),
9371 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00009372 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009373 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009374
Richard Smithb4a9e862013-04-12 22:46:28 +00009375 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9376 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9377 << DeclSpec::getSpecifierName(TSCS);
9378 if (DS.isConstexprSpecified())
9379 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
Richard Smitha77a0a62011-08-15 21:04:07 +00009380 << 0;
Eli Friedmand5c0eed2009-04-19 20:27:55 +00009381
Richard Smithb4a9e862013-04-12 22:46:28 +00009382 DiagnoseFunctionSpecifiers(DS);
Eli Friedman574c7452009-04-07 19:37:57 +00009383
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00009384 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00009385 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00009386
David Blaikiebbafb8a2012-03-11 07:00:24 +00009387 if (getLangOpts().CPlusPlus) {
Douglas Gregor27b4c162010-12-23 22:44:42 +00009388 // Check that there are no default arguments inside the type of this
9389 // parameter.
9390 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00009391
9392 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9393 if (D.getCXXScopeSpec().isSet()) {
9394 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9395 << D.getCXXScopeSpec().getRange();
9396 D.getCXXScopeSpec().clear();
9397 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00009398 }
9399
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009400 // Ensure we have a valid name
Craig Topperc3ec1492014-05-26 06:22:03 +00009401 IdentifierInfo *II = nullptr;
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009402 if (D.hasName()) {
9403 II = D.getIdentifier();
9404 if (!II) {
9405 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
Aaron Ballmanfee0cd42014-01-03 13:34:55 +00009406 << GetNameForDeclarator(D).getName();
Alexis Hunta56cbcc2010-11-03 01:07:06 +00009407 D.setInvalidType(true);
9408 }
9409 }
9410
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009411 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00009412 if (II) {
John McCall84f02672010-03-18 06:42:38 +00009413 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9414 ForRedeclaration);
9415 LookupName(R, S);
9416 if (R.isSingleResult()) {
9417 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00009418 if (PrevDecl->isTemplateParameter()) {
9419 // Maybe we will complain about the shadowed template parameter.
9420 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9421 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00009422 PrevDecl = nullptr;
John McCall48871652010-08-21 09:40:31 +00009423 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00009424 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00009425 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009426
Chris Lattnerd9773512009-01-21 02:38:50 +00009427 // Recover by removing the name
Craig Topperc3ec1492014-05-26 06:22:03 +00009428 II = nullptr;
9429 D.SetIdentifier(nullptr, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009430 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00009431 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009432 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009433 }
Steve Naroff773df5c2007-08-07 22:44:21 +00009434
John McCallf7b2fb52010-01-22 00:28:27 +00009435 // Temporarily put parameter variables in the translation unit, not
9436 // the enclosing context. This prevents them from accidentally
9437 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00009438 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009439 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00009440 D.getIdentifierLoc(), II,
9441 parmDeclType, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009442 StorageClass);
Mike Stump11289f42009-09-09 15:08:12 +00009443
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009444 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00009445 New->setInvalidDecl();
9446
9447 assert(S->isFunctionPrototypeScope());
9448 assert(S->getFunctionPrototypeDepth() >= 1);
9449 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9450 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00009451
Douglas Gregor91f84212008-12-11 16:49:14 +00009452 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00009453 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009454 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00009455 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00009456
Douglas Gregor758a8692009-06-17 21:51:59 +00009457 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00009458
Douglas Gregor41866812011-09-12 18:37:38 +00009459 if (D.getDeclSpec().isModulePrivateSpecified())
9460 Diag(New->getLocation(), diag::err_module_private_local)
9461 << 1 << New->getDeclName()
9462 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9463 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9464
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00009465 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00009466 Diag(New->getLocation(), diag::err_block_on_nonlocal);
9467 }
John McCall48871652010-08-21 09:40:31 +00009468 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00009469}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00009470
John McCalla3ccba02010-06-04 11:21:44 +00009471/// \brief Synthesizes a variable for a parameter arising from a
9472/// typedef.
9473ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9474 SourceLocation Loc,
9475 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00009476 /* FIXME: setting StartLoc == Loc.
9477 Would it be worth to modify callers so as to provide proper source
9478 location for the unnamed parameters, embedding the parameter's type? */
Craig Topperc3ec1492014-05-26 06:22:03 +00009479 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
John McCalla3ccba02010-06-04 11:21:44 +00009480 T, Context.getTrivialTypeSourceInfo(T, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +00009481 SC_None, nullptr);
John McCalla3ccba02010-06-04 11:21:44 +00009482 Param->setImplicit();
9483 return Param;
9484}
9485
John McCallc5990642010-08-24 09:05:15 +00009486void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9487 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00009488 // Don't diagnose unused-parameter errors in template instantiations; we
9489 // will already have done so in the template itself.
9490 if (!ActiveTemplateInstantiations.empty())
9491 return;
9492
9493 for (; Param != ParamEnd; ++Param) {
Eli Friedmanc09e0552012-01-13 23:41:25 +00009494 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
John McCallc5990642010-08-24 09:05:15 +00009495 !(*Param)->hasAttr<UnusedAttr>()) {
9496 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9497 << (*Param)->getDeclName();
9498 }
9499 }
9500}
9501
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009502void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9503 ParmVarDecl * const *ParamEnd,
9504 QualType ReturnTy,
9505 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009506 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009507 return;
9508
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009509 // Warn if the return value is pass-by-value and larger than the specified
9510 // threshold.
Eli Friedman7f21bd72012-01-09 23:46:59 +00009511 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009512 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009513 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009514 Diag(D->getLocation(), diag::warn_return_value_size)
9515 << D->getDeclName() << Size;
9516 }
9517
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009518 // Warn if any parameter is pass-by-value and larger than the specified
9519 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009520 for (; Param != ParamEnd; ++Param) {
9521 QualType T = (*Param)->getType();
Eli Friedman7f21bd72012-01-09 23:46:59 +00009522 if (T->isDependentType() || !T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009523 continue;
9524 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00009525 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00009526 Diag((*Param)->getLocation(), diag::warn_parameter_size)
9527 << (*Param)->getDeclName() << Size;
9528 }
9529}
9530
Abramo Bagnaradff19302011-03-08 08:55:46 +00009531ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9532 SourceLocation NameLoc, IdentifierInfo *Name,
9533 QualType T, TypeSourceInfo *TSInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009534 VarDecl::StorageClass StorageClass) {
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009535 // In ARC, infer a lifetime qualifier for appropriate parameter types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009536 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00009537 T.getObjCLifetime() == Qualifiers::OCL_None &&
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009538 T->isObjCLifetimeType()) {
9539
9540 Qualifiers::ObjCLifetime lifetime;
9541
9542 // Special cases for arrays:
9543 // - if it's const, use __unsafe_unretained
9544 // - otherwise, it's an error
9545 if (T->isArrayType()) {
9546 if (!T.isConstQualified()) {
9547 DelayedDiagnostics.add(
9548 sema::DelayedDiagnostic::makeForbiddenType(
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00009549 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
Reid Kleckner17aeeeb2013-06-08 18:19:52 +00009550 }
9551 lifetime = Qualifiers::OCL_ExplicitNone;
9552 } else {
9553 lifetime = T->getObjCARCImplicitLifetime();
9554 }
9555 T = Context.getLifetimeQualifiedType(T, lifetime);
John McCall31168b02011-06-15 23:02:42 +00009556 }
9557
Abramo Bagnaradff19302011-03-08 08:55:46 +00009558 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00009559 Context.getAdjustedParameterType(T),
9560 TSInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009561 StorageClass, nullptr);
Douglas Gregor940bca72010-04-12 07:48:19 +00009562
9563 // Parameters can not be abstract class types.
9564 // For record types, this is done by the AbstractClassUsageDiagnoser once
9565 // the class has been completely parsed.
9566 if (!CurContext->isRecord() &&
9567 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9568 AbstractParamType))
9569 New->setInvalidDecl();
9570
9571 // Parameter declarators cannot be interface types. All ObjC objects are
9572 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00009573 if (T->isObjCObjectType()) {
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009574 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
Douglas Gregor940bca72010-04-12 07:48:19 +00009575 Diag(NameLoc,
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009576 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
Fariborz Jahanian7a055362012-05-09 21:49:29 +00009577 << FixItHint::CreateInsertion(TypeEndLoc, "*");
Fariborz Jahanian6507135e2011-07-26 17:58:54 +00009578 T = Context.getObjCObjectPointerType(T);
9579 New->setType(T);
Douglas Gregor940bca72010-04-12 07:48:19 +00009580 }
9581
9582 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9583 // duration shall not be qualified by an address-space qualifier."
9584 // Since all parameters have automatic store duration, they can not have
9585 // an address space.
9586 if (T.getAddressSpace() != 0) {
Fraser Cormack01648e02014-04-15 11:38:29 +00009587 // OpenCL allows function arguments declared to be an array of a type
9588 // to be qualified with an address space.
9589 if (!(getLangOpts().OpenCL && T->isArrayType())) {
9590 Diag(NameLoc, diag::err_arg_with_address_space);
9591 New->setInvalidDecl();
9592 }
Douglas Gregor940bca72010-04-12 07:48:19 +00009593 }
9594
9595 return New;
9596}
9597
Douglas Gregor170512f2009-04-01 23:51:29 +00009598void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9599 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009600 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009601
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009602 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9603 // for a K&R function.
9604 if (!FTI.hasPrototype) {
Alp Tokerc5350722014-02-26 22:27:52 +00009605 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00009606 --i;
Craig Topperc3ec1492014-05-26 06:22:03 +00009607 if (FTI.Params[i].Param == nullptr) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009608 SmallString<256> Code;
Alp Tokerc5350722014-02-26 22:27:52 +00009609 llvm::raw_svector_ostream(Code)
9610 << " int " << FTI.Params[i].Ident->getName() << ";\n";
9611 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9612 << FTI.Params[i].Ident
9613 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00009614
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009615 // Implicitly declare the argument as type 'int' for lack of a better
9616 // type.
John McCall084e83d2011-03-24 11:26:52 +00009617 AttributeFactory attrs;
9618 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009619 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00009620 unsigned DiagID; // unused
Alp Tokerc5350722014-02-26 22:27:52 +00009621 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9622 DiagID, Context.getPrintingPolicy());
Abramo Bagnara71f32c12012-10-04 21:38:29 +00009623 // Use the identifier location for the type source range.
Alp Tokerc5350722014-02-26 22:27:52 +00009624 DS.SetRangeStart(FTI.Params[i].IdentLoc);
9625 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009626 Declarator ParamD(DS, Declarator::KNRTypeListContext);
Alp Tokerc5350722014-02-26 22:27:52 +00009627 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9628 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00009629 }
9630 }
Mike Stump11289f42009-09-09 15:08:12 +00009631 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00009632}
9633
Richard Smith79a52e52012-04-17 22:30:01 +00009634Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009635 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00009636 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00009637 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00009638
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00009639 D.setFunctionDefinitionKind(FDK_Definition);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00009640 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
Chris Lattner5bbb3c82009-03-29 16:50:03 +00009641 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00009642}
9643
Hans Wennborga926d842014-05-23 20:37:38 +00009644void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
9645 Consumer.HandleInlineMethodDefinition(D);
9646}
9647
Anders Carlsson2a45e402012-12-18 01:29:20 +00009648static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9649 const FunctionDecl*& PossibleZeroParamPrototype) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009650 // Don't warn about invalid declarations.
9651 if (FD->isInvalidDecl())
9652 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009653
Anders Carlsson31c7e882009-12-09 03:30:09 +00009654 // Or declarations that aren't global.
9655 if (!FD->isGlobal())
9656 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009657
Anders Carlsson31c7e882009-12-09 03:30:09 +00009658 // Don't warn about C++ member functions.
9659 if (isa<CXXMethodDecl>(FD))
9660 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009661
Anders Carlsson31c7e882009-12-09 03:30:09 +00009662 // Don't warn about 'main'.
9663 if (FD->isMain())
9664 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009665
Anders Carlsson31c7e882009-12-09 03:30:09 +00009666 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00009667 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009668 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00009669
9670 // Don't warn about function templates.
9671 if (FD->getDescribedFunctionTemplate())
9672 return false;
9673
9674 // Don't warn about function template specializations.
9675 if (FD->isFunctionTemplateSpecialization())
9676 return false;
9677
Tanya Lattner4bfc3552012-07-26 00:08:28 +00009678 // Don't warn for OpenCL kernels.
9679 if (FD->hasAttr<OpenCLKernelAttr>())
9680 return false;
Richard Smith541b38b2013-09-20 01:15:31 +00009681
Anders Carlsson31c7e882009-12-09 03:30:09 +00009682 bool MissingPrototype = true;
Douglas Gregorec9fd132012-01-14 16:38:05 +00009683 for (const FunctionDecl *Prev = FD->getPreviousDecl();
9684 Prev; Prev = Prev->getPreviousDecl()) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009685 // Ignore any declarations that occur in function or method
9686 // scope, because they aren't visible from the header.
Richard Smith541b38b2013-09-20 01:15:31 +00009687 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
Anders Carlsson31c7e882009-12-09 03:30:09 +00009688 continue;
Richard Smith541b38b2013-09-20 01:15:31 +00009689
Anders Carlsson31c7e882009-12-09 03:30:09 +00009690 MissingPrototype = !Prev->getType()->isFunctionProtoType();
Anders Carlsson2a45e402012-12-18 01:29:20 +00009691 if (FD->getNumParams() == 0)
9692 PossibleZeroParamPrototype = Prev;
Anders Carlsson31c7e882009-12-09 03:30:09 +00009693 break;
9694 }
Richard Smith541b38b2013-09-20 01:15:31 +00009695
Anders Carlsson31c7e882009-12-09 03:30:09 +00009696 return MissingPrototype;
9697}
9698
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009699void
9700Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9701 const FunctionDecl *EffectiveDefinition) {
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009702 // Don't complain if we're in GNU89 mode and the previous definition
9703 // was an extern inline function.
Rafael Espindolad53ffa02013-10-22 21:39:03 +00009704 const FunctionDecl *Definition = EffectiveDefinition;
9705 if (!Definition)
9706 if (!FD->isDefined(Definition))
9707 return;
9708
9709 if (canRedefineFunction(Definition, getLangOpts()))
Rafael Espindola69f53102013-10-22 15:18:22 +00009710 return;
9711
9712 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9713 Definition->getStorageClass() == SC_Extern)
9714 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
David Blaikiebbafb8a2012-03-11 07:00:24 +00009715 << FD->getDeclName() << getLangOpts().CPlusPlus;
Rafael Espindola69f53102013-10-22 15:18:22 +00009716 else
9717 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9718
9719 Diag(Definition->getLocation(), diag::note_previous_definition);
9720 FD->setInvalidDecl();
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009721}
Faisal Valia17d19f2013-11-07 05:17:06 +00009722
9723
Faisal Valic1a6dc42013-10-23 16:10:50 +00009724static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9725 Sema &S) {
9726 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
Faisal Vali524ca282013-11-12 01:40:44 +00009727
9728 LambdaScopeInfo *LSI = S.PushLambdaScope();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009729 LSI->CallOperator = CallOperator;
9730 LSI->Lambda = LambdaClass;
Alp Toker314cc812014-01-25 16:55:45 +00009731 LSI->ReturnType = CallOperator->getReturnType();
Faisal Valic1a6dc42013-10-23 16:10:50 +00009732 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9733
9734 if (LCD == LCD_None)
9735 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9736 else if (LCD == LCD_ByCopy)
9737 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9738 else if (LCD == LCD_ByRef)
9739 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9740 DeclarationNameInfo DNI = CallOperator->getNameInfo();
9741
9742 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9743 LSI->Mutable = !CallOperator->isConst();
9744
Faisal Valia17d19f2013-11-07 05:17:06 +00009745 // Add the captures to the LSI so they can be noted as already
9746 // captured within tryCaptureVar.
Aaron Ballman6def98a2014-03-13 17:08:33 +00009747 for (const auto &C : LambdaClass->captures()) {
9748 if (C.capturesVariable()) {
9749 VarDecl *VD = C.getCapturedVar();
Faisal Valia17d19f2013-11-07 05:17:06 +00009750 if (VD->isInitCapture())
9751 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9752 QualType CaptureType = VD->getType();
Aaron Ballman6def98a2014-03-13 17:08:33 +00009753 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
Faisal Valia17d19f2013-11-07 05:17:06 +00009754 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
Aaron Ballman6def98a2014-03-13 17:08:33 +00009755 /*RefersToEnclosingLocal*/true, C.getLocation(),
9756 /*EllipsisLoc*/C.isPackExpansion()
9757 ? C.getEllipsisLoc() : SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009758 CaptureType, /*Expr*/ nullptr);
9759
Aaron Ballman6def98a2014-03-13 17:08:33 +00009760 } else if (C.capturesThis()) {
9761 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009762 S.getCurrentThisType(), /*Expr*/ nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00009763 }
9764 }
Faisal Valic1a6dc42013-10-23 16:10:50 +00009765}
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009766
John McCall48871652010-08-21 09:40:31 +00009767Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00009768 // Clear the last template instantiation error context.
9769 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9770
Douglas Gregor17a7c122009-06-24 00:54:41 +00009771 if (!D)
9772 return D;
Craig Topperc3ec1492014-05-26 06:22:03 +00009773 FunctionDecl *FD = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009774
John McCall48871652010-08-21 09:40:31 +00009775 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009776 FD = FunTmpl->getTemplatedDecl();
9777 else
John McCall48871652010-08-21 09:40:31 +00009778 FD = cast<FunctionDecl>(D);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009779 // If we are instantiating a generic lambda call operator, push
9780 // a LambdaScopeInfo onto the function stack. But use the information
Faisal Valic1a6dc42013-10-23 16:10:50 +00009781 // that's already been calculated (ActOnLambdaExpr) to prime the current
9782 // LambdaScopeInfo.
9783 // When the template operator is being specialized, the LambdaScopeInfo,
9784 // has to be properly restored so that tryCaptureVariable doesn't try
9785 // and capture any new variables. In addition when calculating potential
9786 // captures during transformation of nested lambdas, it is necessary to
9787 // have the LSI properly restored.
Faisal Valif9a9af32013-09-29 20:15:45 +00009788 if (isGenericLambdaCallOperatorSpecialization(FD)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00009789 assert(ActiveTemplateInstantiations.size() &&
9790 "There should be an active template instantiation on the stack "
9791 "when instantiating a generic lambda!");
Faisal Valic1a6dc42013-10-23 16:10:50 +00009792 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
Faisal Vali2b391ab2013-09-26 19:54:12 +00009793 }
9794 else
9795 // Enter a new function scope
9796 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00009797
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009798 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00009799 if (!FD->isLateTemplateParsed())
9800 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00009801
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009802 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00009803 if (unsigned BuiltinID = FD->getBuiltinID()) {
Rafael Espindola3b3a1662013-06-13 18:34:17 +00009804 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9805 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009806 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00009807 FD->setInvalidDecl();
9808 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00009809 }
9810
Eli Friedman9ad72442009-03-04 07:30:59 +00009811 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00009812 // (C99 6.9.1p3, C++ [dcl.fct]p6).
Alp Toker314cc812014-01-25 16:55:45 +00009813 QualType ResultType = FD->getReturnType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00009814 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00009815 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00009816 RequireCompleteType(FD->getLocation(), ResultType,
9817 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00009818 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00009819
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009820 // GNU warning -Wmissing-prototypes:
9821 // Warn if a global function is defined without a previous
9822 // prototype declaration. This warning is issued even if the
9823 // definition itself provides a prototype. The aim is to detect
9824 // global functions that fail to be declared in header files.
Craig Topperc3ec1492014-05-26 06:22:03 +00009825 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
Anders Carlsson2a45e402012-12-18 01:29:20 +00009826 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
Anders Carlsson31c7e882009-12-09 03:30:09 +00009827 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Richard Smithef87be32013-06-25 20:34:17 +00009828
Anders Carlsson2a45e402012-12-18 01:29:20 +00009829 if (PossibleZeroParamPrototype) {
Richard Smithef87be32013-06-25 20:34:17 +00009830 // We found a declaration that is not a prototype,
Anders Carlsson2a45e402012-12-18 01:29:20 +00009831 // but that could be a zero-parameter prototype
Richard Smithef87be32013-06-25 20:34:17 +00009832 if (TypeSourceInfo *TI =
9833 PossibleZeroParamPrototype->getTypeSourceInfo()) {
9834 TypeLoc TL = TI->getTypeLoc();
9835 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9836 Diag(PossibleZeroParamPrototype->getLocation(),
9837 diag::note_declaration_not_a_prototype)
9838 << PossibleZeroParamPrototype
9839 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9840 }
Anders Carlsson2a45e402012-12-18 01:29:20 +00009841 }
9842 }
Douglas Gregorf1b876d2009-03-31 16:35:03 +00009843
Douglas Gregor67da0d92009-05-15 17:59:04 +00009844 if (FnBodyScope)
9845 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009846
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009847 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00009848 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9849 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009850
9851 // Introduce our parameters into the function scope
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00009852 for (auto Param : FD->params()) {
Douglas Gregorc72e6452009-01-09 18:51:29 +00009853 Param->setOwningFunction(FD);
9854
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009855 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009856 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009857 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00009858
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00009859 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009860 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00009861 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00009862
James Molloy6f8780b2012-02-29 10:24:19 +00009863 // If we had any tags defined in the function prototype,
9864 // introduce them into the function scope.
9865 if (FnBodyScope) {
Robert Wilhelm16e94b92013-08-09 18:02:13 +00009866 for (ArrayRef<NamedDecl *>::iterator
9867 I = FD->getDeclsInPrototypeScope().begin(),
9868 E = FD->getDeclsInPrototypeScope().end();
9869 I != E; ++I) {
James Molloy6f8780b2012-02-29 10:24:19 +00009870 NamedDecl *D = *I;
9871
9872 // Some of these decls (like enums) may have been pinned to the translation unit
9873 // for lack of a real context earlier. If so, remove from the translation unit
9874 // and reattach to the current context.
9875 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9876 // Is the decl actually in the context?
Aaron Ballman629afae2014-03-07 19:56:05 +00009877 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9878 if (DI == D) {
James Molloy6f8780b2012-02-29 10:24:19 +00009879 Context.getTranslationUnitDecl()->removeDecl(D);
9880 break;
9881 }
9882 }
9883 // Either way, reassign the lexical decl context to our FunctionDecl.
9884 D->setLexicalDeclContext(CurContext);
9885 }
9886
9887 // If the decl has a non-null name, make accessible in the current scope.
9888 if (!D->getName().empty())
9889 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9890
9891 // Similarly, dive into enums and fish their constants out, making them
9892 // accessible in this scope.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00009893 if (auto *ED = dyn_cast<EnumDecl>(D)) {
9894 for (auto *EI : ED->enumerators())
9895 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
James Molloy6f8780b2012-02-29 10:24:19 +00009896 }
9897 }
9898 }
9899
Richard Smith79a52e52012-04-17 22:30:01 +00009900 // Ensure that the function's exception specification is instantiated.
9901 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9902 ResolveExceptionSpec(D->getLocation(), FPT);
9903
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009904 // dllimport cannot be applied to non-inline function definitions.
Hans Wennborg7f26fa62014-05-19 20:14:13 +00009905 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
9906 !FD->isTemplateInstantiation()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009907 assert(!FD->hasAttr<DLLExportAttr>());
9908 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
9909 FD->setInvalidDecl();
9910 return D;
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00009911 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +00009912 // We want to attach documentation to original Decl (which might be
9913 // a function template).
9914 ActOnDocumentableDecl(D);
Fariborz Jahanian3451df82014-05-28 17:02:35 +00009915 if (getCurLexicalContext()->isObjCContainer() &&
9916 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
9917 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
9918 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
9919
Argyrios Kyrtzidis26444c52012-12-14 06:54:03 +00009920 return D;
Chris Lattnere168f762006-11-10 05:29:30 +00009921}
9922
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009923/// \brief Given the set of return statements within a function body,
9924/// compute the variables that are subject to the named return value
9925/// optimization.
9926///
9927/// Each of the variables that is subject to the named return value
9928/// optimization will be marked as NRVO variables in the AST, and any
9929/// return statement that has a marked NRVO variable as its NRVO candidate can
9930/// use the named return value optimization.
9931///
9932/// This function applies a very simplistic algorithm for NRVO: if every return
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009933/// statement in the scope of a variable has the same NRVO candidate, that
9934/// candidate is an NRVO variable.
Douglas Gregor49695f02011-09-06 20:46:03 +00009935void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
John McCallaab3e412010-08-25 08:40:02 +00009936 ReturnStmt **Returns = Scope->Returns.data();
9937
John McCallaab3e412010-08-25 08:40:02 +00009938 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009939 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
9940 if (!NRVOCandidate->isNRVOVariable())
9941 Returns[I]->setNRVOCandidate(nullptr);
9942 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009943 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00009944}
9945
Richard Smith8e6002f2014-03-12 23:14:33 +00009946bool Sema::canDelayFunctionBody(const Declarator &D) {
9947 // We can't delay parsing the body of a constexpr function template (yet).
9948 if (D.getDeclSpec().isConstexprSpecified())
9949 return false;
9950
9951 // We can't delay parsing the body of a function template with a deduced
9952 // return type (yet).
9953 if (D.getDeclSpec().containsPlaceholderType()) {
9954 // If the placeholder introduces a non-deduced trailing return type,
9955 // we can still delay parsing it.
9956 if (D.getNumTypeObjects()) {
9957 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9958 if (Outer.Kind == DeclaratorChunk::Function &&
9959 Outer.Fun.hasTrailingReturnType()) {
9960 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9961 return Ty.isNull() || !Ty->isUndeducedType();
9962 }
9963 }
9964 return false;
9965 }
9966
9967 return true;
9968}
9969
Richard Smith1ab34b32012-11-19 21:13:18 +00009970bool Sema::canSkipFunctionBody(Decl *D) {
Richard Smith1ab34b32012-11-19 21:13:18 +00009971 // We cannot skip the body of a function (or function template) which is
9972 // constexpr, since we may need to evaluate its body in order to parse the
9973 // rest of the file.
Richard Smith7500ab22013-05-10 04:31:10 +00009974 // We cannot skip the body of a function with an undeduced return type,
9975 // because any callers of that function need to know the type.
Alp Tokera2794f92014-01-22 07:29:52 +00009976 if (const FunctionDecl *FD = D->getAsFunction())
Alp Toker314cc812014-01-25 16:55:45 +00009977 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
Alp Tokera2794f92014-01-22 07:29:52 +00009978 return false;
9979 return Consumer.shouldSkipFunctionBody(D);
Richard Smith1ab34b32012-11-19 21:13:18 +00009980}
9981
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009982Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009983 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009984 FD->setHasSkippedBody();
Argyrios Kyrtzidis44319182013-02-22 04:11:06 +00009985 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009986 MD->setHasSkippedBody();
Craig Topperc3ec1492014-05-26 06:22:03 +00009987 return ActOnFinishFunctionBody(Decl, nullptr);
Argyrios Kyrtzidis1eb71a12012-12-06 18:59:10 +00009988}
9989
John McCallfaf5fb42010-08-26 23:41:50 +00009990Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009991 return ActOnFinishFunctionBody(D, BodyArg, false);
Douglas Gregor67da0d92009-05-15 17:59:04 +00009992}
9993
John McCallb268a282010-08-23 23:25:46 +00009994Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9995 bool IsInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009996 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00009997
Ted Kremenek0b405322010-03-23 00:13:23 +00009998 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Craig Topperc3ec1492014-05-26 06:22:03 +00009999 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
Ted Kremenek918fe842010-03-20 21:06:02 +000010000
Douglas Gregorc45a40a2009-08-22 00:34:47 +000010001 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +000010002 FD->setBody(Body);
John McCall5ed3caf2012-02-14 19:50:52 +000010003
Richard Smith7500ab22013-05-10 04:31:10 +000010004 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
Alp Toker314cc812014-01-25 16:55:45 +000010005 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
Richard Smith7500ab22013-05-10 04:31:10 +000010006 // If the function has a deduced result type but contains no 'return'
10007 // statements, the result type as written must be exactly 'auto', and
10008 // the deduced result type is 'void'.
Alp Toker314cc812014-01-25 16:55:45 +000010009 if (!FD->getReturnType()->getAs<AutoType>()) {
Richard Smith7500ab22013-05-10 04:31:10 +000010010 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
Alp Toker314cc812014-01-25 16:55:45 +000010011 << FD->getReturnType();
Richard Smith7500ab22013-05-10 04:31:10 +000010012 FD->setInvalidDecl();
10013 } else {
10014 // Substitute 'void' for the 'auto' in the type.
10015 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
Alp Toker42a16a62014-01-25 23:51:36 +000010016 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
Richard Smith7500ab22013-05-10 04:31:10 +000010017 Context.adjustDeducedFunctionResultType(
10018 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
Richard Smith2a7d4812013-05-04 07:00:32 +000010019 }
10020 }
10021
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000010022 // The only way to be included in UndefinedButUsed is if there is an
10023 // ODR use before the definition. Avoid the expensive map lookup if this
Nick Lewyckyf0f56162013-01-31 03:23:57 +000010024 // is the first declaration.
Rafael Espindola3f9e4442013-10-19 02:13:21 +000010025 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +000010026 if (!FD->isExternallyVisible())
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +000010027 UndefinedButUsed.erase(FD);
10028 else if (FD->isInlined() &&
10029 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10030 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10031 UndefinedButUsed.erase(FD);
10032 }
Nick Lewyckyf0f56162013-01-31 03:23:57 +000010033
John McCall5ed3caf2012-02-14 19:50:52 +000010034 // If the function implicitly returns zero (like 'main') or is naked,
10035 // don't complain about missing return statements.
10036 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
Ted Kremenek0b405322010-03-23 00:13:23 +000010037 WP.disableCheckFallThrough();
Mike Stump11289f42009-09-09 15:08:12 +000010038
Francois Pichet3abc9b82011-05-11 02:14:46 +000010039 // MSVC permits the use of pure specifier (=0) on function definition,
Alp Tokerd4733632013-12-05 04:47:09 +000010040 // defined at class scope, warn about this non-standard construct.
Reid Klecknerbe7a4462013-10-08 22:45:29 +000010041 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
Francois Pichet3abc9b82011-05-11 02:14:46 +000010042 Diag(FD->getLocation(), diag::warn_pure_function_definition);
10043
Douglas Gregor88d292c2010-05-13 16:44:06 +000010044 if (!FD->isInvalidDecl()) {
Reid Kleckner121b1a12014-04-30 16:31:28 +000010045 // Don't diagnose unused parameters of defaulted or deleted functions.
10046 if (Body)
10047 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010048 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010049 FD->getReturnType(), FD);
10050
Douglas Gregor88d292c2010-05-13 16:44:06 +000010051 // If this is a constructor, we need a vtable.
10052 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10053 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +000010054
Jordan Rosed39e5f12012-07-02 21:19:23 +000010055 // Try to apply the named return value optimization. We have to check
10056 // if we can do this here because lambdas keep return statements around
10057 // to deduce an implicit return type.
Alp Toker314cc812014-01-25 16:55:45 +000010058 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
Jordan Rosed39e5f12012-07-02 21:19:23 +000010059 !FD->isDependentContext())
10060 computeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +000010061 }
10062
Douglas Gregor21f46922012-02-08 20:17:14 +000010063 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10064 "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +000010065 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +000010066 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +000010067 MD->setBody(Body);
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010068 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010069 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010070 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
Alp Toker314cc812014-01-25 16:55:45 +000010071 MD->getReturnType(), MD);
10072
Douglas Gregore3f3ea02011-09-06 20:33:37 +000010073 if (Body)
Douglas Gregor49695f02011-09-06 20:46:03 +000010074 computeNRVO(Body, getCurFunction());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000010075 }
Jordan Rose2afd6612012-10-19 16:05:26 +000010076 if (getCurFunction()->ObjCShouldCallSuper) {
Fariborz Jahanianb05417e2012-09-10 16:51:09 +000010077 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10078 << MD->getSelector().getAsString();
Jordan Rose2afd6612012-10-19 16:05:26 +000010079 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber1fb82662011-08-28 22:35:17 +000010080 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010081 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010082 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +000010083 bool isDesignated =
10084 MD->isDesignatedInitializerForTheInterface(&InitMethod);
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010085 assert(isDesignated && InitMethod);
10086 (void)isDesignated;
Argyrios Kyrtzidisde103662014-04-16 18:32:51 +000010087
10088 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10089 auto IFace = MD->getClassInterface();
10090 if (!IFace)
10091 return false;
10092 auto SuperD = IFace->getSuperClass();
10093 if (!SuperD)
10094 return false;
10095 return SuperD->getIdentifier() ==
10096 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10097 };
10098 // Don't issue this warning for unavailable inits or direct subclasses
10099 // of NSObject.
10100 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010101 Diag(MD->getLocation(),
10102 diag::warn_objc_designated_init_missing_super_call);
10103 Diag(InitMethod->getLocation(),
10104 diag::note_objc_designated_init_marked_here);
10105 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +000010106 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10107 }
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010108 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +000010109 // Don't issue this warning for unavaialable inits.
10110 if (!MD->isUnavailable())
10111 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +000010112 getCurFunction()->ObjCWarnForNoInitDelegation = false;
10113 }
Ted Kremenek5a201952009-02-07 01:47:29 +000010114 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +000010115 return nullptr;
Ted Kremenek5a201952009-02-07 01:47:29 +000010116 }
Douglas Gregor67da0d92009-05-15 17:59:04 +000010117
Jordan Rose2afd6612012-10-19 16:05:26 +000010118 assert(!getCurFunction()->ObjCShouldCallSuper &&
Eli Friedman22be06a2012-08-01 21:02:59 +000010119 "This should only be set for ObjC methods, which should have been "
10120 "handled in the block above.");
Nico Weber715abaf2011-08-22 17:25:57 +000010121
Chris Lattnere2473062007-05-28 06:28:18 +000010122 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +000010123 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +000010124 // C++ constructors that have function-try-blocks can't have return
10125 // statements in the handlers of that block. (C++ [except.handle]p14)
10126 // Verify this.
10127 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10128 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10129
Richard Smithdef8bdb2011-08-12 18:44:32 +000010130 // Verify that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +000010131 if (getCurFunction()->NeedsScopeChecking() &&
Douglas Gregor5d944db2012-08-17 05:12:08 +000010132 !PP.isCodeCompletionEnabled())
Douglas Gregor9a28e842010-03-01 23:15:13 +000010133 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +000010134
John McCalldeb646e2010-08-04 01:04:25 +000010135 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10136 if (!Destructor->getParent()->isDependentType())
10137 CheckDestructor(Destructor);
10138
John McCalla6309952010-03-16 21:39:52 +000010139 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10140 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +000010141 }
Douglas Gregor9a28e842010-03-01 23:15:13 +000010142
10143 // If any errors have occurred, clear out any temporaries that may have
10144 // been leftover. This ensures that these temporaries won't be picked up for
10145 // deletion in some later function.
Alp Tokerb6cc5922014-05-03 03:45:55 +000010146 if (getDiagnostics().hasErrorOccurred() ||
10147 getDiagnostics().getSuppressAllDiagnostics()) {
John McCall28fc7092011-11-10 05:35:25 +000010148 DiscardCleanupsInEvaluationContext();
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010149 }
Alp Tokerb6cc5922014-05-03 03:45:55 +000010150 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +000010151 !isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +000010152 // Since the body is valid, issue any analysis-based warnings that are
10153 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +000010154 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +000010155 }
10156
Richard Smith3607ffe2012-02-13 03:54:03 +000010157 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10158 (!CheckConstexprFunctionDecl(FD) ||
10159 !CheckConstexprFunctionBody(FD, Body)))
Richard Smitheb3c10c2011-10-01 02:31:28 +000010160 FD->setInvalidDecl();
10161
John McCall28fc7092011-11-10 05:35:25 +000010162 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +000010163 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Eli Friedman3bda6b12012-02-02 23:15:15 +000010164 assert(MaybeODRUseExprs.empty() &&
10165 "Leftover expressions for odr-use checking");
Douglas Gregor9a28e842010-03-01 23:15:13 +000010166 }
10167
John McCalle99d5f32010-03-25 22:08:03 +000010168 if (!IsInstantiation)
10169 PopDeclContext();
10170
Eli Friedman71c80552012-01-05 03:35:19 +000010171 PopFunctionScopeInfo(ActivePolicy, dcl);
Douglas Gregora7e3ea32009-11-15 07:07:58 +000010172 // If any errors have occurred, clear out any temporaries that may have
10173 // been leftover. This ensures that these temporaries won't be picked up for
10174 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +000010175 if (getDiagnostics().hasErrorOccurred()) {
John McCall28fc7092011-11-10 05:35:25 +000010176 DiscardCleanupsInEvaluationContext();
John McCall31168b02011-06-15 23:02:42 +000010177 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +000010178
John McCall48871652010-08-21 09:40:31 +000010179 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +000010180}
10181
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010182
10183/// When we finish delayed parsing of an attribute, we must attach it to the
10184/// relevant Decl.
10185void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10186 ParsedAttributes &Attrs) {
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000010187 // Always attach attributes to the underlying decl.
10188 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10189 D = TD->getTemplatedDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +000010190 ProcessDeclAttributeList(S, D, Attrs.getList());
10191
10192 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10193 if (Method->isStatic())
10194 checkThisInStaticMemberFunctionAttributes(Method);
Caitlin Sadowski9385dd72011-09-08 17:42:22 +000010195}
10196
10197
Chris Lattnerac18be92006-11-20 06:49:47 +000010198/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10199/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +000010200NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +000010201 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010202 // Before we produce a declaration for an implicitly defined
10203 // function, see whether there was a locally-scoped declaration of
10204 // this name as a function or variable. If so, use that
10205 // (non-visible) declaration, and complain about it.
Richard Smith39b79682013-06-18 20:15:12 +000010206 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10207 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10208 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10209 return ExternCPrev;
Douglas Gregor5a80bd12009-03-02 00:19:53 +000010210 }
10211
Chris Lattner00e26072008-05-05 21:18:06 +000010212 // Extension in C99. Legal in C90, but warn about it.
Hans Wennborg70a13242011-12-08 15:56:07 +000010213 unsigned diag_id;
Daniel Dunbar07d07852009-10-18 21:17:35 +000010214 if (II.getName().startswith("__builtin_"))
Abramo Bagnara3732fa52012-01-09 10:05:48 +000010215 diag_id = diag::warn_builtin_unknown;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010216 else if (getLangOpts().C99)
Hans Wennborg70a13242011-12-08 15:56:07 +000010217 diag_id = diag::ext_implicit_function_decl;
Chris Lattner00e26072008-05-05 21:18:06 +000010218 else
Hans Wennborg70a13242011-12-08 15:56:07 +000010219 diag_id = diag::warn_implicit_function_decl;
10220 Diag(Loc, diag_id) << &II;
Mike Stump11289f42009-09-09 15:08:12 +000010221
Hans Wennborg70a13242011-12-08 15:56:07 +000010222 // Because typo correction is expensive, only do it if the implicit
10223 // function declaration is going to be treated as an error.
10224 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10225 TypoCorrection Corrected;
Kaelyn Uhrainb1378402012-01-18 21:41:41 +000010226 DeclFilterCCC<FunctionDecl> Validator;
Hans Wennborg70a13242011-12-08 15:56:07 +000010227 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +000010228 LookupOrdinaryName, S, nullptr, Validator,
John Thompson2255f2c2014-04-23 12:57:01 +000010229 CTK_NonError)))
Richard Smithf9b15102013-08-17 00:46:16 +000010230 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10231 /*ErrorRecovery*/false);
Hans Wennborg2fb8b912011-12-06 09:46:12 +000010232 }
10233
Chris Lattnerac18be92006-11-20 06:49:47 +000010234 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +000010235 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +000010236 AttributeFactory attrFactory;
10237 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +000010238 unsigned DiagID;
Erik Verbruggen888d52a2014-01-15 09:15:43 +000010239 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10240 Context.getPrintingPolicy());
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010241 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +000010242 assert(!Error && "Error setting up implicit decl!");
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010243 SourceLocation NoLoc;
Chris Lattnerac18be92006-11-20 06:49:47 +000010244 Declarator D(DS, Declarator::BlockContext);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010245 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10246 /*IsAmbiguous=*/false,
Richard Smith151b8a32014-04-07 15:16:58 +000010247 /*LParenLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010248 /*Params=*/nullptr,
Richard Smith151b8a32014-04-07 15:16:58 +000010249 /*NumParams=*/0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010250 /*EllipsisLoc=*/NoLoc,
10251 /*RParenLoc=*/NoLoc,
10252 /*TypeQuals=*/0,
10253 /*RefQualifierIsLvalueRef=*/true,
10254 /*RefQualifierLoc=*/NoLoc,
10255 /*ConstQualifierLoc=*/NoLoc,
10256 /*VolatileQualifierLoc=*/NoLoc,
10257 /*MutableLoc=*/NoLoc,
10258 EST_None,
10259 /*ESpecLoc=*/NoLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010260 /*Exceptions=*/nullptr,
10261 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010262 /*NumExceptions=*/0,
Craig Topperc3ec1492014-05-26 06:22:03 +000010263 /*NoexceptExpr=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +000010264 Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +000010265 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010266 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +000010267 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +000010268
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010269 // Insert this function into translation-unit scope.
10270
10271 DeclContext *PrevDC = CurContext;
10272 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +000010273
Jordan Rosed03d99d2013-03-05 01:27:54 +000010274 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +000010275 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +000010276
10277 CurContext = PrevDC;
10278
Douglas Gregore711f702009-02-14 18:57:46 +000010279 AddKnownFunctionAttributes(FD);
10280
Steve Naroff3913ea42008-04-04 14:32:09 +000010281 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +000010282}
10283
Douglas Gregore711f702009-02-14 18:57:46 +000010284/// \brief Adds any function attributes that we know a priori based on
10285/// the declaration of this function.
10286///
10287/// These attributes can apply both to implicitly-declared builtins
10288/// (like __builtin___printf_chk) or to library-declared functions
10289/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +000010290///
10291/// We need to check for duplicate attributes both here and where user-written
10292/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +000010293void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10294 if (FD->isInvalidDecl())
10295 return;
10296
10297 // If this is a built-in function, map its builtin attributes to
10298 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +000010299 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +000010300 // Handle printf-formatting attributes.
10301 unsigned FormatIdx;
10302 bool HasVAListArg;
10303 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010304 if (!FD->hasAttr<FormatAttr>()) {
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010305 const char *fmt = "printf";
10306 unsigned int NumParams = FD->getNumParams();
10307 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10308 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10309 fmt = "NSString";
Aaron Ballman36a53502014-01-16 13:03:14 +000010310 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010311 &Context.Idents.get(fmt),
10312 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010313 HasVAListArg ? 0 : FormatIdx+2,
10314 FD->getLocation()));
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010315 }
Douglas Gregore711f702009-02-14 18:57:46 +000010316 }
Ted Kremenek5932c352010-07-16 02:11:15 +000010317 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10318 HasVAListArg)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010319 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010320 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010321 &Context.Idents.get("scanf"),
10322 FormatIdx+1,
Aaron Ballman36a53502014-01-16 13:03:14 +000010323 HasVAListArg ? 0 : FormatIdx+2,
10324 FD->getLocation()));
Ted Kremenek5932c352010-07-16 02:11:15 +000010325 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010326
10327 // Mark const if we don't care about errno and that is the only
10328 // thing preventing the function from being const. This allows
10329 // IRgen to use LLVM intrinsics for such functions.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010330 if (!getLangOpts().MathErrno &&
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010331 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +000010332 if (!FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010333 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +000010334 }
Mike Stumpca6c8752009-07-27 19:14:18 +000010335
Rafael Espindola2d21ab02011-10-12 19:51:18 +000010336 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
Aaron Ballman9ead1242013-12-19 02:39:40 +000010337 !FD->hasAttr<ReturnsTwiceAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010338 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10339 FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010340 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010341 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
Aaron Ballman9ead1242013-12-19 02:39:40 +000010342 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010343 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
Douglas Gregore711f702009-02-14 18:57:46 +000010344 }
10345
10346 IdentifierInfo *Name = FD->getIdentifier();
10347 if (!Name)
10348 return;
David Blaikiebbafb8a2012-03-11 07:00:24 +000010349 if ((!getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +000010350 FD->getDeclContext()->isTranslationUnit()) ||
10351 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +000010352 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +000010353 LinkageSpecDecl::lang_c)) {
10354 // Okay: this could be a libc/libm/Objective-C function we know
10355 // about.
10356 } else
10357 return;
10358
Jean-Daniel Dupas78536ae2012-01-24 22:32:46 +000010359 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +000010360 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +000010361 // target-specific builtins, perhaps?
Aaron Ballman9ead1242013-12-19 02:39:40 +000010362 if (!FD->hasAttr<FormatAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010363 FD->addAttr(FormatAttr::CreateImplicit(Context,
Aaron Ballmanf58070b2013-09-03 21:02:22 +000010364 &Context.Idents.get("printf"), 2,
Aaron Ballman36a53502014-01-16 13:03:14 +000010365 Name->isStr("vasprintf") ? 0 : 3,
10366 FD->getLocation()));
Mike Stumpa4de80b2009-07-28 02:25:19 +000010367 }
Jordan Rose742c6072012-08-08 21:17:31 +000010368
10369 if (Name->isStr("__CFStringMakeConstantString")) {
10370 // We already have a __builtin___CFStringMakeConstantString,
10371 // but builds that use -fno-constant-cfstrings don't go through that.
Aaron Ballman9ead1242013-12-19 02:39:40 +000010372 if (!FD->hasAttr<FormatArgAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000010373 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10374 FD->getLocation()));
Jordan Rose742c6072012-08-08 21:17:31 +000010375 }
Douglas Gregore711f702009-02-14 18:57:46 +000010376}
Chris Lattner302b4be2006-11-19 02:31:38 +000010377
John McCall703a3f82009-10-24 08:00:42 +000010378TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000010379 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +000010380 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +000010381 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +000010382
John McCallbcd03502009-12-07 02:54:59 +000010383 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +000010384 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +000010385 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +000010386 }
10387
Chris Lattner18b19622007-01-22 07:39:13 +000010388 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010389 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010390 D.getLocStart(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +000010391 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +000010392 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +000010393 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +000010394
John McCall04fcd0d2011-02-01 08:20:08 +000010395 // Bail out immediately if we have an invalid declaration.
10396 if (D.isInvalidType()) {
10397 NewTD->setInvalidDecl();
10398 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +000010399 }
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +000010400
Douglas Gregor41866812011-09-12 18:37:38 +000010401 if (D.getDeclSpec().isModulePrivateSpecified()) {
10402 if (CurContext->isFunctionOrMethod())
10403 Diag(NewTD->getLocation(), diag::err_module_private_local)
10404 << 2 << NewTD->getDeclName()
10405 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10406 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10407 else
10408 NewTD->setModulePrivate();
10409 }
Douglas Gregor26701a42011-09-09 02:06:17 +000010410
John McCall04fcd0d2011-02-01 08:20:08 +000010411 // C++ [dcl.typedef]p8:
10412 // If the typedef declaration defines an unnamed class (or
10413 // enum), the first typedef-name declared by the declaration
10414 // to be that class type (or enum type) is used to denote the
10415 // class type (or enum type) for linkage purposes only.
10416 // We need to check whether the type was declared in the declaration.
10417 switch (D.getDeclSpec().getTypeSpecType()) {
10418 case TST_enum:
10419 case TST_struct:
Joao Matosdc86f942012-08-31 18:45:21 +000010420 case TST_interface:
John McCall04fcd0d2011-02-01 08:20:08 +000010421 case TST_union:
10422 case TST_class: {
10423 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10424
10425 // Do nothing if the tag is not anonymous or already has an
10426 // associated typedef (from an earlier typedef in this decl group).
10427 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +000010428 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +000010429
10430 // A well-formed anonymous tag must always be a TUK_Definition.
10431 assert(tagFromDeclSpec->isThisDeclarationADefinition());
10432
10433 // The type must match the tag exactly; no qualifiers allowed.
10434 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10435 break;
10436
John McCall2575d882014-01-30 01:12:53 +000010437 // If we've already computed linkage for the anonymous tag, then
10438 // adding a typedef name for the anonymous decl can change that
10439 // linkage, which might be a serious problem. Diagnose this as
10440 // unsupported and ignore the typedef name. TODO: we should
10441 // pursue this as a language defect and establish a formal rule
10442 // for how to handle it.
10443 if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10444 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10445
10446 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
Alp Tokerb6cc5922014-05-03 03:45:55 +000010447 tagLoc = getLocForEndOfToken(tagLoc);
John McCall2575d882014-01-30 01:12:53 +000010448
10449 llvm::SmallString<40> textToInsert;
10450 textToInsert += ' ';
10451 textToInsert += D.getIdentifier()->getName();
10452 Diag(tagLoc, diag::note_typedef_changes_linkage)
10453 << FixItHint::CreateInsertion(tagLoc, textToInsert);
10454 break;
10455 }
10456
John McCall04fcd0d2011-02-01 08:20:08 +000010457 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +000010458 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +000010459 break;
10460 }
10461
10462 default:
10463 break;
10464 }
10465
Steve Narofff93b6722007-08-28 20:14:24 +000010466 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +000010467}
10468
Douglas Gregord9034f02009-05-14 16:41:31 +000010469
Richard Smith4b38ded2012-03-14 23:13:10 +000010470/// \brief Check that this is a valid underlying type for an enum declaration.
10471bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10472 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10473 QualType T = TI->getType();
10474
Eli Friedman52f32b92012-12-18 02:37:32 +000010475 if (T->isDependentType())
Richard Smith4b38ded2012-03-14 23:13:10 +000010476 return false;
10477
Eli Friedman52f32b92012-12-18 02:37:32 +000010478 if (const BuiltinType *BT = T->getAs<BuiltinType>())
10479 if (BT->isInteger())
10480 return false;
10481
Richard Smith4b38ded2012-03-14 23:13:10 +000010482 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10483 return true;
10484}
10485
10486/// Check whether this is a valid redeclaration of a previous enumeration.
10487/// \return true if the redeclaration was invalid.
10488bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10489 QualType EnumUnderlyingTy,
10490 const EnumDecl *Prev) {
10491 bool IsFixed = !EnumUnderlyingTy.isNull();
10492
10493 if (IsScoped != Prev->isScoped()) {
10494 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10495 << Prev->isScoped();
Alp Toker8c44db52014-01-06 11:31:06 +000010496 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010497 return true;
10498 }
10499
10500 if (IsFixed && Prev->isFixed()) {
Richard Smith258a7442012-03-26 04:08:46 +000010501 if (!EnumUnderlyingTy->isDependentType() &&
10502 !Prev->getIntegerType()->isDependentType() &&
10503 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Richard Smith4b38ded2012-03-14 23:13:10 +000010504 Prev->getIntegerType())) {
Alp Tokerb9fa5122014-01-06 11:31:18 +000010505 // TODO: Highlight the underlying type of the redeclaration.
Richard Smith4b38ded2012-03-14 23:13:10 +000010506 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10507 << EnumUnderlyingTy << Prev->getIntegerType();
Alp Tokerb9fa5122014-01-06 11:31:18 +000010508 Diag(Prev->getLocation(), diag::note_previous_declaration)
10509 << Prev->getIntegerTypeRange();
Richard Smith4b38ded2012-03-14 23:13:10 +000010510 return true;
10511 }
10512 } else if (IsFixed != Prev->isFixed()) {
10513 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10514 << Prev->isFixed();
Alp Toker8c44db52014-01-06 11:31:06 +000010515 Diag(Prev->getLocation(), diag::note_previous_declaration);
Richard Smith4b38ded2012-03-14 23:13:10 +000010516 return true;
10517 }
10518
10519 return false;
10520}
10521
Joao Matosdc86f942012-08-31 18:45:21 +000010522/// \brief Get diagnostic %select index for tag kind for
10523/// redeclaration diagnostic message.
10524/// WARNING: Indexes apply to particular diagnostics only!
10525///
10526/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +000010527static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
Joao Matosdc86f942012-08-31 18:45:21 +000010528 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +000010529 case TTK_Struct: return 0;
10530 case TTK_Interface: return 1;
10531 case TTK_Class: return 2;
10532 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
Joao Matosdc86f942012-08-31 18:45:21 +000010533 }
Joao Matosdc86f942012-08-31 18:45:21 +000010534}
10535
10536/// \brief Determine if tag kind is a class-key compatible with
10537/// class for redeclaration (class, struct, or __interface).
10538///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010539/// \returns true iff the tag kind is compatible.
Joao Matosdc86f942012-08-31 18:45:21 +000010540static bool isClassCompatTagKind(TagTypeKind Tag)
10541{
10542 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10543}
10544
Douglas Gregord9034f02009-05-14 16:41:31 +000010545/// \brief Determine whether a tag with a given kind is acceptable
10546/// as a redeclaration of the given tag declaration.
10547///
10548/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +000010549bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +000010550 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +000010551 SourceLocation NewTagLoc,
10552 const IdentifierInfo &Name) {
10553 // C++ [dcl.type.elab]p3:
10554 // The class-key or enum keyword present in the
10555 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +000010556 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +000010557 // refers. This rule also applies to the form of
10558 // elaborated-type-specifier that declares a class-name or
10559 // friend class since it can be construed as referring to the
10560 // definition of the class. Thus, in any
10561 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +000010562 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +000010563 // used to refer to a union (clause 9), and either the class or
10564 // struct class-key shall be used to refer to a class (clause 9)
10565 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +000010566 TagTypeKind OldTag = Previous->getTagKind();
Joao Matosdc86f942012-08-31 18:45:21 +000010567 if (!isDefinition || !isClassCompatTagKind(NewTag))
Richard Trieucaa33d32011-06-10 03:11:26 +000010568 if (OldTag == NewTag)
10569 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010570
Joao Matosdc86f942012-08-31 18:45:21 +000010571 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
Douglas Gregord9034f02009-05-14 16:41:31 +000010572 // Warn about the struct/class tag mismatch.
10573 bool isTemplate = false;
10574 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10575 isTemplate = Record->getDescribedClassTemplate();
10576
Richard Trieucaa33d32011-06-10 03:11:26 +000010577 if (!ActiveTemplateInstantiations.empty()) {
10578 // In a template instantiation, do not offer fix-its for tag mismatches
10579 // since they usually mess up the template instead of fixing the problem.
10580 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010581 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10582 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010583 return true;
10584 }
10585
10586 if (isDefinition) {
10587 // On definitions, check previous tags and issue a fix-it for each
10588 // one that doesn't match the current tag.
10589 if (Previous->getDefinition()) {
10590 // Don't suggest fix-its for redefinitions.
10591 return true;
10592 }
10593
10594 bool previousMismatch = false;
Aaron Ballman86c93902014-03-06 23:45:36 +000010595 for (auto I : Previous->redecls()) {
Richard Trieucaa33d32011-06-10 03:11:26 +000010596 if (I->getTagKind() != NewTag) {
10597 if (!previousMismatch) {
10598 previousMismatch = true;
10599 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010600 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10601 << getRedeclDiagFromTagKind(I->getTagKind());
Richard Trieucaa33d32011-06-10 03:11:26 +000010602 }
10603 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010604 << getRedeclDiagFromTagKind(NewTag)
Richard Trieucaa33d32011-06-10 03:11:26 +000010605 << FixItHint::CreateReplacement(I->getInnerLocStart(),
Joao Matosdc86f942012-08-31 18:45:21 +000010606 TypeWithKeyword::getTagTypeKindName(NewTag));
Richard Trieucaa33d32011-06-10 03:11:26 +000010607 }
10608 }
10609 return true;
10610 }
10611
10612 // Check for a previous definition. If current tag and definition
10613 // are same type, do nothing. If no definition, but disagree with
10614 // with previous tag type, give a warning, but no fix-it.
10615 const TagDecl *Redecl = Previous->getDefinition() ?
10616 Previous->getDefinition() : Previous;
10617 if (Redecl->getTagKind() == NewTag) {
10618 return true;
10619 }
10620
Douglas Gregord9034f02009-05-14 16:41:31 +000010621 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Joao Matosdc86f942012-08-31 18:45:21 +000010622 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10623 << getRedeclDiagFromTagKind(OldTag);
Richard Trieucaa33d32011-06-10 03:11:26 +000010624 Diag(Redecl->getLocation(), diag::note_previous_use);
10625
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010626 // If there is a previous definition, suggest a fix-it.
Richard Trieucaa33d32011-06-10 03:11:26 +000010627 if (Previous->getDefinition()) {
10628 Diag(NewTagLoc, diag::note_struct_class_suggestion)
Joao Matosdc86f942012-08-31 18:45:21 +000010629 << getRedeclDiagFromTagKind(Redecl->getTagKind())
Richard Trieucaa33d32011-06-10 03:11:26 +000010630 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Joao Matosdc86f942012-08-31 18:45:21 +000010631 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
Richard Trieucaa33d32011-06-10 03:11:26 +000010632 }
10633
Douglas Gregord9034f02009-05-14 16:41:31 +000010634 return true;
10635 }
10636 return false;
10637}
10638
Steve Naroff30d242c2007-09-15 18:49:24 +000010639/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +000010640/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +000010641/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +000010642/// reference/declaration/definition of a tag.
Richard Smith649c7b062014-01-08 00:56:48 +000010643///
10644/// IsTypeSpecifier is true if this is a type-specifier (or
10645/// trailing-type-specifier) other than one in an alias-declaration.
John McCall48871652010-08-21 09:40:31 +000010646Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +000010647 SourceLocation KWLoc, CXXScopeSpec &SS,
10648 IdentifierInfo *Name, SourceLocation NameLoc,
10649 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010650 SourceLocation ModulePrivateLoc,
Douglas Gregor009f6992010-09-16 23:58:57 +000010651 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000010652 bool &OwnedDecl, bool &IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010653 SourceLocation ScopedEnumKWLoc,
10654 bool ScopedEnumUsesClassTag,
Richard Smith649c7b062014-01-08 00:56:48 +000010655 TypeResult UnderlyingType,
10656 bool IsTypeSpecifier) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +000010657 // If this is not a definition, it must have a name.
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000010658 IdentifierInfo *OrigName = Name;
Craig Topperc3ec1492014-05-26 06:22:03 +000010659 assert((Name != nullptr || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +000010660 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +000010661 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +000010662
Douglas Gregord6ab8742009-05-28 23:31:59 +000010663 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000010664 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Richard Smith0f8ee222012-01-10 01:33:14 +000010665 bool ScopedEnum = ScopedEnumKWLoc.isValid();
Mike Stump11289f42009-09-09 15:08:12 +000010666
Douglas Gregor5c0405d2009-10-07 22:35:40 +000010667 // FIXME: Check explicit specializations more carefully.
10668 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010669 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +000010670
10671 // We only need to do this matching if we have template parameters
10672 // or a scope specifier, which also conveniently avoids this work
10673 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +000010674 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +000010675 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000010676 if (TemplateParameterList *TemplateParams =
10677 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000010678 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
Richard Smith4b55a9c2014-04-17 03:29:33 +000010679 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
Richard Smith1d4b2e12013-04-01 21:43:41 +000010680 if (Kind == TTK_Enum) {
10681 Diag(KWLoc, diag::err_enum_template);
Craig Topperc3ec1492014-05-26 06:22:03 +000010682 return nullptr;
Richard Smith1d4b2e12013-04-01 21:43:41 +000010683 }
10684
Douglas Gregor3dad8422009-09-26 06:47:28 +000010685 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +000010686 // This is a declaration or definition of a class template (which may
10687 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +000010688
Douglas Gregor5f0e2522010-07-14 23:14:12 +000010689 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000010690 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010691
Douglas Gregore93e46c2009-07-22 23:48:44 +000010692 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +000010693 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +000010694 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010695 TemplateParams, AS,
Douglas Gregor2820e692011-09-09 19:05:14 +000010696 ModulePrivateLoc,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010697 TemplateParameterLists.size()-1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010698 TemplateParameterLists.data());
Douglas Gregore93e46c2009-07-22 23:48:44 +000010699 return Result.get();
10700 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010701 // The "template<>" header is extraneous.
10702 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +000010703 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +000010704 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +000010705 }
Mike Stump11289f42009-09-09 15:08:12 +000010706 }
10707 }
10708
Douglas Gregor0bf31402010-10-08 23:50:27 +000010709 // Figure out the underlying type if this a enum declaration. We need to do
10710 // this early, because it's needed to detect if this is an incompatible
10711 // redeclaration.
10712 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10713
10714 if (Kind == TTK_Enum) {
10715 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10716 // No underlying type explicitly specified, or we failed to parse the
10717 // type, default to int.
10718 EnumUnderlying = Context.IntTy.getTypePtr();
10719 else if (UnderlyingType.get()) {
10720 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10721 // integral type; any cv-qualification is ignored.
Craig Topperc3ec1492014-05-26 06:22:03 +000010722 TypeSourceInfo *TI = nullptr;
Richard Smitheece8c32012-03-15 00:22:18 +000010723 GetTypeFromParser(UnderlyingType.get(), &TI);
Douglas Gregor0bf31402010-10-08 23:50:27 +000010724 EnumUnderlying = TI;
10725
Richard Smith4b38ded2012-03-14 23:13:10 +000010726 if (CheckEnumUnderlyingType(TI))
Douglas Gregor0bf31402010-10-08 23:50:27 +000010727 // Recover by falling back to int.
10728 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010729
Richard Smith4b38ded2012-03-14 23:13:10 +000010730 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
Douglas Gregor2b988fd2010-12-16 00:24:44 +000010731 UPPC_FixedUnderlyingType))
10732 EnumUnderlying = Context.IntTy.getTypePtr();
10733
Alp Tokerbfa39342014-01-14 12:51:41 +000010734 } else if (getLangOpts().MSVCCompat)
Francois Picheta3108062010-10-18 15:01:13 +000010735 // Microsoft enums are always of int type.
10736 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +000010737 }
10738
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010739 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010740 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +000010741 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +000010742
Chandler Carrutha419dbb2010-03-01 21:17:36 +000010743 RedeclarationKind Redecl = ForRedeclaration;
10744 if (TUK == TUK_Friend || TUK == TUK_Reference)
10745 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +000010746
10747 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010748 bool FriendSawTagOutsideEnclosingNamespace = false;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010749 if (Name && SS.isNotEmpty()) {
10750 // We have a nested-name tag ('struct foo::bar').
10751
10752 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010753 if (SS.isInvalid()) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010754 Name = nullptr;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010755 goto CreateNewDecl;
10756 }
10757
John McCall7f41d982009-09-11 04:59:25 +000010758 // If this is a friend or a reference to a class in a dependent
10759 // context, don't try to make a decl for it.
10760 if (TUK == TUK_Friend || TUK == TUK_Reference) {
10761 DC = computeDeclContext(SS, false);
10762 if (!DC) {
10763 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000010764 return nullptr;
John McCall7f41d982009-09-11 04:59:25 +000010765 }
John McCall0b66eb32010-05-01 00:40:08 +000010766 } else {
10767 DC = computeDeclContext(SS, true);
10768 if (!DC) {
10769 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10770 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010771 return nullptr;
John McCall0b66eb32010-05-01 00:40:08 +000010772 }
John McCall7f41d982009-09-11 04:59:25 +000010773 }
10774
John McCall0b66eb32010-05-01 00:40:08 +000010775 if (RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +000010776 return nullptr;
Douglas Gregor2ec748c2009-05-14 00:28:11 +000010777
Douglas Gregor8761da52009-02-03 00:34:39 +000010778 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +000010779 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +000010780 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +000010781
John McCall1f82f242009-11-18 22:49:29 +000010782 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010783 return nullptr;
John McCall6538c932009-10-10 05:48:19 +000010784
John McCall1f82f242009-11-18 22:49:29 +000010785 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010786 // Name lookup did not find anything. However, if the
10787 // nested-name-specifier refers to the current instantiation,
10788 // and that current instantiation has any dependent base
10789 // classes, we might find something at instantiation time: treat
10790 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +000010791 // But this only makes any sense for reference-like lookups.
10792 if (Previous.wasNotFoundInCurrentInstantiation() &&
10793 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +000010794 IsDependent = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000010795 return nullptr;
Douglas Gregord2e6a452010-01-14 17:47:39 +000010796 }
10797
10798 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +000010799 Diag(NameLoc, diag::err_not_tag_in_scope)
10800 << Kind << Name << DC << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010801 Name = nullptr;
Douglas Gregorb8006faf2009-05-27 17:30:49 +000010802 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010803 goto CreateNewDecl;
10804 }
Chris Lattnerd9773512009-01-21 02:38:50 +000010805 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010806 // If this is a named struct, check to see if there was a previous forward
10807 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +000010808 // FIXME: We're looking into outer scopes here, even when we
10809 // shouldn't be. Doing so can result in ambiguities that we
10810 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +000010811 LookupName(Previous, S);
10812
John McCall3c581bf2013-03-20 01:53:00 +000010813 // When declaring or defining a tag, ignore ambiguities introduced
10814 // by types using'ed into this scope.
Douglas Gregor5d1d9e32011-05-09 21:46:33 +000010815 if (Previous.isAmbiguous() &&
10816 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +000010817 LookupResult::Filter F = Previous.makeFilter();
10818 while (F.hasNext()) {
10819 NamedDecl *ND = F.next();
10820 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10821 F.erase();
10822 }
10823 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +000010824 }
John McCall3c581bf2013-03-20 01:53:00 +000010825
10826 // C++11 [namespace.memdef]p3:
10827 // If the name in a friend declaration is neither qualified nor
10828 // a template-id and the declaration is a function or an
10829 // elaborated-type-specifier, the lookup to determine whether
10830 // the entity has been previously declared shall not consider
10831 // any scopes outside the innermost enclosing namespace.
10832 //
10833 // Does it matter that this should be by scope instead of by
10834 // semantic context?
10835 if (!Previous.empty() && TUK == TUK_Friend) {
10836 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10837 LookupResult::Filter F = Previous.makeFilter();
10838 while (F.hasNext()) {
10839 NamedDecl *ND = F.next();
10840 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010841 if (DC->isFileContext() &&
10842 !EnclosingNS->Encloses(ND->getDeclContext())) {
John McCall3c581bf2013-03-20 01:53:00 +000010843 F.erase();
Douglas Gregorf83b4ea2013-06-27 20:42:30 +000010844 FriendSawTagOutsideEnclosingNamespace = true;
10845 }
John McCall3c581bf2013-03-20 01:53:00 +000010846 }
10847 F.done();
10848 }
Douglas Gregored8a29b2011-05-04 00:25:33 +000010849
John McCall1f82f242009-11-18 22:49:29 +000010850 // Note: there used to be some attempt at recovery here.
10851 if (Previous.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010852 return nullptr;
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010853
David Blaikiebbafb8a2012-03-11 07:00:24 +000010854 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010855 // FIXME: This makes sure that we ignore the contexts associated
10856 // with C structs, unions, and enums when looking for a matching
10857 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +000010858 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000010859 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10860 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000010861 }
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +000010862 }
10863
John McCall1f82f242009-11-18 22:49:29 +000010864 if (Previous.isSingleResult() &&
10865 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000010866 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +000010867 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +000010868 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +000010869 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +000010870 }
10871
David Blaikiebbafb8a2012-03-11 07:00:24 +000010872 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010873 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010874 // This is a declaration of or a reference to "std::bad_alloc".
10875 isStdBadAlloc = true;
10876
John McCall1f82f242009-11-18 22:49:29 +000010877 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000010878 // std::bad_alloc has been implicitly declared (but made invisible to
10879 // name lookup). Fill in this implicit declaration as the previous
10880 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000010881 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +000010882 }
10883 }
John McCall1f82f242009-11-18 22:49:29 +000010884
John McCalle9eaf8e2010-03-25 21:28:06 +000010885 // If we didn't find a previous declaration, and this is a reference
10886 // (or friend reference), move to the correct scope. In C++, we
10887 // also need to do a redeclaration lookup there, just in case
10888 // there's a shadow friend decl.
10889 if (Name && Previous.empty() &&
10890 (TUK == TUK_Reference || TUK == TUK_Friend)) {
10891 if (Invalid) goto CreateNewDecl;
10892 assert(SS.isEmpty());
10893
10894 if (TUK == TUK_Reference) {
10895 // C++ [basic.scope.pdecl]p5:
10896 // -- for an elaborated-type-specifier of the form
10897 //
10898 // class-key identifier
10899 //
10900 // if the elaborated-type-specifier is used in the
10901 // decl-specifier-seq or parameter-declaration-clause of a
10902 // function defined in namespace scope, the identifier is
10903 // declared as a class-name in the namespace that contains
10904 // the declaration; otherwise, except as a friend
10905 // declaration, the identifier is declared in the smallest
10906 // non-class, non-function-prototype scope that contains the
10907 // declaration.
10908 //
10909 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10910 // C structs and unions.
10911 //
10912 // It is an error in C++ to declare (rather than define) an enum
10913 // type, including via an elaborated type specifier. We'll
10914 // diagnose that later; for now, declare the enum in the same
10915 // scope as we would have picked for any other tag type.
10916 //
10917 // GNU C also supports this behavior as part of its incomplete
10918 // enum types extension, while GNU C++ does not.
10919 //
10920 // Find the context where we'll be declaring the tag.
10921 // FIXME: We would like to maintain the current DeclContext as the
10922 // lexical context,
Nick Lewyckyf6042122012-03-10 07:47:07 +000010923 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
John McCalle9eaf8e2010-03-25 21:28:06 +000010924 SearchDC = SearchDC->getParent();
10925
10926 // Find the scope where we'll be declaring the tag.
10927 while (S->isClassScope() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000010928 (getLangOpts().CPlusPlus &&
John McCalle9eaf8e2010-03-25 21:28:06 +000010929 S->isFunctionPrototypeScope()) ||
10930 ((S->getFlags() & Scope::DeclScope) == 0) ||
Ted Kremenekc37877d2013-10-08 17:08:03 +000010931 (S->getEntity() && S->getEntity()->isTransparentContext()))
John McCalle9eaf8e2010-03-25 21:28:06 +000010932 S = S->getParent();
10933 } else {
10934 assert(TUK == TUK_Friend);
10935 // C++ [namespace.memdef]p3:
10936 // If a friend declaration in a non-local class first declares a
10937 // class or function, the friend class or function is a member of
10938 // the innermost enclosing namespace.
10939 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +000010940 }
10941
John McCalle87beb22010-04-23 18:46:30 +000010942 // In C++, we need to do a redeclaration lookup to properly
10943 // diagnose some problems.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010944 if (getLangOpts().CPlusPlus) {
John McCalle9eaf8e2010-03-25 21:28:06 +000010945 Previous.setRedeclarationKind(ForRedeclaration);
10946 LookupQualifiedName(Previous, SearchDC);
10947 }
10948 }
10949
John McCall1f82f242009-11-18 22:49:29 +000010950 if (!Previous.empty()) {
Alp Toker0abb0572014-01-18 00:59:32 +000010951 NamedDecl *PrevDecl = Previous.getFoundDecl();
10952 NamedDecl *DirectPrevDecl =
10953 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
John McCalle87beb22010-04-23 18:46:30 +000010954
10955 // It's okay to have a tag decl in the same scope as a typedef
10956 // which hides a tag decl in the same scope. Finding this
10957 // insanity with a redeclaration lookup can only actually happen
10958 // in C++.
10959 //
10960 // This is also okay for elaborated-type-specifiers, which is
10961 // technically forbidden by the current standard but which is
10962 // okay according to the likely resolution of an open issue;
10963 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
David Blaikiebbafb8a2012-03-11 07:00:24 +000010964 if (getLangOpts().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +000010965 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +000010966 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10967 TagDecl *Tag = TT->getDecl();
10968 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +000010969 Tag->getDeclContext()->getRedeclContext()
10970 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +000010971 PrevDecl = Tag;
10972 Previous.clear();
10973 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +000010974 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +000010975 }
10976 }
10977 }
10978 }
10979
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010980 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010981 // If this is a use of a previous tag, or if the tag is already declared
10982 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000010983 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +000010984 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Alp Toker320374c2014-01-17 12:57:21 +000010985 isDeclInScope(DirectPrevDecl, SearchDC, S,
Richard Smith72bcaec2013-12-05 04:30:04 +000010986 SS.isNotEmpty() || isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +000010987 // Make sure that this wasn't declared as an enum and now used as a
10988 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +000010989 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10990 TUK == TUK_Definition, KWLoc,
10991 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +000010992 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +000010993 = (PrevTagDecl->getTagKind() != TTK_Enum &&
10994 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +000010995 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +000010996 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +000010997 << Name
Douglas Gregora771f462010-03-31 17:46:05 +000010998 << FixItHint::CreateReplacement(SourceRange(KWLoc),
10999 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +000011000 else
11001 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +000011002 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +000011003
Mike Stump11289f42009-09-09 15:08:12 +000011004 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +000011005 Kind = PrevTagDecl->getTagKind();
11006 else {
11007 // Recover by making this an anonymous redefinition.
Craig Topperc3ec1492014-05-26 06:22:03 +000011008 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011009 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +000011010 Invalid = true;
11011 }
11012 }
11013
Douglas Gregor0bf31402010-10-08 23:50:27 +000011014 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11015 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11016
Richard Smith0f8ee222012-01-10 01:33:14 +000011017 // If this is an elaborated-type-specifier for a scoped enumeration,
11018 // the 'class' keyword is not necessary and not permitted.
11019 if (TUK == TUK_Reference || TUK == TUK_Friend) {
11020 if (ScopedEnum)
11021 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11022 << PrevEnum->isScoped()
11023 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11024 return PrevTagDecl;
11025 }
11026
Richard Smith4b38ded2012-03-14 23:13:10 +000011027 QualType EnumUnderlyingTy;
11028 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
Richard Smith8bcc0862014-01-08 01:16:19 +000011029 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
Richard Smith4b38ded2012-03-14 23:13:10 +000011030 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11031 EnumUnderlyingTy = QualType(T, 0);
11032
Douglas Gregor0bf31402010-10-08 23:50:27 +000011033 // All conflicts with previous declarations are recovered by
Richard Smithb66d7772012-03-23 23:09:08 +000011034 // returning the previous declaration, unless this is a definition,
11035 // in which case we want the caller to bail out.
Richard Smith4b38ded2012-03-14 23:13:10 +000011036 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11037 ScopedEnum, EnumUnderlyingTy, PrevEnum))
Craig Topperc3ec1492014-05-26 06:22:03 +000011038 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
Douglas Gregor0bf31402010-10-08 23:50:27 +000011039 }
11040
David Majnemer55890bf2013-06-11 03:51:23 +000011041 // C++11 [class.mem]p1:
David Majnemerbfce6642013-06-11 06:19:45 +000011042 // A member shall not be declared twice in the member-specification,
David Majnemer55890bf2013-06-11 03:51:23 +000011043 // except that a nested class or member class template can be declared
11044 // and then later defined.
11045 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11046 S->isDeclScope(PrevDecl)) {
11047 Diag(NameLoc, diag::ext_member_redeclared);
11048 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11049 }
11050
Douglas Gregor170512f2009-04-01 23:51:29 +000011051 if (!Invalid) {
John McCall2976f8b2014-05-14 07:54:17 +000011052 // If this is a use, just return the declaration we found, unless
11053 // we have attributes.
Chris Lattner9ff58d72008-07-03 03:30:58 +000011054
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011055 // FIXME: In the future, return a variant or some other clue
11056 // for the consumer of this Decl to know it doesn't own it.
11057 // For our current ASTs this shouldn't be a problem, but will
11058 // need to be changed with DeclGroups.
John McCall2976f8b2014-05-14 07:54:17 +000011059 if (!Attr &&
11060 ((TUK == TUK_Reference &&
11061 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11062 || TUK == TUK_Friend))
John McCall48871652010-08-21 09:40:31 +000011063 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011064
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011065 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +000011066 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +000011067 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000011068 // If we're defining a specialization and the previous definition
11069 // is from an implicit instantiation, don't emit an error
11070 // here; we'll catch this in the general case below.
Richard Smith7d137e32012-03-23 03:33:32 +000011071 bool IsExplicitSpecializationAfterInstantiation = false;
11072 if (isExplicitSpecialization) {
11073 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11074 IsExplicitSpecializationAfterInstantiation =
11075 RD->getTemplateSpecializationKind() !=
11076 TSK_ExplicitSpecialization;
11077 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11078 IsExplicitSpecializationAfterInstantiation =
11079 ED->getTemplateSpecializationKind() !=
11080 TSK_ExplicitSpecialization;
11081 }
11082
11083 if (!IsExplicitSpecializationAfterInstantiation) {
James Molloy6f8780b2012-02-29 10:24:19 +000011084 // A redeclaration in function prototype scope in C isn't
11085 // visible elsewhere, so merely issue a warning.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011086 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
James Molloy6f8780b2012-02-29 10:24:19 +000011087 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11088 else
11089 Diag(NameLoc, diag::err_redefinition) << Name;
Douglas Gregor06db9f52009-10-12 20:18:28 +000011090 Diag(Def->getLocation(), diag::note_previous_definition);
11091 // If this is a redefinition, recover by making this
11092 // struct be anonymous, which will make any later
11093 // references get the previous definition.
Craig Topperc3ec1492014-05-26 06:22:03 +000011094 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011095 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +000011096 Invalid = true;
11097 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011098 } else {
11099 // If the type is currently being defined, complain
11100 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +000011101 const TagType *Tag
11102 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +000011103 if (Tag->isBeingDefined()) {
11104 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +000011105 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +000011106 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011107 Name = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011108 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +000011109 Invalid = true;
11110 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011111 }
Douglas Gregordee1be82009-01-17 00:42:38 +000011112
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011113 // Okay, this is definition of a previously declared or referenced
John McCalla16fc892014-05-14 18:31:48 +000011114 // tag. We're going to create a new Decl for it.
11115 }
11116
11117 // Okay, we're going to make a redeclaration. If this is some kind
11118 // of reference, make sure we build the redeclaration in the same DC
11119 // as the original, and ignore the current access specifier.
11120 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11121 SearchDC = PrevTagDecl->getDeclContext();
11122 AS = AS_none;
Douglas Gregordee1be82009-01-17 00:42:38 +000011123 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011124 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011125 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +000011126 // have a definition. Just create a new decl.
11127
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011128 } else {
11129 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +000011130 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011131 // new decl/type. We set PrevDecl to NULL so that the entities
11132 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +000011133 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +000011134 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011135 // If we get here, we're going to create a new Decl. If PrevDecl
11136 // is non-NULL, it's a definition of the tag declared by
11137 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +000011138
11139
11140 // Otherwise, PrevDecl is not a tag, but was found with tag
11141 // lookup. This is only actually possible in C++, where a few
11142 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +000011143 } else {
John McCalle87beb22010-04-23 18:46:30 +000011144 // Use a better diagnostic if an elaborated-type-specifier
11145 // found the wrong kind of type on the first
11146 // (non-redeclaration) lookup.
11147 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11148 !Previous.isForRedeclaration()) {
11149 unsigned Kind = 0;
11150 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011151 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11152 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011153 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11154 Diag(PrevDecl->getLocation(), diag::note_declared_at);
11155 Invalid = true;
11156
11157 // Otherwise, only diagnose if the declaration is in scope.
Richard Smith72bcaec2013-12-05 04:30:04 +000011158 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11159 SS.isNotEmpty() || isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +000011160 // do nothing
11161
11162 // Diagnose implicit declarations introduced by elaborated types.
11163 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11164 unsigned Kind = 0;
11165 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +000011166 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11167 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +000011168 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11169 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11170 Invalid = true;
11171
11172 // Otherwise it's a declaration. Call out a particularly common
11173 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +000011174 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11175 unsigned Kind = 0;
11176 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +000011177 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +000011178 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +000011179 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11180 Invalid = true;
11181
11182 // Otherwise, diagnose.
11183 } else {
11184 // The tag name clashes with something else in the target scope,
11185 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +000011186 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +000011187 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000011188 Name = nullptr;
Douglas Gregordee1be82009-01-17 00:42:38 +000011189 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +000011190 }
John McCalle87beb22010-04-23 18:46:30 +000011191
11192 // The existing declaration isn't relevant to us; we're in a
11193 // new scope, so clear out the previous declaration.
11194 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +000011195 }
Chris Lattner18b19622007-01-22 07:39:13 +000011196 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000011197
Chris Lattner438e5012008-12-17 07:13:27 +000011198CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +000011199
Craig Topperc3ec1492014-05-26 06:22:03 +000011200 TagDecl *PrevDecl = nullptr;
John McCall1f82f242009-11-18 22:49:29 +000011201 if (Previous.isSingleResult())
11202 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11203
Chris Lattnerbf0b7982007-01-23 04:27:41 +000011204 // If there is an identifier, use the location of the identifier as the
11205 // location of the decl, otherwise use the location of the struct/union
11206 // keyword.
11207 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +000011208
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011209 // Otherwise, create a new declaration. If there is a previous
11210 // declaration of the same entity, the two will be linked via
11211 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +000011212 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +000011213
Douglas Gregor0bf31402010-10-08 23:50:27 +000011214 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +000011215 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +000011216 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11217 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011218 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +000011219 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +000011220 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +000011221 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011222 if (TUK != TUK_Definition && !Invalid) {
11223 TagDecl *Def;
Douglas Gregor780420e2013-03-25 22:22:35 +000011224 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11225 cast<EnumDecl>(New)->isFixed()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +000011226 // C++0x: 7.2p2: opaque-enum-declaration.
11227 // Conflicts are diagnosed above. Do nothing.
11228 }
11229 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011230 Diag(Loc, diag::ext_forward_ref_enum_def)
11231 << New;
11232 Diag(Def->getLocation(), diag::note_previous_definition);
11233 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +000011234 unsigned DiagID = diag::ext_forward_ref_enum;
Alp Tokerbfa39342014-01-14 12:51:41 +000011235 if (getLangOpts().MSVCCompat)
Francois Pichet488b4a72010-09-12 05:06:55 +000011236 DiagID = diag::ext_ms_forward_ref_enum;
David Blaikiebbafb8a2012-03-11 07:00:24 +000011237 else if (getLangOpts().CPlusPlus)
Francois Pichet488b4a72010-09-12 05:06:55 +000011238 DiagID = diag::err_forward_ref_enum;
11239 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011240
11241 // If this is a forward-declared reference to an enumeration, make a
11242 // note of it; we won't actually be introducing the declaration into
11243 // the declaration context.
11244 if (TUK == TUK_Reference)
11245 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +000011246 }
Douglas Gregord45b93b2009-03-06 18:34:03 +000011247 }
Douglas Gregor0bf31402010-10-08 23:50:27 +000011248
11249 if (EnumUnderlying) {
11250 EnumDecl *ED = cast<EnumDecl>(New);
11251 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11252 ED->setIntegerTypeSourceInfo(TI);
11253 else
11254 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11255 ED->setPromotionType(ED->getIntegerType());
11256 }
11257
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000011258 } else {
11259 // struct/union/class
11260
Chris Lattner776fac82007-06-09 00:53:06 +000011261 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11262 // struct X { int A; } D; D should chain to X.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011263 if (getLangOpts().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +000011264 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011265 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011266 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011267
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +000011268 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +000011269 StdBadAlloc = cast<CXXRecordDecl>(New);
11270 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011271 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011272 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000011273 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011274
Richard Smith649c7b062014-01-08 00:56:48 +000011275 // C++11 [dcl.type]p3:
11276 // A type-specifier-seq shall not define a class or enumeration [...].
11277 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11278 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11279 << Context.getTagDeclType(New);
11280 Invalid = true;
11281 }
11282
John McCall3e11ebe2010-03-15 10:12:16 +000011283 // Maybe add qualifier info.
11284 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011285 if (SS.isSet()) {
Douglas Gregorb7d17dd2012-03-28 16:01:27 +000011286 // If this is either a declaration or a definition, check the
11287 // nested-name-specifier against the current context. We don't do this
11288 // for explicit specializations, because they have similar checking
11289 // (with more specific diagnostics) in the call to
11290 // CheckMemberSpecialization, below.
11291 if (!isExplicitSpecialization &&
11292 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11293 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11294 Invalid = true;
11295
Douglas Gregor14454802011-02-25 02:25:35 +000011296 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +000011297 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +000011298 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +000011299 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011300 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +000011301 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +000011302 }
11303 else
11304 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +000011305 }
11306
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000011307 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11308 // Add alignment attributes if necessary; these attributes are checked when
11309 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011310 //
11311 // It is important for implementing the correct semantics that this
11312 // happen here (in act on tag decl). The #pragma pack stack is
11313 // maintained as a result of parser callbacks which can occur at
11314 // many points during the parsing of a struct declaration (because
11315 // the #pragma tokens are effectively skipped over during the
11316 // parsing of the struct).
Eli Friedman0415f3e12012-08-08 21:08:34 +000011317 if (TUK == TUK_Definition) {
11318 AddAlignmentAttributesForRecord(RD);
11319 AddMsStructLayoutForRecord(RD);
11320 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011321 }
11322
Douglas Gregor21823bf2011-12-20 18:11:52 +000011323 if (ModulePrivateLoc.isValid()) {
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +000011324 if (isExplicitSpecialization)
11325 Diag(New->getLocation(), diag::err_module_private_specialization)
11326 << 2
11327 << FixItHint::CreateRemoval(ModulePrivateLoc);
Douglas Gregor41866812011-09-12 18:37:38 +000011328 // __module_private__ does not apply to local classes. However, we only
11329 // diagnose this as an error when the declaration specifiers are
11330 // freestanding. Here, we just ignore the __module_private__.
Douglas Gregor41866812011-09-12 18:37:38 +000011331 else if (!SearchDC->isFunctionOrMethod())
Douglas Gregor2820e692011-09-09 19:05:14 +000011332 New->setModulePrivate();
11333 }
Serge Pavlova8261472014-06-25 17:09:41 +000011334
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011335 // If this is a specialization of a member class (of a class template),
11336 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +000011337 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +000011338 Invalid = true;
Serge Pavlova8261472014-06-25 17:09:41 +000011339
11340 // If we're declaring or defining a tag in function prototype scope in C,
11341 // note that this type can only be used within the function and add it to
11342 // the list of decls to inject into the function definition scope.
11343 if ((Name || Kind == TTK_Enum) &&
11344 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11345 if (getLangOpts().CPlusPlus) {
11346 // C++ [dcl.fct]p6:
11347 // Types shall not be defined in return or parameter types.
11348 if (TUK == TUK_Definition && !IsTypeSpecifier) {
11349 Diag(Loc, diag::err_type_defined_in_param_type)
11350 << Name;
11351 Invalid = true;
11352 }
11353 } else {
11354 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11355 }
11356 DeclsInPrototypeScope.push_back(New);
11357 }
11358
Douglas Gregordee1be82009-01-17 00:42:38 +000011359 if (Invalid)
11360 New->setInvalidDecl();
11361
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011362 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000011363 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +000011364
11365 // Set the lexical context. If the tag has a C++ scope specifier, the
11366 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +000011367 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +000011368
John McCallaa74a0c2009-08-28 07:59:38 +000011369 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +000011370 // In Microsoft mode, a friend declaration also acts as a forward
11371 // declaration so we always pass true to setObjectOfFriendDecl to make
11372 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +000011373 if (TUK == TUK_Friend)
Richard Smith64017682013-07-17 23:53:16 +000011374 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11375 getLangOpts().MicrosoftExt);
John McCallaa74a0c2009-08-28 07:59:38 +000011376
Anders Carlsson5558ca12009-03-26 01:19:02 +000011377 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +000011378 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +000011379 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +000011380
John McCall9bb74a52009-07-31 02:45:11 +000011381 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +000011382 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +000011383
Chris Lattner18b19622007-01-22 07:39:13 +000011384 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +000011385 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +000011386 // We might be replacing an existing declaration in the lookup tables;
11387 // if so, borrow its access specifier.
11388 if (PrevDecl)
11389 New->setAccess(PrevDecl->getAccess());
11390
Sebastian Redl50c68252010-08-31 00:36:30 +000011391 DeclContext *DC = New->getDeclContext()->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011392 DC->makeDeclVisibleInContext(New);
John McCalle9eaf8e2010-03-25 21:28:06 +000011393 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +000011394 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11395 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +000011396 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +000011397 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011398 PushOnScopeChains(New, S, !IsForwardReference);
11399 if (IsForwardReference)
Richard Smith05afe5e2012-03-13 03:12:56 +000011400 SearchDC->makeDeclVisibleInContext(New);
Douglas Gregor0bf31402010-10-08 23:50:27 +000011401
Douglas Gregorc6f58fe2009-01-12 22:49:06 +000011402 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011403 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +000011404 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000011405
Douglas Gregor27821ce2009-07-07 16:35:42 +000011406 // If this is the C FILE type, notify the AST context.
11407 if (IdentifierInfo *II = New->getIdentifier())
11408 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +000011409 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +000011410 II->isStr("FILE"))
11411 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +000011412
Rafael Espindolac67f2232012-05-10 02:50:16 +000011413 if (PrevDecl)
11414 mergeDeclAttributes(New, PrevDecl);
11415
Rafael Espindolae3a14bb2012-07-17 15:14:47 +000011416 // If there's a #pragma GCC visibility in scope, set the visibility of this
11417 // record.
11418 AddPushedVisibilityAttribute(New);
11419
Douglas Gregord6ab8742009-05-28 23:31:59 +000011420 OwnedDecl = true;
Richard Smith3e284692012-12-05 11:34:06 +000011421 // In C++, don't return an invalid declaration. We can't recover well from
11422 // the cases where we make the type anonymous.
Craig Topperc3ec1492014-05-26 06:22:03 +000011423 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
Chris Lattner18b19622007-01-22 07:39:13 +000011424}
Chris Lattner1300fb92007-01-23 23:42:53 +000011425
John McCall48871652010-08-21 09:40:31 +000011426void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011427 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011428 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +000011429
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011430 // Enter the tag context.
11431 PushDeclContext(S, Tag);
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000011432
11433 ActOnDocumentableDecl(TagD);
Rafael Espindola4dedd0c2012-07-12 04:47:34 +000011434
11435 // If there's a #pragma GCC visibility in scope, set the visibility of this
11436 // record.
11437 AddPushedVisibilityAttribute(Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +000011438}
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011439
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011440Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011441 assert(isa<ObjCContainerDecl>(IDecl) &&
11442 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11443 DeclContext *OCD = cast<DeclContext>(IDecl);
11444 assert(getContainingDC(OCD) == CurContext &&
11445 "The next DeclContext should be lexically contained in the current one.");
11446 CurContext = OCD;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011447 return IDecl;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011448}
11449
John McCall48871652010-08-21 09:40:31 +000011450void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +000011451 SourceLocation FinalLoc,
David Majnemera5433082013-10-18 00:33:31 +000011452 bool IsFinalSpelledSealed,
John McCall1c7e6ec2009-12-20 07:58:13 +000011453 SourceLocation LBraceLoc) {
11454 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011455 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011456
John McCall1c7e6ec2009-12-20 07:58:13 +000011457 FieldCollector->StartClass();
11458
11459 if (!Record->getIdentifier())
11460 return;
11461
Anders Carlsson30f29442011-03-25 14:31:08 +000011462 if (FinalLoc.isValid())
David Majnemera5433082013-10-18 00:33:31 +000011463 Record->addAttr(new (Context)
11464 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11465
John McCall1c7e6ec2009-12-20 07:58:13 +000011466 // C++ [class]p2:
11467 // [...] The class-name is also inserted into the scope of the
11468 // class itself; this is known as the injected-class-name. For
11469 // purposes of access checking, the injected-class-name is treated
11470 // as if it were a public member name.
11471 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +000011472 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11473 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +000011474 Record->getIdentifier(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011475 /*PrevDecl=*/nullptr,
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +000011476 /*DelayTypeCreation=*/true);
11477 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +000011478 InjectedClassName->setImplicit();
11479 InjectedClassName->setAccess(AS_public);
11480 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11481 InjectedClassName->setDescribedClassTemplate(Template);
11482 PushOnScopeChains(InjectedClassName, S);
11483 assert(InjectedClassName->isInjectedClassName() &&
11484 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011485}
11486
John McCall48871652010-08-21 09:40:31 +000011487void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011488 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +000011489 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011490 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +000011491 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011492
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011493 // Make sure we "complete" the definition even it is invalid.
11494 if (Tag->isBeingDefined()) {
11495 assert(Tag->isInvalidDecl() && "We should already have completed it");
11496 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11497 RD->completeDefinition();
11498 }
11499
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011500 if (isa<CXXRecordDecl>(Tag))
11501 FieldCollector->FinishClass();
11502
11503 // Exit this scope of this tag's definition.
11504 PopDeclContext();
Argyrios Kyrtzidisc821f732013-01-29 18:00:54 +000011505
11506 if (getCurLexicalContext()->isObjCContainer() &&
11507 Tag->getDeclContext()->isFileContext())
11508 Tag->setTopLevelDeclInObjCContainer();
11509
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011510 // Notify the consumer that we've defined a tag.
Serge Pavlovfb73ec82013-07-02 17:31:56 +000011511 if (!Tag->isInvalidDecl())
11512 Consumer.HandleTagDeclDefinition(Tag);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011513}
Chris Lattner535b8302008-06-21 19:39:06 +000011514
Fariborz Jahanian4327b322011-08-29 17:33:12 +000011515void Sema::ActOnObjCContainerFinishDefinition() {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000011516 // Exit this scope of this interface definition.
11517 PopDeclContext();
11518}
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011519
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011520void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
Argyrios Kyrtzidis67f914d2011-10-27 00:53:06 +000011521 assert(DC == CurContext && "Mismatch of container contexts");
11522 OriginalLexicalContext = DC;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011523 ActOnObjCContainerFinishDefinition();
11524}
11525
Argyrios Kyrtzidisa9aabf72011-10-27 00:09:34 +000011526void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11527 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
Craig Topperc3ec1492014-05-26 06:22:03 +000011528 OriginalLexicalContext = nullptr;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +000011529}
11530
John McCall48871652010-08-21 09:40:31 +000011531void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +000011532 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +000011533 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +000011534 Tag->setInvalidDecl();
11535
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011536 // Make sure we "complete" the definition even it is invalid.
11537 if (Tag->isBeingDefined()) {
11538 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11539 RD->completeDefinition();
11540 }
11541
John McCall71ba5f22010-03-17 19:25:57 +000011542 // We're undoing ActOnTagStartDefinition here, not
11543 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11544 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +000011545
11546 PopDeclContext();
11547}
11548
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011549// Note that FieldName may be null for anonymous bitfields.
Richard Smithf4c51d92012-02-04 09:53:13 +000011550ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11551 IdentifierInfo *FieldName,
Reid Kleckner736bc982013-07-17 20:46:03 +000011552 QualType FieldTy, bool IsMsStruct,
11553 Expr *BitWidth, bool *ZeroWidth) {
Eli Friedmanc96d4962009-08-15 21:55:26 +000011554 // Default to true; that shouldn't confuse checks for emptiness
11555 if (ZeroWidth)
11556 *ZeroWidth = true;
11557
Chris Lattner73bf7b42009-03-05 22:45:59 +000011558 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +000011559 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +000011560 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +000011561 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +000011562 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
Richard Smithf4c51d92012-02-04 09:53:13 +000011563 return ExprError();
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011564 if (FieldName)
11565 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11566 << FieldName << FieldTy << BitWidth->getSourceRange();
11567 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11568 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +000011569 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11570 UPPC_BitFieldWidth))
Richard Smithf4c51d92012-02-04 09:53:13 +000011571 return ExprError();
Douglas Gregor1efa4372009-03-11 18:59:21 +000011572
11573 // If the bit-width is type- or value-dependent, don't try to check
11574 // it now.
11575 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011576 return BitWidth;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011577
Anders Carlsson5df391e2008-12-06 20:33:04 +000011578 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +000011579 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11580 if (ICE.isInvalid())
11581 return ICE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011582 BitWidth = ICE.get();
Anders Carlsson5df391e2008-12-06 20:33:04 +000011583
Eli Friedmanc96d4962009-08-15 21:55:26 +000011584 if (Value != 0 && ZeroWidth)
11585 *ZeroWidth = false;
11586
Chris Lattner81ed6802008-12-12 04:56:04 +000011587 // Zero-width bitfield is ok for anonymous field.
11588 if (Value == 0 && FieldName)
11589 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +000011590
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011591 if (Value.isSigned() && Value.isNegative()) {
11592 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +000011593 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011594 << FieldName << Value.toString(10);
11595 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11596 << Value.toString(10);
11597 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011598
Douglas Gregor1efa4372009-03-11 18:59:21 +000011599 if (!FieldTy->isDependentType()) {
11600 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011601 if (Value.getZExtValue() > TypeSize) {
Warren Hunt96afec12013-12-12 23:23:28 +000011602 if (!getLangOpts().CPlusPlus || IsMsStruct ||
11603 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Anders Carlssond5635fe2010-04-16 15:16:32 +000011604 if (FieldName)
11605 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11606 << FieldName << (unsigned)Value.getZExtValue()
11607 << (unsigned)TypeSize;
11608
11609 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11610 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11611 }
11612
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011613 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +000011614 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11615 << FieldName << (unsigned)Value.getZExtValue()
11616 << (unsigned)TypeSize;
11617 else
11618 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11619 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +000011620 }
Douglas Gregor1efa4372009-03-11 18:59:21 +000011621 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011622
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011623 return BitWidth;
Anders Carlsson5df391e2008-12-06 20:33:04 +000011624}
11625
Richard Smith938f40b2011-06-11 17:19:42 +000011626/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +000011627/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +000011628Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011629 Declarator &D, Expr *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +000011630 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +000011631 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith2b013182012-06-10 03:12:00 +000011632 /*InitStyle=*/ICIS_NoInit, AS_public);
John McCall48871652010-08-21 09:40:31 +000011633 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +000011634}
11635
11636/// HandleField - Analyze a field of a C struct or a C++ data member.
11637///
11638FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11639 SourceLocation DeclStart,
Richard Smith2b013182012-06-10 03:12:00 +000011640 Declarator &D, Expr *BitWidth,
11641 InClassInitStyle InitStyle,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011642 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +000011643 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +000011644 SourceLocation Loc = DeclStart;
11645 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000011646
John McCall8cb7bdf2010-06-04 23:28:52 +000011647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11648 QualType T = TInfo->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011649 if (getLangOpts().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +000011650 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +000011651
Douglas Gregora02a72a2010-12-15 23:18:36 +000011652 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11653 UPPC_DataMemberType)) {
11654 D.setInvalidType();
11655 T = Context.IntTy;
11656 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11657 }
11658 }
11659
Matt Arsenault376f7202013-02-26 21:16:00 +000011660 // TR 18037 does not allow fields to be declared with address spaces.
11661 if (T.getQualifiers().hasAddressSpace()) {
11662 Diag(Loc, diag::err_field_with_address_space);
11663 D.setInvalidType();
11664 }
11665
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000011666 // OpenCL 1.2 spec, s6.9 r:
11667 // The event type cannot be used to declare a structure or union field.
11668 if (LangOpts.OpenCL && T->isEventT()) {
11669 Diag(Loc, diag::err_event_t_struct_field);
11670 D.setInvalidType();
11671 }
11672
Richard Smithb1402ae2013-03-18 22:52:47 +000011673 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Eli Friedman574c7452009-04-07 19:37:57 +000011674
Richard Smithb4a9e862013-04-12 22:46:28 +000011675 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11676 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11677 diag::err_invalid_thread)
11678 << DeclSpec::getSpecifierName(TSCS);
Matt Arsenault376f7202013-02-26 21:16:00 +000011679
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011680 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000011681 NamedDecl *PrevDecl = nullptr;
Douglas Gregor2c7d9292010-08-30 14:32:14 +000011682 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11683 LookupName(Previous, S);
Douglas Gregorfbf87522011-10-21 15:47:52 +000011684 switch (Previous.getResultKind()) {
11685 case LookupResult::Found:
11686 case LookupResult::FoundUnresolvedValue:
11687 PrevDecl = Previous.getAsSingle<NamedDecl>();
11688 break;
11689
11690 case LookupResult::FoundOverloaded:
11691 PrevDecl = Previous.getRepresentativeDecl();
11692 break;
11693
11694 case LookupResult::NotFound:
11695 case LookupResult::NotFoundInCurrentInstantiation:
11696 case LookupResult::Ambiguous:
11697 break;
11698 }
11699 Previous.suppressDiagnostics();
Douglas Gregorf187420f2009-06-17 23:37:01 +000011700
11701 if (PrevDecl && PrevDecl->isTemplateParameter()) {
11702 // Maybe we will complain about the shadowed template parameter.
11703 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11704 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011705 PrevDecl = nullptr;
Douglas Gregorf187420f2009-06-17 23:37:01 +000011706 }
11707
Douglas Gregor1efa4372009-03-11 18:59:21 +000011708 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000011709 PrevDecl = nullptr;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011710
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011711 bool Mutable
11712 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011713 SourceLocation TSSL = D.getLocStart();
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011714 FieldDecl *NewFD
Richard Smith2b013182012-06-10 03:12:00 +000011715 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
Richard Smith938f40b2011-06-11 17:19:42 +000011716 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +000011717
11718 if (NewFD->isInvalidDecl())
11719 Record->setInvalidDecl();
11720
Douglas Gregor3baa6702011-09-12 16:11:24 +000011721 if (D.getDeclSpec().isModulePrivateSpecified())
11722 NewFD->setModulePrivate();
11723
Douglas Gregor1efa4372009-03-11 18:59:21 +000011724 if (NewFD->isInvalidDecl() && PrevDecl) {
11725 // Don't introduce NewFD into scope; there's already something
11726 // with the same name in the same scope.
11727 } else if (II) {
11728 PushOnScopeChains(NewFD, S);
11729 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011730 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011731
11732 return NewFD;
11733}
11734
11735/// \brief Build a new FieldDecl and check its well-formedness.
11736///
11737/// This routine builds a new FieldDecl given the fields name, type,
11738/// record, etc. \p PrevDecl should refer to any previous declaration
11739/// with the same name and in the same scope as the field to be
11740/// created.
11741///
11742/// \returns a new FieldDecl.
11743///
Mike Stump11289f42009-09-09 15:08:12 +000011744/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +000011745FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +000011746 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011747 RecordDecl *Record, SourceLocation Loc,
Richard Smith2b013182012-06-10 03:12:00 +000011748 bool Mutable, Expr *BitWidth,
11749 InClassInitStyle InitStyle,
Steve Naroff5ec6ff72009-07-14 14:58:18 +000011750 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011751 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +000011752 Declarator *D) {
11753 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +000011754 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011755 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011756
Douglas Gregor1efa4372009-03-11 18:59:21 +000011757 // If we receive a broken type, recover by assuming 'int' and
11758 // marking this declaration as invalid.
11759 if (T.isNull()) {
11760 InvalidDecl = true;
11761 T = Context.IntTy;
11762 }
11763
Eli Friedmand0e8de22009-12-07 00:22:08 +000011764 QualType EltTy = Context.getBaseElementType(T);
Argyrios Kyrtzidis25596292012-03-09 20:10:30 +000011765 if (!EltTy->isDependentType()) {
11766 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11767 // Fields of incomplete type force their record to be invalid.
11768 Record->setInvalidDecl();
11769 InvalidDecl = true;
11770 } else {
11771 NamedDecl *Def;
11772 EltTy->isIncompleteType(&Def);
11773 if (Def && Def->isInvalidDecl()) {
11774 Record->setInvalidDecl();
11775 InvalidDecl = true;
11776 }
11777 }
John McCall2677e102010-08-16 23:42:35 +000011778 }
Eli Friedmand0e8de22009-12-07 00:22:08 +000011779
Joey Gouly1d58cdb2013-01-17 17:35:00 +000011780 // OpenCL v1.2 s6.9.c: bitfields are not supported.
11781 if (BitWidth && getLangOpts().OpenCL) {
11782 Diag(Loc, diag::err_opencl_bitfields);
11783 InvalidDecl = true;
11784 }
11785
Steve Naroff8eeeb132007-05-08 21:09:37 +000011786 // C99 6.7.2.1p8: A member of a structure or union may have any type other
11787 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +000011788 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011789 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011790 llvm::APSInt Oversized;
Abramo Bagnara341ab732012-11-08 14:44:42 +000011791
11792 TypeSourceInfo *FixedTInfo =
11793 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11794 SizeIsNegative,
11795 Oversized);
11796 if (FixedTInfo) {
Eli Friedmana3b1d032009-02-21 00:44:51 +000011797 Diag(Loc, diag::warn_illegal_constant_array_size);
Abramo Bagnara341ab732012-11-08 14:44:42 +000011798 TInfo = FixedTInfo;
11799 T = FixedTInfo->getType();
Eli Friedmana3b1d032009-02-21 00:44:51 +000011800 } else {
11801 if (SizeIsNegative)
11802 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +000011803 else if (Oversized.getBoolValue())
11804 Diag(Loc, diag::err_array_too_large)
11805 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011806 else
11807 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +000011808 InvalidDecl = true;
11809 }
Steve Naroff8eeeb132007-05-08 21:09:37 +000011810 }
Mike Stump11289f42009-09-09 15:08:12 +000011811
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011812 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +000011813 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11814 diag::err_abstract_type_in_decl,
11815 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +000011816 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +000011817
Eli Friedmanc96d4962009-08-15 21:55:26 +000011818 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +000011819 // If this is declared as a bit-field, check the bit-field.
Richard Smithf4c51d92012-02-04 09:53:13 +000011820 if (!InvalidDecl && BitWidth) {
Reid Kleckner736bc982013-07-17 20:46:03 +000011821 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011822 &ZeroWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000011823 if (!BitWidth) {
11824 InvalidDecl = true;
Craig Topperc3ec1492014-05-26 06:22:03 +000011825 BitWidth = nullptr;
Richard Smithf4c51d92012-02-04 09:53:13 +000011826 ZeroWidth = false;
11827 }
Anders Carlsson5df391e2008-12-06 20:33:04 +000011828 }
Mike Stump11289f42009-09-09 15:08:12 +000011829
John McCallb1cd7da2010-06-04 08:34:12 +000011830 // Check that 'mutable' is consistent with the type of the declaration.
11831 if (!InvalidDecl && Mutable) {
11832 unsigned DiagID = 0;
11833 if (T->isReferenceType())
11834 DiagID = diag::err_mutable_reference;
11835 else if (T.isConstQualified())
11836 DiagID = diag::err_mutable_const;
11837
11838 if (DiagID) {
11839 SourceLocation ErrLoc = Loc;
11840 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11841 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11842 Diag(ErrLoc, DiagID);
11843 Mutable = false;
11844 InvalidDecl = true;
11845 }
11846 }
11847
Richard Smithab44d5b2013-12-10 08:25:00 +000011848 // C++11 [class.union]p8 (DR1460):
11849 // At most one variant member of a union may have a
11850 // brace-or-equal-initializer.
11851 if (InitStyle != ICIS_NoInit)
11852 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11853
Abramo Bagnaradff19302011-03-08 08:55:46 +000011854 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +000011855 BitWidth, Mutable, InitStyle);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011856 if (InvalidDecl)
11857 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +000011858
Douglas Gregor1efa4372009-03-11 18:59:21 +000011859 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11860 Diag(Loc, diag::err_duplicate_member) << II;
11861 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11862 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +000011863 }
11864
David Blaikiebbafb8a2012-03-11 07:00:24 +000011865 if (!InvalidDecl && getLangOpts().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011866 if (Record->isUnion()) {
11867 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11868 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11869 if (RDecl->getDefinition()) {
11870 // C++ [class.union]p1: An object of a class with a non-trivial
11871 // constructor, a non-trivial copy constructor, a non-trivial
11872 // destructor, or a non-trivial copy assignment operator
11873 // cannot be a member of a union, nor can an array of such
11874 // objects.
Richard Smithf720df02011-10-19 20:41:51 +000011875 if (CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011876 NewFD->setInvalidDecl();
11877 }
11878 }
11879
11880 // C++ [class.union]p1: If a union contains a member of reference type,
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011881 // the program is ill-formed, except when compiling with MSVC extensions
11882 // enabled.
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011883 if (EltTy->isReferenceType()) {
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011884 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11885 diag::ext_union_member_of_reference_type :
11886 diag::err_union_member_of_reference_type)
Anders Carlsson2ceb3472010-11-07 19:13:55 +000011887 << NewFD->getDeclName() << EltTy;
Aaron Ballmaned0ae1d2013-05-30 16:20:00 +000011888 if (!getLangOpts().MicrosoftExt)
11889 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +000011890 }
11891 }
11892 }
11893
Douglas Gregor1efa4372009-03-11 18:59:21 +000011894 // FIXME: We need to pass in the attributes given an AST
11895 // representation, not a parser representation.
Richard Smith848e1f12013-02-01 08:12:08 +000011896 if (D) {
Douglas Gregord2472d42013-05-02 23:25:32 +000011897 // FIXME: The current scope is almost... but not entirely... correct here.
11898 ProcessDeclAttributes(getCurScope(), NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +000011899
Richard Smith848e1f12013-02-01 08:12:08 +000011900 if (NewFD->hasAttrs())
11901 CheckAlignasUnderalignment(NewFD);
11902 }
11903
John McCall31168b02011-06-15 23:02:42 +000011904 // In auto-retain/release, infer strong retension for fields of
11905 // retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011906 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
John McCall31168b02011-06-15 23:02:42 +000011907 NewFD->setInvalidDecl();
11908
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +000011909 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +000011910 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +000011911
Douglas Gregor4261e4c2009-03-11 20:50:30 +000011912 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +000011913 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +000011914}
11915
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011916bool Sema::CheckNontrivialField(FieldDecl *FD) {
11917 assert(FD);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011918 assert(getLangOpts().CPlusPlus && "valid check only for C++");
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011919
Nick Lewycky7a2a4792013-06-25 23:22:23 +000011920 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11921 return false;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011922
11923 QualType EltTy = Context.getBaseElementType(FD->getType());
11924 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Richard Smith92f241f2012-12-08 02:53:02 +000011925 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011926 if (RDecl->getDefinition()) {
11927 // We check for copy constructors before constructors
11928 // because otherwise we'll never get complaints about
11929 // copy constructors.
11930
11931 CXXSpecialMember member = CXXInvalid;
Richard Smith16488472012-11-16 00:53:38 +000011932 // We're required to check for any non-trivial constructors. Since the
11933 // implicit default constructor is suppressed if there are any
11934 // user-declared constructors, we just need to check that there is a
11935 // trivial default constructor and a trivial copy constructor. (We don't
11936 // worry about move constructors here, since this is a C++98 check.)
11937 if (RDecl->hasNonTrivialCopyConstructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011938 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +000011939 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +000011940 member = CXXDefaultConstructor;
Richard Smith16488472012-11-16 00:53:38 +000011941 else if (RDecl->hasNonTrivialCopyAssignment())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011942 member = CXXCopyAssignment;
Richard Smith16488472012-11-16 00:53:38 +000011943 else if (RDecl->hasNonTrivialDestructor())
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011944 member = CXXDestructor;
11945
11946 if (member != CXXInvalid) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011947 if (!getLangOpts().CPlusPlus11 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011948 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
John McCall31168b02011-06-15 23:02:42 +000011949 // Objective-C++ ARC: it is an error to have a non-trivial field of
11950 // a union. However, system headers in Objective-C programs
11951 // occasionally have Objective-C lifetime objects within unions,
11952 // and rather than cause the program to fail, we make those
11953 // members unavailable.
11954 SourceLocation Loc = FD->getLocation();
11955 if (getSourceManager().isInSystemHeader(Loc)) {
11956 if (!FD->hasAttr<UnavailableAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +000011957 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11958 "this system field has retaining ownership",
11959 Loc));
John McCall31168b02011-06-15 23:02:42 +000011960 return false;
11961 }
11962 }
Richard Smithf720df02011-10-19 20:41:51 +000011963
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011964 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
Richard Smithf720df02011-10-19 20:41:51 +000011965 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11966 diag::err_illegal_union_or_anon_struct_member)
11967 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
Richard Smith92f241f2012-12-08 02:53:02 +000011968 DiagnoseNontrivial(RDecl, member);
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011969 return !getLangOpts().CPlusPlus11;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011970 }
11971 }
11972 }
Richard Smith92f241f2012-12-08 02:53:02 +000011973
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +000011974 return false;
11975}
11976
Mike Stump11289f42009-09-09 15:08:12 +000011977/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011978/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +000011979static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +000011980TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +000011981 switch (ivarVisibility) {
David Blaikie83d382b2011-09-23 05:06:16 +000011982 default: llvm_unreachable("Unknown visitibility kind");
Chris Lattner79ef8432008-10-12 00:28:42 +000011983 case tok::objc_private: return ObjCIvarDecl::Private;
11984 case tok::objc_public: return ObjCIvarDecl::Public;
11985 case tok::objc_protected: return ObjCIvarDecl::Protected;
11986 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +000011987 }
11988}
11989
Mike Stump11289f42009-09-09 15:08:12 +000011990/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +000011991/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +000011992Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +000011993 SourceLocation DeclStart,
Richard Trieu2bd04012011-09-09 02:00:50 +000011994 Declarator &D, Expr *BitfieldWidth,
Chris Lattner83f095c2009-03-28 19:18:32 +000011995 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +000011996
Fariborz Jahaniande615832008-04-10 23:32:45 +000011997 IdentifierInfo *II = D.getIdentifier();
11998 Expr *BitWidth = (Expr*)BitfieldWidth;
11999 SourceLocation Loc = DeclStart;
12000 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +000012001
Fariborz Jahaniande615832008-04-10 23:32:45 +000012002 // FIXME: Unnamed fields can be handled in various different ways, for
12003 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +000012004
John McCall8cb7bdf2010-06-04 23:28:52 +000012005 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12006 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +000012007
Fariborz Jahaniande615832008-04-10 23:32:45 +000012008 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +000012009 // 6.7.2.1p3, 6.7.2.1p4
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012010 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
Richard Smithf4c51d92012-02-04 09:53:13 +000012011 if (!BitWidth)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012012 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000012013 } else {
12014 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +000012015
Fariborz Jahaniande615832008-04-10 23:32:45 +000012016 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +000012017
Fariborz Jahaniande615832008-04-10 23:32:45 +000012018 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +000012019 if (T->isReferenceType()) {
12020 Diag(Loc, diag::err_ivar_reference_type);
12021 D.setInvalidType();
12022 }
Fariborz Jahaniande615832008-04-10 23:32:45 +000012023 // C99 6.7.2.1p8: A member of a structure or union may have any type other
12024 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +000012025 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +000012026 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012027 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +000012028 }
Mike Stump11289f42009-09-09 15:08:12 +000012029
Ted Kremenek73295fa2008-07-23 18:04:17 +000012030 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +000012031 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +000012032 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12033 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +000012034 // Must set ivar's DeclContext to its enclosing interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012035 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
Fariborz Jahanian17612b12012-02-02 00:49:12 +000012036 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +000012037 return nullptr;
Daniel Dunbar229385c2010-04-02 18:29:09 +000012038 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +000012039 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +000012040 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000012041 if (LangOpts.ObjCRuntime.isFragile()) {
Fariborz Jahanian68453832009-06-05 18:16:35 +000012042 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +000012043 EnclosingContext = IMPDecl->getClassInterface();
12044 assert(EnclosingContext && "Implementation has no class interface!");
12045 }
12046 else
12047 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012048 } else {
12049 if (ObjCCategoryDecl *CDecl =
12050 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
John McCall5fb5df92012-06-20 06:18:46 +000012051 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012052 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
Craig Topperc3ec1492014-05-26 06:22:03 +000012053 return nullptr;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012054 }
12055 }
Daniel Dunbar229385c2010-04-02 18:29:09 +000012056 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012057 }
Mike Stump11289f42009-09-09 15:08:12 +000012058
Ted Kremenek73295fa2008-07-23 18:04:17 +000012059 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012060 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12061 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +000012062 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +000012063
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012064 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012065 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +000012066 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012067 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012068 && !isa<TagDecl>(PrevDecl)) {
12069 Diag(Loc, diag::err_duplicate_member) << II;
12070 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12071 NewID->setInvalidDecl();
12072 }
12073 }
12074
Ted Kremenek73295fa2008-07-23 18:04:17 +000012075 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +000012076 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +000012077
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012078 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +000012079 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +000012080
John McCall31168b02011-06-15 23:02:42 +000012081 // In ARC, infer 'retaining' for ivars of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012082 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
John McCall31168b02011-06-15 23:02:42 +000012083 NewID->setInvalidDecl();
12084
Douglas Gregor3baa6702011-09-12 16:11:24 +000012085 if (D.getDeclSpec().isModulePrivateSpecified())
12086 NewID->setModulePrivate();
12087
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012088 if (II) {
12089 // FIXME: When interfaces are DeclContexts, we'll need to add
12090 // these to the interface.
John McCall48871652010-08-21 09:40:31 +000012091 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012092 IdResolver.AddDecl(NewID);
12093 }
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012094
John McCall5fb5df92012-06-20 06:18:46 +000012095 if (LangOpts.ObjCRuntime.isNonFragile() &&
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012096 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Fariborz Jahaniane1ada582012-05-15 17:43:16 +000012097 Diag(Loc, diag::warn_ivars_in_interface);
Fariborz Jahanian80297b12012-05-15 16:33:04 +000012098
John McCall48871652010-08-21 09:40:31 +000012099 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +000012100}
12101
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012102/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
Jordan Rosea0e9d392013-04-03 01:39:23 +000012103/// class and class extensions. For every class \@interface and class
12104/// extension \@interface, if the last ivar is a bitfield of any type,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012105/// then add an implicit `char :0` ivar to the end of that interface.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012106void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012107 SmallVectorImpl<Decl *> &AllIvarDecls) {
John McCall5fb5df92012-06-20 06:18:46 +000012108 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012109 return;
12110
12111 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12112 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12113
Richard Smithcaf33902011-10-10 18:28:20 +000012114 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012115 return;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012116 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012117 if (!ID) {
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012118 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012119 if (!CD->IsClassExtension())
12120 return;
12121 }
12122 // No need to add this to end of @implementation.
12123 else
12124 return;
12125 }
12126 // All conditions are met. Add a new bitfield to the tail end of ivars.
Douglas Gregor1d394802011-08-03 16:26:46 +000012127 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12128 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012129
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000012130 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
Craig Topperc3ec1492014-05-26 06:22:03 +000012131 DeclLoc, DeclLoc, nullptr,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012132 Context.CharTy,
Douglas Gregor1d394802011-08-03 16:26:46 +000012133 Context.getTrivialTypeSourceInfo(Context.CharTy,
12134 DeclLoc),
Fariborz Jahanian616d3e72010-08-23 22:46:52 +000012135 ObjCIvarDecl::Private, BW,
12136 true);
12137 AllIvarDecls.push_back(Ivar);
12138}
12139
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012140void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12141 ArrayRef<Decl *> Fields, SourceLocation LBrac,
12142 SourceLocation RBrac, AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +000012143 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +000012144
Eric Christopher7457aaf2012-07-19 22:22:51 +000012145 // If this is an Objective-C @implementation or category and we have
12146 // new fields here we should reset the layout of the interface since
12147 // it will now change.
12148 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12149 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12150 switch (DC->getKind()) {
12151 default: break;
12152 case Decl::ObjCCategory:
12153 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12154 break;
12155 case Decl::ObjCImplementation:
12156 Context.
12157 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12158 break;
12159 }
12160 }
12161
Eli Friedmana7679412012-02-07 05:00:47 +000012162 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12163
12164 // Start counting up the number of named members; make sure to include
12165 // members of anonymous structs and unions in the total.
Chris Lattner82625602007-01-24 02:26:21 +000012166 unsigned NumNamedMembers = 0;
Eli Friedmana7679412012-02-07 05:00:47 +000012167 if (Record) {
Aaron Ballman629afae2014-03-07 19:56:05 +000012168 for (const auto *I : Record->decls()) {
12169 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
Eli Friedmana7679412012-02-07 05:00:47 +000012170 if (IFD->getDeclName())
12171 ++NumNamedMembers;
12172 }
12173 }
12174
12175 // Verify that all the fields are okay.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012176 SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +000012177
John McCall31168b02011-06-15 23:02:42 +000012178 bool ARCErrReported = false;
Robert Wilhelm16e94b92013-08-09 18:02:13 +000012179 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
David Blaikie751c5582011-09-22 02:58:26 +000012180 i != end; ++i) {
12181 FieldDecl *FD = cast<FieldDecl>(*i);
Mike Stump11289f42009-09-09 15:08:12 +000012182
Chris Lattner720a0542007-01-25 00:44:24 +000012183 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +000012184 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +000012185
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012186 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +000012187 // Remember all fields written by the user.
12188 RecFields.push_back(FD);
12189 }
Mike Stump11289f42009-09-09 15:08:12 +000012190
Chris Lattner73bf7b42009-03-05 22:45:59 +000012191 // If the field is already invalid for some reason, don't emit more
12192 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +000012193 if (FD->isInvalidDecl()) {
12194 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +000012195 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +000012196 }
Mike Stump11289f42009-09-09 15:08:12 +000012197
Douglas Gregorac1fb652009-03-24 19:52:54 +000012198 // C99 6.7.2.1p2:
12199 // A structure or union shall not contain a member with
12200 // incomplete or function type (hence, a structure shall not
12201 // contain an instance of itself, but may contain a pointer to
12202 // an instance of itself), except that the last member of a
12203 // structure with more than one named member may have incomplete
12204 // array type; such a structure (and any union containing,
12205 // possibly recursively, a member that is such a structure)
12206 // shall not be a member of a structure or an element of an
12207 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +000012208 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012209 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +000012210 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012211 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +000012212 FD->setInvalidDecl();
12213 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012214 continue;
Francois Pichetf657b632010-09-15 00:14:08 +000012215 } else if (FDTy->isIncompleteArrayType() && Record &&
David Blaikie751c5582011-09-22 02:58:26 +000012216 ((i + 1 == Fields.end() && !Record->isUnion()) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +000012217 ((getLangOpts().MicrosoftExt ||
12218 getLangOpts().CPlusPlus) &&
David Blaikie751c5582011-09-22 02:58:26 +000012219 (i + 1 == Fields.end() || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012220 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +000012221 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +000012222 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +000012223 // as the sole element of a struct/class.
David Majnemer41016212013-11-02 10:38:05 +000012224 unsigned DiagID = 0;
12225 if (Record->isUnion())
12226 DiagID = getLangOpts().MicrosoftExt
12227 ? diag::ext_flexible_array_union_ms
12228 : getLangOpts().CPlusPlus
12229 ? diag::ext_flexible_array_union_gnu
12230 : diag::err_flexible_array_union;
12231 else if (Fields.size() == 1)
12232 DiagID = getLangOpts().MicrosoftExt
12233 ? diag::ext_flexible_array_empty_aggregate_ms
12234 : getLangOpts().CPlusPlus
12235 ? diag::ext_flexible_array_empty_aggregate_gnu
12236 : NumNamedMembers < 1
12237 ? diag::err_flexible_array_empty_aggregate
12238 : 0;
12239
12240 if (DiagID)
12241 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12242 << Record->getTagKind();
David Majnemer08cd7602013-11-02 11:19:13 +000012243 // While the layout of types that contain virtual bases is not specified
12244 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12245 // virtual bases after the derived members. This would make a flexible
12246 // array member declared at the end of an object not adjacent to the end
12247 // of the type.
12248 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12249 if (RD->getNumVBases() != 0)
12250 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12251 << FD->getDeclName() << Record->getTagKind();
David Majnemer41016212013-11-02 10:38:05 +000012252 if (!getLangOpts().C99)
12253 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12254 << FD->getDeclName() << Record->getTagKind();
12255
Richard Smith6fa28ff2014-01-11 00:53:35 +000012256 // If the element type has a non-trivial destructor, we would not
12257 // implicitly destroy the elements, so disallow it for now.
12258 //
12259 // FIXME: GCC allows this. We should probably either implicitly delete
12260 // the destructor of the containing class, or just allow this.
12261 QualType BaseElem = Context.getBaseElementType(FD->getType());
12262 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12263 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +000012264 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000012265 FD->setInvalidDecl();
12266 EnclosingDecl->setInvalidDecl();
12267 continue;
12268 }
Chris Lattner720a0542007-01-25 00:44:24 +000012269 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +000012270 if (Record)
12271 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +000012272 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +000012273 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +000012274 diag::err_field_incomplete)) {
12275 // Incomplete type
12276 FD->setInvalidDecl();
12277 EnclosingDecl->setInvalidDecl();
12278 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012279 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +000012280 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12281 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +000012282 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +000012283 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012284 } else {
12285 // If this is a struct/class and this is not the last element, reject
12286 // it. Note that GCC supports variable sized arrays in the middle of
12287 // structures.
David Blaikie751c5582011-09-22 02:58:26 +000012288 if (i + 1 != Fields.end())
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012289 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +000012290 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +000012291 else {
12292 // We support flexible arrays at the end of structs in
12293 // other structs as an extension.
12294 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12295 << FD->getDeclName();
12296 if (Record)
12297 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +000012298 }
Chris Lattner720a0542007-01-25 00:44:24 +000012299 }
12300 }
Fariborz Jahanian78f565b2012-08-16 22:38:41 +000012301 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12302 RequireNonAbstractType(FD->getLocation(), FD->getType(),
12303 diag::err_abstract_type_in_decl,
12304 AbstractIvarType)) {
12305 // Ivars can not have abstract class types
12306 FD->setInvalidDecl();
12307 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000012308 if (Record && FDTTy->getDecl()->hasObjectMember())
12309 Record->setHasObjectMember(true);
Fariborz Jahanian78652202013-01-25 23:57:05 +000012310 if (Record && FDTTy->getDecl()->hasVolatileMember())
12311 Record->setHasVolatileMember(true);
John McCall8b07ec22010-05-15 11:32:37 +000012312 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +000012313 /// A field cannot be an Objective-c object
Fariborz Jahanian6507135e2011-07-26 17:58:54 +000012314 Diag(FD->getLocation(), diag::err_statically_allocated_object)
12315 << FixItHint::CreateInsertion(FD->getLocation(), "*");
12316 QualType T = Context.getObjCObjectPointerType(FD->getType());
12317 FD->setType(T);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012318 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12319 (!getLangOpts().CPlusPlus || Record->isUnion())) {
12320 // It's an error in ARC if a field has lifetime.
12321 // We don't want to report this in a system header, though,
12322 // so we just make the field unavailable.
12323 // FIXME: that's really not sufficient; we need to make the type
12324 // itself invalid to, say, initialize or copy.
12325 QualType T = FD->getType();
12326 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12327 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12328 SourceLocation loc = FD->getLocation();
12329 if (getSourceManager().isInSystemHeader(loc)) {
12330 if (!FD->hasAttr<UnavailableAttr>()) {
Aaron Ballman36a53502014-01-16 13:03:14 +000012331 FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12332 "this system field has retaining ownership",
12333 loc));
John McCall31168b02011-06-15 23:02:42 +000012334 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012335 } else {
12336 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
Douglas Gregor0ad84b42013-01-28 20:13:44 +000012337 << T->isBlockPointerType() << Record->getTagKind();
John McCall31168b02011-06-15 23:02:42 +000012338 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012339 ARCErrReported = true;
John McCall31168b02011-06-15 23:02:42 +000012340 }
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012341 } else if (getLangOpts().ObjC1 &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012342 getLangOpts().getGC() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +000012343 Record && !Record->hasObjectMember()) {
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012344 if (FD->getType()->isObjCObjectPointerType() ||
12345 FD->getType().isObjCGCStrong())
12346 Record->setHasObjectMember(true);
12347 else if (Context.getAsArrayType(FD->getType())) {
12348 QualType BaseType = Context.getBaseElementType(FD->getType());
12349 if (BaseType->isRecordType() &&
12350 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
John McCall31168b02011-06-15 23:02:42 +000012351 Record->setHasObjectMember(true);
Douglas Gregore6c3fa02013-01-28 19:08:09 +000012352 else if (BaseType->isObjCObjectPointerType() ||
12353 BaseType.isObjCGCStrong())
12354 Record->setHasObjectMember(true);
John McCall31168b02011-06-15 23:02:42 +000012355 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +000012356 }
Fariborz Jahanian78652202013-01-25 23:57:05 +000012357 if (Record && FD->getType().isVolatileQualified())
12358 Record->setHasVolatileMember(true);
Chris Lattner82625602007-01-24 02:26:21 +000012359 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +000012360 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +000012361 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +000012362 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012363
Chris Lattner82625602007-01-24 02:26:21 +000012364 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +000012365 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +000012366 bool Completed = false;
12367 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12368 if (!CXXRecord->isInvalidDecl()) {
12369 // Set access bits correctly on the directly-declared conversions.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000012370 for (CXXRecordDecl::conversion_iterator
12371 I = CXXRecord->conversion_begin(),
12372 E = CXXRecord->conversion_end(); I != E; ++I)
12373 I.setAccess((*I)->getAccess());
Douglas Gregor8fb95122010-09-29 00:15:42 +000012374
12375 if (!CXXRecord->isDependentType()) {
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012376 if (CXXRecord->hasUserDeclaredDestructor()) {
12377 // Adjust user-defined destructor exception spec.
12378 if (getLangOpts().CPlusPlus11)
12379 AdjustDestructorExceptionSpec(CXXRecord,
12380 CXXRecord->getDestructor());
Peter Collingbourneb289fe62013-05-20 14:12:25 +000012381 }
Sebastian Redl623ea822011-05-19 05:13:44 +000012382
Douglas Gregor8fb95122010-09-29 00:15:42 +000012383 // Add any implicitly-declared members to this class.
12384 AddImplicitlyDeclaredMembersToClass(CXXRecord);
12385
12386 // If we have virtual base classes, we may end up finding multiple
12387 // final overriders for a given virtual function. Check for this
12388 // problem now.
12389 if (CXXRecord->getNumVBases()) {
12390 CXXFinalOverriderMap FinalOverriders;
12391 CXXRecord->getFinalOverriders(FinalOverriders);
12392
12393 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12394 MEnd = FinalOverriders.end();
12395 M != MEnd; ++M) {
12396 for (OverridingMethods::iterator SO = M->second.begin(),
12397 SOEnd = M->second.end();
12398 SO != SOEnd; ++SO) {
12399 assert(SO->second.size() > 0 &&
12400 "Virtual function without overridding functions?");
12401 if (SO->second.size() == 1)
12402 continue;
12403
12404 // C++ [class.virtual]p2:
12405 // In a derived class, if a virtual member function of a base
12406 // class subobject has more than one final overrider the
12407 // program is ill-formed.
12408 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
Roman Divackye6377112012-09-06 15:59:27 +000012409 << (const NamedDecl *)M->first << Record;
Douglas Gregor8fb95122010-09-29 00:15:42 +000012410 Diag(M->first->getLocation(),
12411 diag::note_overridden_virtual_function);
12412 for (OverridingMethods::overriding_iterator
12413 OM = SO->second.begin(),
12414 OMEnd = SO->second.end();
12415 OM != OMEnd; ++OM)
12416 Diag(OM->Method->getLocation(), diag::note_final_overrider)
Roman Divackye6377112012-09-06 15:59:27 +000012417 << (const NamedDecl *)M->first << OM->Method->getParent();
Douglas Gregor8fb95122010-09-29 00:15:42 +000012418
12419 Record->setInvalidDecl();
12420 }
12421 }
12422 CXXRecord->completeDefinition(&FinalOverriders);
12423 Completed = true;
12424 }
12425 }
12426 }
12427 }
12428
12429 if (!Completed)
12430 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +000012431
David Majnemer2c4e00a2014-01-29 22:07:36 +000012432 if (Record->hasAttrs()) {
Richard Smith848e1f12013-02-01 08:12:08 +000012433 CheckAlignasUnderalignment(Record);
Serge Pavlov89578fd2013-06-08 13:29:58 +000012434
David Majnemer98c9ee22014-02-07 00:43:07 +000012435 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
David Majnemer2c4e00a2014-01-29 22:07:36 +000012436 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
David Majnemer4bb09802014-02-10 19:50:15 +000012437 IA->getRange(), IA->getBestCase(),
David Majnemer2c4e00a2014-01-29 22:07:36 +000012438 IA->getSemanticSpelling());
12439 }
12440
Serge Pavlov3cb80222013-11-14 02:13:03 +000012441 // Check if the structure/union declaration is a type that can have zero
12442 // size in C. For C this is a language extension, for C++ it may cause
12443 // compatibility problems.
12444 bool CheckForZeroSize;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012445 if (!getLangOpts().CPlusPlus) {
Serge Pavlov3cb80222013-11-14 02:13:03 +000012446 CheckForZeroSize = true;
12447 } else {
12448 // For C++ filter out types that cannot be referenced in C code.
12449 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12450 CheckForZeroSize =
12451 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12452 !CXXRecord->isDependentType() &&
12453 CXXRecord->isCLike();
12454 }
12455 if (CheckForZeroSize) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012456 bool ZeroSize = true;
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012457 bool IsEmpty = true;
12458 unsigned NonBitFields = 0;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012459 for (RecordDecl::field_iterator I = Record->field_begin(),
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012460 E = Record->field_end();
12461 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12462 IsEmpty = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012463 if (I->isUnnamedBitfield()) {
Serge Pavlov89578fd2013-06-08 13:29:58 +000012464 if (I->getBitWidthValue(Context) > 0)
12465 ZeroSize = false;
12466 } else {
Serge Pavlovf7c1a212013-06-17 17:18:51 +000012467 ++NonBitFields;
12468 QualType FieldType = I->getType();
12469 if (FieldType->isIncompleteType() ||
12470 !Context.getTypeSizeInChars(FieldType).isZero())
12471 ZeroSize = false;
Serge Pavlov89578fd2013-06-08 13:29:58 +000012472 }
12473 }
12474
Serge Pavlov3cb80222013-11-14 02:13:03 +000012475 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12476 // allowed in C++, but warn if its declaration is inside
12477 // extern "C" block.
12478 if (ZeroSize) {
12479 Diag(RecLoc, getLangOpts().CPlusPlus ?
12480 diag::warn_zero_size_struct_union_in_extern_c :
12481 diag::warn_zero_size_struct_union_compat)
12482 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12483 }
Serge Pavlov89578fd2013-06-08 13:29:58 +000012484
Serge Pavlov3cb80222013-11-14 02:13:03 +000012485 // Structs without named members are extension in C (C99 6.7.2.1p7),
12486 // but are accepted by GCC.
12487 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12488 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12489 diag::ext_no_named_members_in_struct_union)
12490 << Record->isUnion();
Serge Pavlov89578fd2013-06-08 13:29:58 +000012491 }
12492 }
Chris Lattner622c1932008-02-06 00:51:33 +000012493 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +000012494 ObjCIvarDecl **ClsFields =
12495 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +000012496 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Douglas Gregor16408322011-12-15 22:34:59 +000012497 ID->setEndOfDefinitionLoc(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012498 // Add ivar's to class's DeclContext.
12499 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12500 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012501 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +000012502 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +000012503 // Must enforce the rule that ivars in the base classes may not be
12504 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +000012505 if (ID->getSuperClass())
12506 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +000012507 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +000012508 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +000012509 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +000012510 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12511 // Ivar declared in @implementation never belongs to the implementation.
12512 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +000012513 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +000012514 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012515 IMPDecl->setIvarLBraceLoc(LBrac);
12516 IMPDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012517 } else if (ObjCCategoryDecl *CDecl =
12518 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012519 // case of ivars in class extension; all other cases have been
12520 // reported as errors elsewhere.
12521 // FIXME. Class extension does not have a LocEnd field.
12522 // CDecl->setLocEnd(RBrac);
12523 // Add ivar's to class extension's DeclContext.
Fariborz Jahanian25127472011-10-21 18:03:52 +000012524 // Diagnose redeclaration of private ivars.
12525 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012526 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012527 if (IDecl) {
12528 if (const ObjCIvarDecl *ClsIvar =
12529 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12530 Diag(ClsFields[i]->getLocation(),
12531 diag::err_duplicate_ivar_declaration);
12532 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12533 continue;
12534 }
Aaron Ballmanb4a53452014-03-13 21:57:01 +000012535 for (const auto *Ext : IDecl->known_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +000012536 if (const ObjCIvarDecl *ClsExtIvar
12537 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Fariborz Jahanian25127472011-10-21 18:03:52 +000012538 Diag(ClsFields[i]->getLocation(),
12539 diag::err_duplicate_ivar_declaration);
12540 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12541 continue;
12542 }
12543 }
12544 }
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +000012545 ClsFields[i]->setLexicalDeclContext(CDecl);
12546 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +000012547 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +000012548 CDecl->setIvarLBraceLoc(LBrac);
12549 CDecl->setIvarRBraceLoc(RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +000012550 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +000012551 }
Daniel Dunbar325601a2008-10-03 17:33:35 +000012552
12553 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +000012554 ProcessDeclAttributeList(S, Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +000012555}
12556
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012557/// \brief Determine whether the given integral value is representable within
12558/// the given type T.
12559static bool isRepresentableIntegerValue(ASTContext &Context,
12560 llvm::APSInt &Value,
12561 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +000012562 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +000012563 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012564
Douglas Gregor0bf31402010-10-08 23:50:27 +000012565 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012566 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +000012567 --BitWidth;
12568 return Value.getActiveBits() <= BitWidth;
12569 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012570 return Value.getMinSignedBits() <= BitWidth;
12571}
12572
12573// \brief Given an integral type, return the next larger integral type
12574// (or a NULL type of no such type exists).
12575static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12576 // FIXME: Int128/UInt128 support, which also needs to be introduced into
12577 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +000012578 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012579 const unsigned NumTypes = 4;
12580 QualType SignedIntegralTypes[NumTypes] = {
12581 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12582 };
12583 QualType UnsignedIntegralTypes[NumTypes] = {
12584 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12585 Context.UnsignedLongLongTy
12586 };
12587
12588 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012589 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12590 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012591 for (unsigned I = 0; I != NumTypes; ++I)
12592 if (Context.getTypeSize(Types[I]) > BitWidth)
12593 return Types[I];
12594
12595 return QualType();
12596}
12597
Douglas Gregor954f6b272009-03-17 19:05:46 +000012598EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12599 EnumConstantDecl *LastEnumConst,
12600 SourceLocation IdLoc,
12601 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +000012602 Expr *Val) {
Douglas Gregore8bbc122011-09-02 00:18:52 +000012603 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012604 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012605 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012606
12607 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
Craig Topperc3ec1492014-05-26 06:22:03 +000012608 Val = nullptr;
Douglas Gregor2b988fd2010-12-16 00:24:44 +000012609
Eli Friedman7c6515a2011-12-06 00:10:34 +000012610 if (Val)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012611 Val = DefaultLvalueConversion(Val).get();
Eli Friedman7c6515a2011-12-06 00:10:34 +000012612
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012613 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012614 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012615 EltTy = Context.DependentTy;
12616 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012617 SourceLocation ExpLoc;
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012618 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000012619 !getLangOpts().MSVCCompat) {
Richard Smithf8379a02012-01-18 23:55:52 +000012620 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12621 // constant-expression in the enumerator-definition shall be a converted
12622 // constant expression of the underlying type.
12623 EltTy = Enum->getIntegerType();
12624 ExprResult Converted =
12625 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12626 CCEK_Enumerator);
12627 if (Converted.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +000012628 Val = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +000012629 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012630 Val = Converted.get();
Richard Smithf8379a02012-01-18 23:55:52 +000012631 } else if (!Val->isValueDependent() &&
Richard Smithf4c51d92012-02-04 09:53:13 +000012632 !(Val = VerifyIntegerConstantExpression(Val,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012633 &EnumVal).get())) {
Richard Smithf8379a02012-01-18 23:55:52 +000012634 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
Richard Smithf8379a02012-01-18 23:55:52 +000012635 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +000012636 if (Enum->isFixed()) {
12637 EltTy = Enum->getIntegerType();
12638
Richard Smithf8379a02012-01-18 23:55:52 +000012639 // In Obj-C and Microsoft mode, require the enumeration value to be
12640 // representable in the underlying type of the enumeration. In C++11,
12641 // we perform a non-narrowing conversion as part of converted constant
12642 // expression checking.
Francois Picheta3108062010-10-18 15:01:13 +000012643 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Alp Tokerbfa39342014-01-14 12:51:41 +000012644 if (getLangOpts().MSVCCompat) {
Francois Picheta3108062010-10-18 15:01:13 +000012645 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012646 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +000012647 } else
12648 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
Francois Picheta3108062010-10-18 15:01:13 +000012649 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012650 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012651 } else if (getLangOpts().CPlusPlus) {
Richard Smithf8379a02012-01-18 23:55:52 +000012652 // C++11 [dcl.enum]p5:
Douglas Gregor0bf31402010-10-08 23:50:27 +000012653 // If the underlying type is not fixed, the type of each enumerator
12654 // is the type of its initializing value:
12655 // - If an initializer is specified for an enumerator, the
12656 // initializing value has the same type as the expression.
12657 EltTy = Val->getType();
Eli Friedman2beed112012-02-07 04:34:38 +000012658 } else {
12659 // C99 6.7.2.2p2:
12660 // The expression that defines the value of an enumeration constant
12661 // shall be an integer constant expression that has a value
12662 // representable as an int.
12663
12664 // Complain if the value is not representable in an int.
12665 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12666 Diag(IdLoc, diag::ext_enum_value_not_int)
12667 << EnumVal.toString(10) << Val->getSourceRange()
12668 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12669 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12670 // Force the type of the expression to 'int'.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012671 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
Eli Friedman2beed112012-02-07 04:34:38 +000012672 }
12673 EltTy = Val->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +000012674 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012675 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012676 }
12677 }
Mike Stump11289f42009-09-09 15:08:12 +000012678
Douglas Gregor954f6b272009-03-17 19:05:46 +000012679 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +000012680 if (Enum->isDependentType())
12681 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012682 else if (!LastEnumConst) {
12683 // C++0x [dcl.enum]p5:
12684 // If the underlying type is not fixed, the type of each enumerator
12685 // is the type of its initializing value:
12686 // - If no initializer is specified for the first enumerator, the
12687 // initializing value has an unspecified integral type.
12688 //
12689 // GCC uses 'int' for its unspecified integral type, as does
12690 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +000012691 if (Enum->isFixed()) {
12692 EltTy = Enum->getIntegerType();
12693 }
12694 else {
12695 EltTy = Context.IntTy;
12696 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012697 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +000012698 // Assign the last value + 1.
12699 EnumVal = LastEnumConst->getInitVal();
12700 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012701 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +000012702
12703 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012704 if (EnumVal < LastEnumConst->getInitVal()) {
12705 // C++0x [dcl.enum]p5:
12706 // If the underlying type is not fixed, the type of each enumerator
12707 // is the type of its initializing value:
12708 //
12709 // - Otherwise the type of the initializing value is the same as
12710 // the type of the initializing value of the preceding enumerator
12711 // unless the incremented value is not representable in that type,
12712 // in which case the type is an unspecified integral type
12713 // sufficient to contain the incremented value. If no such type
12714 // exists, the program is ill-formed.
12715 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012716 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012717 // There is no integral type larger enough to represent this
12718 // value. Complain, then allow the value to wrap around.
12719 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +000012720 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +000012721 ++EnumVal;
12722 if (Enum->isFixed())
12723 // When the underlying type is fixed, this is ill-formed.
12724 Diag(IdLoc, diag::err_enumerator_wrapped)
12725 << EnumVal.toString(10)
12726 << EltTy;
12727 else
Richard Smithfaf156a2014-03-05 22:54:58 +000012728 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
Douglas Gregor0bf31402010-10-08 23:50:27 +000012729 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012730 } else {
12731 EltTy = T;
12732 }
12733
12734 // Retrieve the last enumerator's value, extent that type to the
12735 // type that is supposed to be large enough to represent the incremented
12736 // value, then increment.
12737 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012738 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +000012739 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012740 ++EnumVal;
12741
12742 // If we're not in C++, diagnose the overflow of enumerator values,
12743 // which in C99 means that the enumerator value is not representable in
12744 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12745 // permits enumerator values that are representable in some larger
12746 // integral type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012747 if (!getLangOpts().CPlusPlus && !T.isNull())
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012748 Diag(IdLoc, diag::warn_enum_value_overflow);
David Blaikiebbafb8a2012-03-11 07:00:24 +000012749 } else if (!getLangOpts().CPlusPlus &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012750 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12751 // Enforce C99 6.7.2.2p2 even when we compute the next value.
12752 Diag(IdLoc, diag::ext_enum_value_not_int)
12753 << EnumVal.toString(10) << 1;
12754 }
Douglas Gregor954f6b272009-03-17 19:05:46 +000012755 }
12756 }
Mike Stump11289f42009-09-09 15:08:12 +000012757
Douglas Gregordc70c3a2010-03-02 17:53:14 +000012758 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012759 // Make the enumerator value match the signedness and size of the
12760 // enumerator's type.
Eli Friedman2beed112012-02-07 04:34:38 +000012761 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000012762 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +000012763 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +000012764
Douglas Gregor954f6b272009-03-17 19:05:46 +000012765 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +000012766 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +000012767}
12768
12769
John McCall811a0f52010-10-22 23:36:17 +000012770Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12771 SourceLocation IdLoc, IdentifierInfo *Id,
12772 AttributeList *Attr,
Richard Smithf8379a02012-01-18 23:55:52 +000012773 SourceLocation EqualLoc, Expr *Val) {
John McCall48871652010-08-21 09:40:31 +000012774 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +000012775 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +000012776 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +000012777
Chris Lattner1a76a3c2007-08-26 06:24:45 +000012778 // The scope passed in may not be a decl scope. Zip up the scope tree until
12779 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +000012780 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +000012781
Chris Lattner8116d1b2007-01-25 22:38:29 +000012782 // Verify that there isn't already something declared with this name in this
12783 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012784 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +000012785 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +000012786 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +000012787 // Maybe we will complain about the shadowed template parameter.
12788 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12789 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012790 PrevDecl = nullptr;
Douglas Gregor5101c242008-12-05 18:15:24 +000012791 }
12792
12793 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012794 // When in C++, we may get a TagDecl with the same name; in this case the
12795 // enum constant will 'hide' the tag.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012796 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +000012797 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +000012798 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +000012799 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012800 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012801 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +000012802 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +000012803 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +000012804 return nullptr;
Chris Lattner8116d1b2007-01-25 22:38:29 +000012805 }
12806 }
Chris Lattner4ef40012007-06-11 01:28:17 +000012807
Aaron Ballman24a10472012-07-19 03:12:23 +000012808 // C++ [class.mem]p15:
12809 // If T is the name of a class, then each of the following shall have a name
12810 // different from T:
12811 // - every enumerator of every member of class T that is an unscoped
12812 // enumerated type
Douglas Gregor36c22a22010-10-15 13:21:21 +000012813 if (CXXRecordDecl *Record
12814 = dyn_cast<CXXRecordDecl>(
12815 TheEnumDecl->getDeclContext()->getRedeclContext()))
Aaron Ballman24a10472012-07-19 03:12:23 +000012816 if (!TheEnumDecl->isScoped() &&
12817 Record->getIdentifier() && Record->getIdentifier() == Id)
Douglas Gregor36c22a22010-10-15 13:21:21 +000012818 Diag(IdLoc, diag::err_member_name_of_class) << Id;
12819
John McCall811a0f52010-10-22 23:36:17 +000012820 EnumConstantDecl *New =
12821 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +000012822
John McCall553c0792010-01-23 00:46:32 +000012823 if (New) {
John McCall811a0f52010-10-22 23:36:17 +000012824 // Process attributes.
12825 if (Attr) ProcessDeclAttributeList(S, New, Attr);
12826
12827 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +000012828 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +000012829 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +000012830 }
Douglas Gregor2f521192008-12-17 02:04:30 +000012831
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000012832 ActOnDocumentableDecl(New);
12833
John McCall48871652010-08-21 09:40:31 +000012834 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +000012835}
12836
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012837// Returns true when the enum initial expression does not trigger the
12838// duplicate enum warning. A few common cases are exempted as follows:
12839// Element2 = Element1
12840// Element2 = Element1 + 1
12841// Element2 = Element1 - 1
12842// Where Element2 and Element1 are from the same enum.
12843static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12844 Expr *InitExpr = ECD->getInitExpr();
12845 if (!InitExpr)
12846 return true;
12847 InitExpr = InitExpr->IgnoreImpCasts();
12848
12849 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12850 if (!BO->isAdditiveOp())
12851 return true;
12852 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12853 if (!IL)
12854 return true;
12855 if (IL->getValue() != 1)
12856 return true;
12857
12858 InitExpr = BO->getLHS();
12859 }
12860
12861 // This checks if the elements are from the same enum.
12862 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12863 if (!DRE)
12864 return true;
12865
12866 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12867 if (!EnumConstant)
12868 return true;
12869
12870 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12871 Enum)
12872 return true;
12873
12874 return false;
12875}
12876
12877struct DupKey {
12878 int64_t val;
12879 bool isTombstoneOrEmptyKey;
12880 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12881 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12882};
12883
12884static DupKey GetDupKey(const llvm::APSInt& Val) {
12885 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12886 false);
12887}
12888
12889struct DenseMapInfoDupKey {
12890 static DupKey getEmptyKey() { return DupKey(0, true); }
12891 static DupKey getTombstoneKey() { return DupKey(1, true); }
12892 static unsigned getHashValue(const DupKey Key) {
12893 return (unsigned)(Key.val * 37);
12894 }
12895 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12896 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12897 LHS.val == RHS.val;
12898 }
12899};
12900
12901// Emits a warning when an element is implicitly set a value that
12902// a previous element has already been set to.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012903static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12904 EnumDecl *Enum,
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012905 QualType EnumType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012906 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012907 return;
12908 // Avoid anonymous enums
12909 if (!Enum->getIdentifier())
12910 return;
12911
12912 // Only check for small enums.
12913 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12914 return;
12915
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012916 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12917 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012918
12919 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12920 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12921 ValueToVectorMap;
12922
12923 DuplicatesVector DupVector;
12924 ValueToVectorMap EnumMap;
12925
12926 // Populate the EnumMap with all values represented by enum constants without
12927 // an initialier.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012928 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Benjamin Kramer5c488ef2013-04-07 14:10:40 +000012929 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012930
12931 // Null EnumConstantDecl means a previous diagnostic has been emitted for
12932 // this constant. Skip this enum since it may be ill-formed.
12933 if (!ECD) {
12934 return;
12935 }
12936
12937 if (ECD->getInitExpr())
12938 continue;
12939
12940 DupKey Key = GetDupKey(ECD->getInitVal());
12941 DeclOrVector &Entry = EnumMap[Key];
12942
12943 // First time encountering this value.
12944 if (Entry.isNull())
12945 Entry = ECD;
12946 }
12947
12948 // Create vectors for any values that has duplicates.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000012949 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Ted Kremenek6cae9ec2012-12-22 01:34:09 +000012950 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12951 if (!ValidDuplicateEnum(ECD, Enum))
12952 continue;
12953
12954 DupKey Key = GetDupKey(ECD->getInitVal());
12955
12956 DeclOrVector& Entry = EnumMap[Key];
12957 if (Entry.isNull())
12958 continue;
12959
12960 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12961 // Ensure constants are different.
12962 if (D == ECD)
12963 continue;
12964
12965 // Create new vector and push values onto it.
12966 ECDVector *Vec = new ECDVector();
12967 Vec->push_back(D);
12968 Vec->push_back(ECD);
12969
12970 // Update entry to point to the duplicates vector.
12971 Entry = Vec;
12972
12973 // Store the vector somewhere we can consult later for quick emission of
12974 // diagnostics.
12975 DupVector.push_back(Vec);
12976 continue;
12977 }
12978
12979 ECDVector *Vec = Entry.get<ECDVector*>();
12980 // Make sure constants are not added more than once.
12981 if (*Vec->begin() == ECD)
12982 continue;
12983
12984 Vec->push_back(ECD);
12985 }
12986
12987 // Emit diagnostics.
12988 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12989 DupVectorEnd = DupVector.end();
12990 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12991 ECDVector *Vec = *DupVectorIter;
12992 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12993
12994 // Emit warning for one enum constant.
12995 ECDVector::iterator I = Vec->begin();
12996 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12997 << (*I)->getName() << (*I)->getInitVal().toString(10)
12998 << (*I)->getSourceRange();
12999 ++I;
13000
13001 // Emit one note for each of the remaining enum constants with
13002 // the same value.
13003 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13004 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13005 << (*I)->getName() << (*I)->getInitVal().toString(10)
13006 << (*I)->getSourceRange();
13007 delete Vec;
13008 }
13009}
13010
Mike Stump6814d1c2009-05-16 07:06:02 +000013011void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +000013012 SourceLocation RBraceLoc, Decl *EnumDeclX,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013013 ArrayRef<Decl *> Elements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013014 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +000013015 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +000013016 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013017
13018 if (Attr)
13019 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +000013020
Eli Friedmand0e60972009-12-11 01:34:50 +000013021 if (Enum->isDependentType()) {
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013022 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Eli Friedmand0e60972009-12-11 01:34:50 +000013023 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000013024 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +000013025 if (!ECD) continue;
13026
13027 ECD->setType(EnumType);
13028 }
13029
John McCall9aa35be2010-05-06 08:49:23 +000013030 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +000013031 return;
13032 }
13033
Chris Lattner67933c02007-08-28 05:10:31 +000013034 // TODO: If the result value doesn't fit in an int, it must be a long or long
13035 // long value. ISO C does not support this, but GCC does as an extension,
13036 // emit a warning.
Douglas Gregore8bbc122011-09-02 00:18:52 +000013037 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13038 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13039 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013040
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013041 // Verify that all the values are okay, compute the size of the values, and
13042 // reverse the list.
13043 unsigned NumNegativeBits = 0;
13044 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +000013045
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013046 // Keep track of whether all elements have type int.
13047 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +000013048
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013049 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Chris Lattnerc1915e22007-01-25 07:29:02 +000013050 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +000013051 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013052 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +000013053
Chris Lattnerbf478cb2007-08-28 05:27:00 +000013054 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +000013055
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013056 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +000013057 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +000013058 NumPositiveBits = std::max(NumPositiveBits,
13059 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013060 else
Chris Lattner49f980c2008-01-14 21:47:29 +000013061 NumNegativeBits = std::max(NumNegativeBits,
13062 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +000013063
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013064 // Keep track of whether every enum element has type int (very commmon).
13065 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +000013066 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +000013067 }
Mike Stump11289f42009-09-09 15:08:12 +000013068
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013069 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013070 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013071 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013072
John McCall56774992009-12-09 09:09:27 +000013073 // C++0x N3000 [conv.prom]p3:
13074 // An rvalue of an unscoped enumeration type whose underlying
13075 // type is not fixed can be converted to an rvalue of the first
13076 // of the following types that can represent all the values of
13077 // the enumeration: int, unsigned int, long int, unsigned long
13078 // int, long long int, or unsigned long long int.
13079 // C99 6.4.4.3p2:
13080 // An identifier declared as an enumeration constant has type int.
13081 // The C99 rule is modified by a gcc extension
13082 QualType BestPromotionType;
13083
Aaron Ballman9ead1242013-12-19 02:39:40 +000013084 bool Packed = Enum->hasAttr<PackedAttr>();
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +000013085 // -fshort-enums is the equivalent to specifying the packed attribute on all
13086 // enum definitions.
13087 if (LangOpts.ShortEnums)
13088 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013089
Douglas Gregor0bf31402010-10-08 23:50:27 +000013090 if (Enum->isFixed()) {
Eli Friedman64d95042011-10-26 07:38:19 +000013091 BestType = Enum->getIntegerType();
13092 if (BestType->isPromotableIntegerType())
13093 BestPromotionType = Context.getPromotedIntegerType(BestType);
13094 else
13095 BestPromotionType = BestType;
Duncan Sands38b918c2010-10-12 14:07:59 +000013096 // We don't need to set BestWidth, because BestType is going to be the type
13097 // of the enumerators, but we do anyway because otherwise some compilers
13098 // warn that it might be used uninitialized.
13099 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +000013100 }
13101 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +000013102 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013103 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013104 // If it's packed, check also if it fits a char or a short.
13105 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013106 BestType = Context.SignedCharTy;
13107 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +000013108 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013109 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013110 BestType = Context.ShortTy;
13111 BestWidth = ShortWidth;
13112 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013113 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013114 BestWidth = IntWidth;
13115 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013116 BestWidth = Context.getTargetInfo().getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013117
John McCall56774992009-12-09 09:09:27 +000013118 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013119 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +000013120 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013121 BestWidth = Context.getTargetInfo().getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +000013122
Chris Lattner3a370bf2007-08-29 17:31:48 +000013123 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Richard Smithfaf156a2014-03-05 22:54:58 +000013124 Diag(Enum->getLocation(), diag::ext_enum_too_large);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013125 BestType = Context.LongLongTy;
13126 }
13127 }
John McCall56774992009-12-09 09:09:27 +000013128 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013129 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +000013130 // If there is no negative value, figure out the smallest type that fits
13131 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013132 // If it's packed, check also if it fits a char or a short.
13133 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +000013134 BestType = Context.UnsignedCharTy;
13135 BestPromotionType = Context.IntTy;
13136 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +000013137 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +000013138 BestType = Context.UnsignedShortTy;
13139 BestPromotionType = Context.IntTy;
13140 BestWidth = ShortWidth;
13141 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013142 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013143 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +000013144 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013145 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013146 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +000013147 } else if (NumPositiveBits <=
Douglas Gregore8bbc122011-09-02 00:18:52 +000013148 (BestWidth = Context.getTargetInfo().getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013149 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013150 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013151 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013152 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +000013153 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +000013154 BestWidth = Context.getTargetInfo().getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013155 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013156 "How could an initializer get larger than ULL?");
13157 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +000013158 BestPromotionType
David Blaikiebbafb8a2012-03-11 07:00:24 +000013159 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
Douglas Gregora71cc152010-02-02 20:10:50 +000013160 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +000013161 }
13162 }
Mike Stump11289f42009-09-09 15:08:12 +000013163
Chris Lattner3a370bf2007-08-29 17:31:48 +000013164 // Loop over all of the enumerator constants, changing their types to match
13165 // the type of the enum if needed.
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013166 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +000013167 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013168 if (!ECD) continue; // Already issued a diagnostic.
13169
13170 // Standard C says the enumerators have int type, but we allow, as an
13171 // extension, the enumerators to be larger than int size. If each
13172 // enumerator value fits in an int, type it as an int, otherwise type it the
13173 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
13174 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +000013175
13176 // Determine whether the value fits into an int.
13177 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013178
13179 // If it fits into an integer type, force it. Otherwise force it to match
13180 // the enum decl type.
13181 QualType NewTy;
13182 unsigned NewWidth;
13183 bool NewSign;
David Blaikiebbafb8a2012-03-11 07:00:24 +000013184 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian37c64172011-11-04 18:51:24 +000013185 !Enum->isFixed() &&
Douglas Gregor6791a0d2010-02-01 23:36:03 +000013186 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +000013187 NewTy = Context.IntTy;
13188 NewWidth = IntWidth;
13189 NewSign = true;
13190 } else if (ECD->getType() == BestType) {
13191 // Already the right type!
David Blaikiebbafb8a2012-03-11 07:00:24 +000013192 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013193 // C++ [dcl.enum]p4: Following the closing brace of an
13194 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013195 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013196 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013197 continue;
13198 } else {
13199 NewTy = BestType;
13200 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +000013201 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +000013202 }
13203
13204 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +000013205 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013206 InitVal.setIsSigned(NewSign);
13207 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +000013208
Chris Lattner3a370bf2007-08-29 17:31:48 +000013209 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +000013210 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +000013211 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +000013212 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +000013213 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +000013214 ECD->getInitExpr(),
Craig Topperc3ec1492014-05-26 06:22:03 +000013215 /*base paths*/ nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000013216 VK_RValue));
David Blaikiebbafb8a2012-03-11 07:00:24 +000013217 if (getLangOpts().CPlusPlus)
Douglas Gregor1d248c52008-12-12 02:00:36 +000013218 // C++ [dcl.enum]p4: Following the closing brace of an
13219 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +000013220 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +000013221 ECD->setType(EnumType);
13222 else
13223 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +000013224 }
Mike Stump11289f42009-09-09 15:08:12 +000013225
John McCall9aa35be2010-05-06 08:49:23 +000013226 Enum->completeDefinition(BestType, BestPromotionType,
13227 NumPositiveBits, NumNegativeBits);
James Molloy6f8780b2012-02-29 10:24:19 +000013228
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +000013229 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
Richard Smith848e1f12013-02-01 08:12:08 +000013230
13231 // Now that the enum type is defined, ensure it's not been underaligned.
13232 if (Enum->hasAttrs())
13233 CheckAlignasUnderalignment(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +000013234}
Chris Lattner1300fb92007-01-23 23:42:53 +000013235
Abramo Bagnara348823a2011-03-03 14:20:18 +000013236Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13237 SourceLocation StartLoc,
13238 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +000013239 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +000013240
Douglas Gregor278f52e2009-05-30 00:08:05 +000013241 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +000013242 AsmString, StartLoc,
13243 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013244 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +000013245 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +000013246}
Eli Friedman5ed51982009-06-05 02:44:36 +000013247
Richard Smith77944862014-03-02 05:58:18 +000013248static void checkModuleImportContext(Sema &S, Module *M,
13249 SourceLocation ImportLoc,
13250 DeclContext *DC) {
13251 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13252 switch (LSD->getLanguage()) {
13253 case LinkageSpecDecl::lang_c:
13254 if (!M->IsExternC) {
13255 S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13256 << M->getFullModuleName();
13257 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13258 return;
13259 }
13260 break;
13261 case LinkageSpecDecl::lang_cxx:
13262 break;
13263 }
13264 DC = LSD->getParent();
13265 }
13266
13267 while (isa<LinkageSpecDecl>(DC))
13268 DC = DC->getParent();
13269 if (!isa<TranslationUnitDecl>(DC)) {
13270 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13271 << M->getFullModuleName() << DC;
13272 S.Diag(cast<Decl>(DC)->getLocStart(),
13273 diag::note_module_import_not_at_top_level)
13274 << DC;
13275 }
13276}
13277
Douglas Gregor22d09742012-01-03 18:04:46 +000013278DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13279 SourceLocation ImportLoc,
13280 ModuleIdPath Path) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000013281 Module *Mod =
13282 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13283 /*IsIncludeDirective=*/false);
Douglas Gregorde3ef502011-11-30 23:21:26 +000013284 if (!Mod)
Douglas Gregor08142532011-08-26 23:56:07 +000013285 return true;
Richard Smith77944862014-03-02 05:58:18 +000013286
13287 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13288
Ben Langmuir527040e2014-05-05 05:31:33 +000013289 // FIXME: we should support importing a submodule within a different submodule
13290 // of the same top-level module. Until we do, make it an error rather than
13291 // silently ignoring the import.
13292 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13293 Diag(ImportLoc, diag::err_module_self_import)
13294 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13295
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013296 SmallVector<SourceLocation, 2> IdentifierLocs;
Douglas Gregorba345522011-12-02 23:23:56 +000013297 Module *ModCheck = Mod;
13298 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13299 // If we've run out of module parents, just drop the remaining identifiers.
13300 // We need the length to be consistent.
13301 if (!ModCheck)
13302 break;
13303 ModCheck = ModCheck->Parent;
13304
13305 IdentifierLocs.push_back(Path[I].second);
13306 }
13307
13308 ImportDecl *Import = ImportDecl::Create(Context,
13309 Context.getTranslationUnitDecl(),
Douglas Gregor22d09742012-01-03 18:04:46 +000013310 AtLoc.isValid()? AtLoc : ImportLoc,
13311 Mod, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +000013312 Context.getTranslationUnitDecl()->addDecl(Import);
13313 return Import;
Douglas Gregor08142532011-08-26 23:56:07 +000013314}
13315
Richard Smithce587f52013-11-15 04:24:58 +000013316void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
Richard Smith77944862014-03-02 05:58:18 +000013317 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13318
Richard Smithce587f52013-11-15 04:24:58 +000013319 // FIXME: Should we synthesize an ImportDecl here?
Alp Tokerb6cc5922014-05-03 03:45:55 +000013320 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13321 /*Complain=*/true);
Richard Smithce587f52013-11-15 04:24:58 +000013322}
13323
Richard Smith3d23c422014-05-07 02:25:43 +000013324void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13325 Module *Mod) {
13326 // Bail if we're not allowed to implicitly import a module here.
13327 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13328 return;
13329
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013330 // Create the implicit import declaration.
13331 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13332 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13333 Loc, Mod, Loc);
13334 TU->addDecl(ImportD);
13335 Consumer.HandleImplicitImportDecl(ImportD);
13336
13337 // Make the module visible.
Alp Tokerb6cc5922014-05-03 03:45:55 +000013338 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13339 /*Complain=*/false);
Douglas Gregorc147b0b2013-01-12 01:29:50 +000013340}
13341
David Chisnall0867d9c2012-02-18 16:12:34 +000013342void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13343 IdentifierInfo* AliasName,
13344 SourceLocation PragmaLoc,
13345 SourceLocation NameLoc,
13346 SourceLocation AliasNameLoc) {
13347 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13348 LookupOrdinaryName);
Aaron Ballman36a53502014-01-16 13:03:14 +000013349 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13350 AliasName->getName(), 0);
David Chisnall0867d9c2012-02-18 16:12:34 +000013351
13352 if (PrevDecl)
13353 PrevDecl->addAttr(Attr);
13354 else
13355 (void)ExtnameUndeclaredIdentifiers.insert(
13356 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13357}
13358
Eli Friedman5ed51982009-06-05 02:44:36 +000013359void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13360 SourceLocation PragmaLoc,
13361 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013362 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +000013363
Eli Friedman5ed51982009-06-05 02:44:36 +000013364 if (PrevDecl) {
Aaron Ballman36a53502014-01-16 13:03:14 +000013365 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
Ryan Flynn7d470f32009-07-30 03:15:39 +000013366 } else {
13367 (void)WeakUndeclaredIdentifiers.insert(
13368 std::pair<IdentifierInfo*,WeakInfo>
Craig Topperc3ec1492014-05-26 06:22:03 +000013369 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +000013370 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013371}
13372
13373void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13374 IdentifierInfo* AliasName,
13375 SourceLocation PragmaLoc,
13376 SourceLocation NameLoc,
13377 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013378 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13379 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013380 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +000013381
Eli Friedman5ed51982009-06-05 02:44:36 +000013382 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +000013383 if (!PrevDecl->hasAttr<AliasAttr>())
13384 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +000013385 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +000013386 } else {
13387 (void)WeakUndeclaredIdentifiers.insert(
13388 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +000013389 }
Eli Friedman5ed51982009-06-05 02:44:36 +000013390}
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000013391
13392Decl *Sema::getObjCDeclContext() const {
13393 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13394}
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013395
13396AvailabilityResult Sema::getCurContextAvailability() const {
Fariborz Jahanian979780f2012-09-06 18:38:58 +000013397 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
Ted Kremenekcb42dbe2013-11-20 17:24:03 +000013398 // If we are within an Objective-C method, we should consult
13399 // both the availability of the method as well as the
13400 // enclosing class. If the class is (say) deprecated,
13401 // the entire method is considered deprecated from the
13402 // purpose of checking if the current context is deprecated.
13403 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13404 AvailabilityResult R = MD->getAvailability();
13405 if (R != AR_Available)
13406 return R;
13407 D = MD->getClassInterface();
13408 }
13409 // If we are within an Objective-c @implementation, it
13410 // gets the same availability context as the @interface.
13411 else if (const ObjCImplementationDecl *ID =
13412 dyn_cast<ObjCImplementationDecl>(D)) {
13413 D = ID->getClassInterface();
13414 }
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +000013415 return D->getAvailability();
13416}