1193326Sed//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements semantic analysis for declarations.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14212904Sdim#include "clang/Sema/SemaInternal.h"
15221345Sdim#include "TypeLocBuilder.h"
16193326Sed#include "clang/AST/ASTConsumer.h"
17193326Sed#include "clang/AST/ASTContext.h"
18263508Sdim#include "clang/AST/ASTLambda.h"
19198092Srdivacky#include "clang/AST/CXXInheritance.h"
20249423Sdim#include "clang/AST/CharUnits.h"
21239462Sdim#include "clang/AST/CommentDiagnostic.h"
22212904Sdim#include "clang/AST/DeclCXX.h"
23212904Sdim#include "clang/AST/DeclObjC.h"
24193326Sed#include "clang/AST/DeclTemplate.h"
25221345Sdim#include "clang/AST/EvaluatedExprVisitor.h"
26193326Sed#include "clang/AST/ExprCXX.h"
27193326Sed#include "clang/AST/StmtCXX.h"
28198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
29198092Srdivacky#include "clang/Basic/SourceManager.h"
30193326Sed#include "clang/Basic/TargetInfo.h"
31249423Sdim#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32249423Sdim#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33249423Sdim#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34249423Sdim#include "clang/Parse/ParseDiagnostic.h"
35249423Sdim#include "clang/Sema/CXXFieldCollector.h"
36249423Sdim#include "clang/Sema/DeclSpec.h"
37249423Sdim#include "clang/Sema/DelayedDiagnostic.h"
38249423Sdim#include "clang/Sema/Initialization.h"
39249423Sdim#include "clang/Sema/Lookup.h"
40249423Sdim#include "clang/Sema/ParsedTemplate.h"
41249423Sdim#include "clang/Sema/Scope.h"
42249423Sdim#include "clang/Sema/ScopeInfo.h"
43263508Sdim#include "clang/Sema/Template.h"
44234353Sdim#include "llvm/ADT/SmallString.h"
45201361Srdivacky#include "llvm/ADT/Triple.h"
46193326Sed#include <algorithm>
47198092Srdivacky#include <cstring>
48193326Sed#include <functional>
49193326Sedusing namespace clang;
50212904Sdimusing namespace sema;
51193326Sed
52224145SdimSema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53224145Sdim  if (OwnedType) {
54224145Sdim    Decl *Group[2] = { OwnedType, Ptr };
55224145Sdim    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56224145Sdim  }
57224145Sdim
58212904Sdim  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
59193326Sed}
60193326Sed
61234353Sdimnamespace {
62234353Sdim
63234353Sdimclass TypeNameValidatorCCC : public CorrectionCandidateCallback {
64234353Sdim public:
65239462Sdim  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66239462Sdim      : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
67234353Sdim    WantExpressionKeywords = false;
68234353Sdim    WantCXXNamedCasts = false;
69234353Sdim    WantRemainingKeywords = false;
70234353Sdim  }
71234353Sdim
72234353Sdim  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
73234353Sdim    if (NamedDecl *ND = candidate.getCorrectionDecl())
74234353Sdim      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
75234353Sdim          (AllowInvalidDecl || !ND->isInvalidDecl());
76234353Sdim    else
77239462Sdim      return !WantClassName && candidate.isKeyword();
78234353Sdim  }
79234353Sdim
80234353Sdim private:
81234353Sdim  bool AllowInvalidDecl;
82239462Sdim  bool WantClassName;
83234353Sdim};
84234353Sdim
85234353Sdim}
86234353Sdim
87239462Sdim/// \brief Determine whether the token kind starts a simple-type-specifier.
88239462Sdimbool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
89239462Sdim  switch (Kind) {
90239462Sdim  // FIXME: Take into account the current language when deciding whether a
91239462Sdim  // token kind is a valid type specifier
92239462Sdim  case tok::kw_short:
93239462Sdim  case tok::kw_long:
94239462Sdim  case tok::kw___int64:
95239462Sdim  case tok::kw___int128:
96239462Sdim  case tok::kw_signed:
97239462Sdim  case tok::kw_unsigned:
98239462Sdim  case tok::kw_void:
99239462Sdim  case tok::kw_char:
100239462Sdim  case tok::kw_int:
101239462Sdim  case tok::kw_half:
102239462Sdim  case tok::kw_float:
103239462Sdim  case tok::kw_double:
104239462Sdim  case tok::kw_wchar_t:
105239462Sdim  case tok::kw_bool:
106239462Sdim  case tok::kw___underlying_type:
107239462Sdim    return true;
108239462Sdim
109239462Sdim  case tok::annot_typename:
110239462Sdim  case tok::kw_char16_t:
111239462Sdim  case tok::kw_char32_t:
112239462Sdim  case tok::kw_typeof:
113263508Sdim  case tok::annot_decltype:
114239462Sdim  case tok::kw_decltype:
115239462Sdim    return getLangOpts().CPlusPlus;
116239462Sdim
117239462Sdim  default:
118239462Sdim    break;
119239462Sdim  }
120239462Sdim
121239462Sdim  return false;
122239462Sdim}
123239462Sdim
124193326Sed/// \brief If the identifier refers to a type name within this scope,
125193326Sed/// return the declaration of that type.
126193326Sed///
127193326Sed/// This routine performs ordinary name lookup of the identifier II
128193326Sed/// within the given scope, with optional C++ scope specifier SS, to
129193326Sed/// determine whether the name refers to a type. If so, returns an
130193326Sed/// opaque pointer (actually a QualType) corresponding to that
131193326Sed/// type. Otherwise, returns NULL.
132251662SdimParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
133212904Sdim                             Scope *S, CXXScopeSpec *SS,
134218893Sdim                             bool isClassName, bool HasTrailingDot,
135221345Sdim                             ParsedType ObjectTypePtr,
136234353Sdim                             bool IsCtorOrDtorName,
137226633Sdim                             bool WantNontrivialTypeSourceInfo,
138226633Sdim                             IdentifierInfo **CorrectedII) {
139199990Srdivacky  // Determine where we will perform name lookup.
140199990Srdivacky  DeclContext *LookupCtx = 0;
141199990Srdivacky  if (ObjectTypePtr) {
142212904Sdim    QualType ObjectType = ObjectTypePtr.get();
143199990Srdivacky    if (ObjectType->isRecordType())
144199990Srdivacky      LookupCtx = computeDeclContext(ObjectType);
145207619Srdivacky  } else if (SS && SS->isNotEmpty()) {
146199990Srdivacky    LookupCtx = computeDeclContext(*SS, false);
147199990Srdivacky
148199990Srdivacky    if (!LookupCtx) {
149199990Srdivacky      if (isDependentScopeSpecifier(*SS)) {
150199990Srdivacky        // C++ [temp.res]p3:
151199990Srdivacky        //   A qualified-id that refers to a type and in which the
152199990Srdivacky        //   nested-name-specifier depends on a template-parameter (14.6.2)
153199990Srdivacky        //   shall be prefixed by the keyword typename to indicate that the
154199990Srdivacky        //   qualified-id denotes a type, forming an
155199990Srdivacky        //   elaborated-type-specifier (7.1.5.3).
156199990Srdivacky        //
157199990Srdivacky        // We therefore do not perform any name lookup if the result would
158199990Srdivacky        // refer to a member of an unknown specialization.
159234353Sdim        if (!isClassName && !IsCtorOrDtorName)
160212904Sdim          return ParsedType();
161199990Srdivacky
162210299Sed        // We know from the grammar that this name refers to a type,
163210299Sed        // so build a dependent node to describe the type.
164221345Sdim        if (WantNontrivialTypeSourceInfo)
165221345Sdim          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166221345Sdim
167221345Sdim        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168212904Sdim        QualType T =
169221345Sdim          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170221345Sdim                            II, NameLoc);
171221345Sdim
172221345Sdim          return ParsedType::make(T);
173199990Srdivacky      }
174199990Srdivacky
175212904Sdim      return ParsedType();
176199990Srdivacky    }
177199990Srdivacky
178207619Srdivacky    if (!LookupCtx->isDependentContext() &&
179207619Srdivacky        RequireCompleteDeclContext(*SS, LookupCtx))
180212904Sdim      return ParsedType();
181198092Srdivacky  }
182201361Srdivacky
183201361Srdivacky  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184201361Srdivacky  // lookup for class-names.
185201361Srdivacky  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186201361Srdivacky                                      LookupOrdinaryName;
187201361Srdivacky  LookupResult Result(*this, &II, NameLoc, Kind);
188199990Srdivacky  if (LookupCtx) {
189199990Srdivacky    // Perform "qualified" name lookup into the declaration context we
190199990Srdivacky    // computed, which is either the type of the base of a member access
191199990Srdivacky    // expression or the declaration context associated with a prior
192199990Srdivacky    // nested-name-specifier.
193199990Srdivacky    LookupQualifiedName(Result, LookupCtx);
194198092Srdivacky
195199990Srdivacky    if (ObjectTypePtr && Result.empty()) {
196199990Srdivacky      // C++ [basic.lookup.classref]p3:
197199990Srdivacky      //   If the unqualified-id is ~type-name, the type-name is looked up
198199990Srdivacky      //   in the context of the entire postfix-expression. If the type T of
199199990Srdivacky      //   the object expression is of a class type C, the type-name is also
200199990Srdivacky      //   looked up in the scope of class C. At least one of the lookups shall
201199990Srdivacky      //   find a name that refers to (possibly cv-qualified) T.
202199990Srdivacky      LookupName(Result, S);
203199990Srdivacky    }
204199990Srdivacky  } else {
205199990Srdivacky    // Perform unqualified name lookup.
206199990Srdivacky    LookupName(Result, S);
207199990Srdivacky  }
208199990Srdivacky
209193326Sed  NamedDecl *IIDecl = 0;
210199482Srdivacky  switch (Result.getResultKind()) {
211193326Sed  case LookupResult::NotFound:
212202379Srdivacky  case LookupResult::NotFoundInCurrentInstantiation:
213226633Sdim    if (CorrectedII) {
214239462Sdim      TypeNameValidatorCCC Validator(true, isClassName);
215226633Sdim      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216234353Sdim                                              Kind, S, SS, Validator);
217226633Sdim      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218226633Sdim      TemplateTy Template;
219226633Sdim      bool MemberOfUnknownSpecialization;
220226633Sdim      UnqualifiedId TemplateName;
221226633Sdim      TemplateName.setIdentifier(NewII, NameLoc);
222226633Sdim      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223226633Sdim      CXXScopeSpec NewSS, *NewSSPtr = SS;
224226633Sdim      if (SS && NNS) {
225226633Sdim        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226226633Sdim        NewSSPtr = &NewSS;
227226633Sdim      }
228226633Sdim      if (Correction && (NNS || NewII != &II) &&
229226633Sdim          // Ignore a correction to a template type as the to-be-corrected
230226633Sdim          // identifier is not a template (typo correction for template names
231226633Sdim          // is handled elsewhere).
232234353Sdim          !(getLangOpts().CPlusPlus && NewSSPtr &&
233226633Sdim            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234226633Sdim                           false, Template, MemberOfUnknownSpecialization))) {
235226633Sdim        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236226633Sdim                                    isClassName, HasTrailingDot, ObjectTypePtr,
237234353Sdim                                    IsCtorOrDtorName,
238226633Sdim                                    WantNontrivialTypeSourceInfo);
239226633Sdim        if (Ty) {
240263508Sdim          diagnoseTypo(Correction,
241263508Sdim                       PDiag(diag::err_unknown_type_or_class_name_suggest)
242263508Sdim                         << Result.getLookupName() << isClassName);
243226633Sdim          if (SS && NNS)
244226633Sdim            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
245226633Sdim          *CorrectedII = NewII;
246226633Sdim          return Ty;
247226633Sdim        }
248226633Sdim      }
249226633Sdim    }
250226633Sdim    // If typo correction failed or was not performed, fall through
251193326Sed  case LookupResult::FoundOverloaded:
252199482Srdivacky  case LookupResult::FoundUnresolvedValue:
253203955Srdivacky    Result.suppressDiagnostics();
254212904Sdim    return ParsedType();
255193326Sed
256198893Srdivacky  case LookupResult::Ambiguous:
257198092Srdivacky    // Recover from type-hiding ambiguities by hiding the type.  We'll
258198092Srdivacky    // do the lookup again when looking for an object, and we can
259198092Srdivacky    // diagnose the error then.  If we don't do this, then the error
260198092Srdivacky    // about hiding the type will be immediately followed by an error
261198092Srdivacky    // that only makes sense if the identifier was treated like a type.
262199482Srdivacky    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263199482Srdivacky      Result.suppressDiagnostics();
264212904Sdim      return ParsedType();
265199482Srdivacky    }
266198092Srdivacky
267193326Sed    // Look to see if we have a type anywhere in the list of results.
268193326Sed    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
269193326Sed         Res != ResEnd; ++Res) {
270193326Sed      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
271198092Srdivacky        if (!IIDecl ||
272198092Srdivacky            (*Res)->getLocation().getRawEncoding() <
273193326Sed              IIDecl->getLocation().getRawEncoding())
274193326Sed          IIDecl = *Res;
275193326Sed      }
276193326Sed    }
277193326Sed
278193326Sed    if (!IIDecl) {
279193326Sed      // None of the entities we found is a type, so there is no way
280193326Sed      // to even assume that the result is a type. In this case, don't
281193326Sed      // complain about the ambiguity. The parser will either try to
282193326Sed      // perform this lookup again (e.g., as an object name), which
283193326Sed      // will produce the ambiguity, or will complain that it expected
284193326Sed      // a type name.
285199482Srdivacky      Result.suppressDiagnostics();
286212904Sdim      return ParsedType();
287193326Sed    }
288193326Sed
289193326Sed    // We found a type within the ambiguous lookup; diagnose the
290193326Sed    // ambiguity and then return that type. This might be the right
291193326Sed    // answer, or it might not be, but it suppresses any attempt to
292193326Sed    // perform the name lookup again.
293193326Sed    break;
294193326Sed
295193326Sed  case LookupResult::Found:
296198092Srdivacky    IIDecl = Result.getFoundDecl();
297193326Sed    break;
298193326Sed  }
299193326Sed
300198893Srdivacky  assert(IIDecl && "Didn't find decl");
301198092Srdivacky
302198893Srdivacky  QualType T;
303198893Srdivacky  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
304198893Srdivacky    DiagnoseUseOfDecl(IIDecl, NameLoc);
305199482Srdivacky
306198893Srdivacky    if (T.isNull())
307198893Srdivacky      T = Context.getTypeDeclType(TD);
308234353Sdim
309234353Sdim    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
310234353Sdim    // constructor or destructor name (in such a case, the scope specifier
311234353Sdim    // will be attached to the enclosing Expr or Decl node).
312234353Sdim    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
313221345Sdim      if (WantNontrivialTypeSourceInfo) {
314221345Sdim        // Construct a type with type-source information.
315221345Sdim        TypeLocBuilder Builder;
316221345Sdim        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
317221345Sdim
318221345Sdim        T = getElaboratedType(ETK_None, *SS, T);
319221345Sdim        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
320234353Sdim        ElabTL.setElaboratedKeywordLoc(SourceLocation());
321221345Sdim        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
322221345Sdim        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
323221345Sdim      } else {
324221345Sdim        T = getElaboratedType(ETK_None, *SS, T);
325221345Sdim      }
326221345Sdim    }
327198893Srdivacky  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
328221345Sdim    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
329218893Sdim    if (!HasTrailingDot)
330218893Sdim      T = Context.getObjCInterfaceType(IDecl);
331218893Sdim  }
332218893Sdim
333218893Sdim  if (T.isNull()) {
334199482Srdivacky    // If it's not plausibly a type, suppress diagnostics.
335199482Srdivacky    Result.suppressDiagnostics();
336212904Sdim    return ParsedType();
337199482Srdivacky  }
338212904Sdim  return ParsedType::make(T);
339193326Sed}
340193326Sed
341193326Sed/// isTagName() - This method is called *for error recovery purposes only*
342193326Sed/// to determine if the specified name is a valid tag name ("struct foo").  If
343193326Sed/// so, this returns the TST for the tag corresponding to it (TST_enum,
344243830Sdim/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
345243830Sdim/// cases in C where the user forgot to specify the tag.
346193326SedDeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347193326Sed  // Do a tag name lookup in this scope.
348199482Srdivacky  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
349199482Srdivacky  LookupName(R, S, false);
350199482Srdivacky  R.suppressDiagnostics();
351199482Srdivacky  if (R.getResultKind() == LookupResult::Found)
352200583Srdivacky    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
353193326Sed      switch (TD->getTagKind()) {
354208600Srdivacky      case TTK_Struct: return DeclSpec::TST_struct;
355243830Sdim      case TTK_Interface: return DeclSpec::TST_interface;
356208600Srdivacky      case TTK_Union:  return DeclSpec::TST_union;
357208600Srdivacky      case TTK_Class:  return DeclSpec::TST_class;
358208600Srdivacky      case TTK_Enum:   return DeclSpec::TST_enum;
359193326Sed      }
360193326Sed    }
361198092Srdivacky
362193326Sed  return DeclSpec::TST_unspecified;
363193326Sed}
364193326Sed
365221345Sdim/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
366221345Sdim/// if a CXXScopeSpec's type is equal to the type of one of the base classes
367221345Sdim/// then downgrade the missing typename error to a warning.
368221345Sdim/// This is needed for MSVC compatibility; Example:
369221345Sdim/// @code
370221345Sdim/// template<class T> class A {
371221345Sdim/// public:
372221345Sdim///   typedef int TYPE;
373221345Sdim/// };
374221345Sdim/// template<class T> class B : public A<T> {
375221345Sdim/// public:
376221345Sdim///   A<T>::TYPE a; // no typename required because A<T> is a base class.
377221345Sdim/// };
378221345Sdim/// @endcode
379226633Sdimbool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
380221345Sdim  if (CurContext->isRecord()) {
381221345Sdim    const Type *Ty = SS->getScopeRep()->getAsType();
382221345Sdim
383221345Sdim    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
384221345Sdim    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
385221345Sdim          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
386221345Sdim      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
387221345Sdim        return true;
388226633Sdim    return S->isFunctionPrototypeScope();
389221345Sdim  }
390226633Sdim  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
391221345Sdim}
392221345Sdim
393239462Sdimbool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
394198092Srdivacky                                   SourceLocation IILoc,
395198092Srdivacky                                   Scope *S,
396207619Srdivacky                                   CXXScopeSpec *SS,
397212904Sdim                                   ParsedType &SuggestedType) {
398198092Srdivacky  // We don't have anything to suggest (yet).
399212904Sdim  SuggestedType = ParsedType();
400198092Srdivacky
401201361Srdivacky  // There may have been a typo in the name of the type. Look up typo
402201361Srdivacky  // results, in case we have something that we can suggest.
403234353Sdim  TypeNameValidatorCCC Validator(false);
404239462Sdim  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
405234353Sdim                                             LookupOrdinaryName, S, SS,
406234353Sdim                                             Validator)) {
407224145Sdim    if (Corrected.isKeyword()) {
408224145Sdim      // We corrected to a keyword.
409263508Sdim      diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410263508Sdim      II = Corrected.getCorrectionAsIdentifierInfo();
411224145Sdim    } else {
412234353Sdim      // We found a similarly-named type or interface; suggest that.
413263508Sdim      if (!SS || !SS->isSet()) {
414263508Sdim        diagnoseTypo(Corrected,
415263508Sdim                     PDiag(diag::err_unknown_typename_suggest) << II);
416263508Sdim      } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
417263508Sdim        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418263508Sdim        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
419263508Sdim                                II->getName().equals(CorrectedStr);
420263508Sdim        diagnoseTypo(Corrected,
421263508Sdim                     PDiag(diag::err_unknown_nested_typename_suggest)
422263508Sdim                       << II << DC << DroppedSpecifier << SS->getRange());
423263508Sdim      } else {
424234353Sdim        llvm_unreachable("could not have corrected a typo here");
425263508Sdim      }
426201361Srdivacky
427263508Sdim      CXXScopeSpec tmpSS;
428263508Sdim      if (Corrected.getCorrectionSpecifier())
429263508Sdim        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430263508Sdim                          SourceRange(IILoc));
431263508Sdim      SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
432263508Sdim                                  IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433263508Sdim                                  false, ParsedType(),
434234353Sdim                                  /*IsCtorOrDtorName=*/false,
435234353Sdim                                  /*NonTrivialTypeSourceInfo=*/true);
436207619Srdivacky    }
437234353Sdim    return true;
438207619Srdivacky  }
439201361Srdivacky
440234353Sdim  if (getLangOpts().CPlusPlus) {
441207619Srdivacky    // See if II is a class template that the user forgot to pass arguments to.
442207619Srdivacky    UnqualifiedId Name;
443239462Sdim    Name.setIdentifier(II, IILoc);
444207619Srdivacky    CXXScopeSpec EmptySS;
445207619Srdivacky    TemplateTy TemplateResult;
446208600Srdivacky    bool MemberOfUnknownSpecialization;
447212904Sdim    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
448212904Sdim                       Name, ParsedType(), true, TemplateResult,
449208600Srdivacky                       MemberOfUnknownSpecialization) == TNK_Type_template) {
450263508Sdim      TemplateName TplName = TemplateResult.get();
451207619Srdivacky      Diag(IILoc, diag::err_template_missing_args) << TplName;
452207619Srdivacky      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
453207619Srdivacky        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
454207619Srdivacky          << TplDecl->getTemplateParameters()->getSourceRange();
455207619Srdivacky      }
456201361Srdivacky      return true;
457201361Srdivacky    }
458201361Srdivacky  }
459201361Srdivacky
460198092Srdivacky  // FIXME: Should we move the logic that tries to recover from a missing tag
461198092Srdivacky  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
462198092Srdivacky
463201361Srdivacky  if (!SS || (!SS->isSet() && !SS->isInvalid()))
464239462Sdim    Diag(IILoc, diag::err_unknown_typename) << II;
465198092Srdivacky  else if (DeclContext *DC = computeDeclContext(*SS, false))
466198092Srdivacky    Diag(IILoc, diag::err_typename_nested_not_found)
467239462Sdim      << II << DC << SS->getRange();
468198092Srdivacky  else if (isDependentScopeSpecifier(*SS)) {
469221345Sdim    unsigned DiagID = diag::err_typename_missing;
470234353Sdim    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
471221345Sdim      DiagID = diag::warn_typename_missing;
472221345Sdim
473221345Sdim    Diag(SS->getRange().getBegin(), DiagID)
474239462Sdim      << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
475198092Srdivacky      << SourceRange(SS->getRange().getBegin(), IILoc)
476206084Srdivacky      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
477239462Sdim    SuggestedType = ActOnTypenameType(S, SourceLocation(),
478239462Sdim                                      *SS, *II, IILoc).get();
479198092Srdivacky  } else {
480198092Srdivacky    assert(SS && SS->isInvalid() &&
481198092Srdivacky           "Invalid scope specifier has already been diagnosed");
482198092Srdivacky  }
483198092Srdivacky
484198092Srdivacky  return true;
485198092Srdivacky}
486193326Sed
487221345Sdim/// \brief Determine whether the given result set contains either a type name
488221345Sdim/// or
489221345Sdimstatic bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
490234353Sdim  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
491221345Sdim                       NextToken.is(tok::less);
492221345Sdim
493221345Sdim  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
494221345Sdim    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
495221345Sdim      return true;
496221345Sdim
497221345Sdim    if (CheckTemplate && isa<TemplateDecl>(*I))
498221345Sdim      return true;
499221345Sdim  }
500221345Sdim
501221345Sdim  return false;
502221345Sdim}
503221345Sdim
504239462Sdimstatic bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505239462Sdim                                    Scope *S, CXXScopeSpec &SS,
506239462Sdim                                    IdentifierInfo *&Name,
507239462Sdim                                    SourceLocation NameLoc) {
508243830Sdim  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
509243830Sdim  SemaRef.LookupParsedName(R, S, &SS);
510243830Sdim  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
511239462Sdim    const char *TagName = 0;
512239462Sdim    const char *FixItTagName = 0;
513239462Sdim    switch (Tag->getTagKind()) {
514239462Sdim      case TTK_Class:
515239462Sdim        TagName = "class";
516239462Sdim        FixItTagName = "class ";
517239462Sdim        break;
518239462Sdim
519239462Sdim      case TTK_Enum:
520239462Sdim        TagName = "enum";
521239462Sdim        FixItTagName = "enum ";
522239462Sdim        break;
523239462Sdim
524239462Sdim      case TTK_Struct:
525239462Sdim        TagName = "struct";
526239462Sdim        FixItTagName = "struct ";
527239462Sdim        break;
528239462Sdim
529243830Sdim      case TTK_Interface:
530243830Sdim        TagName = "__interface";
531243830Sdim        FixItTagName = "__interface ";
532243830Sdim        break;
533243830Sdim
534239462Sdim      case TTK_Union:
535239462Sdim        TagName = "union";
536239462Sdim        FixItTagName = "union ";
537239462Sdim        break;
538239462Sdim    }
539239462Sdim
540239462Sdim    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
541239462Sdim      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
542239462Sdim      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
543239462Sdim
544243830Sdim    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
545243830Sdim         I != IEnd; ++I)
546243830Sdim      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
547243830Sdim        << Name << TagName;
548243830Sdim
549243830Sdim    // Replace lookup results with just the tag decl.
550243830Sdim    Result.clear(Sema::LookupTagName);
551243830Sdim    SemaRef.LookupParsedName(Result, S, &SS);
552239462Sdim    return true;
553239462Sdim  }
554239462Sdim
555239462Sdim  return false;
556239462Sdim}
557239462Sdim
558243830Sdim/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
559243830Sdimstatic ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
560243830Sdim                                  QualType T, SourceLocation NameLoc) {
561243830Sdim  ASTContext &Context = S.Context;
562243830Sdim
563243830Sdim  TypeLocBuilder Builder;
564243830Sdim  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
565243830Sdim
566243830Sdim  T = S.getElaboratedType(ETK_None, SS, T);
567243830Sdim  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
568243830Sdim  ElabTL.setElaboratedKeywordLoc(SourceLocation());
569243830Sdim  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
570243830Sdim  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571243830Sdim}
572243830Sdim
573221345SdimSema::NameClassification Sema::ClassifyName(Scope *S,
574221345Sdim                                            CXXScopeSpec &SS,
575221345Sdim                                            IdentifierInfo *&Name,
576221345Sdim                                            SourceLocation NameLoc,
577243830Sdim                                            const Token &NextToken,
578243830Sdim                                            bool IsAddressOfOperand,
579243830Sdim                                            CorrectionCandidateCallback *CCC) {
580221345Sdim  DeclarationNameInfo NameInfo(Name, NameLoc);
581221345Sdim  ObjCMethodDecl *CurMethod = getCurMethodDecl();
582221345Sdim
583221345Sdim  if (NextToken.is(tok::coloncolon)) {
584221345Sdim    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
585221345Sdim                                QualType(), false, SS, 0, false);
586221345Sdim
587221345Sdim  }
588221345Sdim
589221345Sdim  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
590221345Sdim  LookupParsedName(Result, S, &SS, !CurMethod);
591221345Sdim
592221345Sdim  // Perform lookup for Objective-C instance variables (including automatically
593221345Sdim  // synthesized instance variables), if we're in an Objective-C method.
594221345Sdim  // FIXME: This lookup really, really needs to be folded in to the normal
595221345Sdim  // unqualified lookup mechanism.
596221345Sdim  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
597221345Sdim    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
598221345Sdim    if (E.get() || E.isInvalid())
599221345Sdim      return E;
600221345Sdim  }
601221345Sdim
602221345Sdim  bool SecondTry = false;
603221345Sdim  bool IsFilteredTemplateName = false;
604221345Sdim
605221345SdimCorrected:
606221345Sdim  switch (Result.getResultKind()) {
607221345Sdim  case LookupResult::NotFound:
608221345Sdim    // If an unqualified-id is followed by a '(', then we have a function
609221345Sdim    // call.
610221345Sdim    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
611221345Sdim      // In C++, this is an ADL-only call.
612221345Sdim      // FIXME: Reference?
613234353Sdim      if (getLangOpts().CPlusPlus)
614221345Sdim        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
615221345Sdim
616221345Sdim      // C90 6.3.2.2:
617221345Sdim      //   If the expression that precedes the parenthesized argument list in a
618221345Sdim      //   function call consists solely of an identifier, and if no
619221345Sdim      //   declaration is visible for this identifier, the identifier is
620221345Sdim      //   implicitly declared exactly as if, in the innermost block containing
621221345Sdim      //   the function call, the declaration
622221345Sdim      //
623221345Sdim      //     extern int identifier ();
624221345Sdim      //
625221345Sdim      //   appeared.
626221345Sdim      //
627221345Sdim      // We also allow this in C99 as an extension.
628221345Sdim      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
629221345Sdim        Result.addDecl(D);
630221345Sdim        Result.resolveKind();
631221345Sdim        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
632221345Sdim      }
633221345Sdim    }
634221345Sdim
635221345Sdim    // In C, we first see whether there is a tag type by the same name, in
636221345Sdim    // which case it's likely that the user just forget to write "enum",
637221345Sdim    // "struct", or "union".
638239462Sdim    if (!getLangOpts().CPlusPlus && !SecondTry &&
639239462Sdim        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640239462Sdim      break;
641221345Sdim    }
642221345Sdim
643221345Sdim    // Perform typo correction to determine if there is another name that is
644221345Sdim    // close to this name.
645243830Sdim    if (!SecondTry && CCC) {
646224145Sdim      SecondTry = true;
647224145Sdim      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
648234353Sdim                                                 Result.getLookupKind(), S,
649243830Sdim                                                 &SS, *CCC)) {
650221345Sdim        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651221345Sdim        unsigned QualifiedDiag = diag::err_no_member_suggest;
652263508Sdim
653224145Sdim        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
654221345Sdim        NamedDecl *UnderlyingFirstDecl
655221345Sdim          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
656234353Sdim        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
657221345Sdim            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
658221345Sdim          UnqualifiedDiag = diag::err_no_template_suggest;
659221345Sdim          QualifiedDiag = diag::err_no_member_template_suggest;
660221345Sdim        } else if (UnderlyingFirstDecl &&
661221345Sdim                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
662221345Sdim                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663221345Sdim                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
664249423Sdim          UnqualifiedDiag = diag::err_unknown_typename_suggest;
665249423Sdim          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666249423Sdim        }
667224145Sdim
668263508Sdim        if (SS.isEmpty()) {
669263508Sdim          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
670263508Sdim        } else {// FIXME: is this even reachable? Test it.
671263508Sdim          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672263508Sdim          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
673263508Sdim                                  Name->getName().equals(CorrectedStr);
674263508Sdim          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675263508Sdim                                    << Name << computeDeclContext(SS, false)
676263508Sdim                                    << DroppedSpecifier << SS.getRange());
677263508Sdim        }
678221345Sdim
679221345Sdim        // Update the name, so that the caller has the new name.
680224145Sdim        Name = Corrected.getCorrectionAsIdentifierInfo();
681263508Sdim
682234353Sdim        // Typo correction corrected to a keyword.
683234353Sdim        if (Corrected.isKeyword())
684263508Sdim          return Name;
685234353Sdim
686224145Sdim        // Also update the LookupResult...
687224145Sdim        // FIXME: This should probably go away at some point
688224145Sdim        Result.clear();
689224145Sdim        Result.setLookupName(Corrected.getCorrection());
690263508Sdim        if (FirstDecl)
691234353Sdim          Result.addDecl(FirstDecl);
692221345Sdim
693221345Sdim        // If we found an Objective-C instance variable, let
694221345Sdim        // LookupInObjCMethod build the appropriate expression to
695221345Sdim        // reference the ivar.
696221345Sdim        // FIXME: This is a gross hack.
697221345Sdim        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
698221345Sdim          Result.clear();
699221345Sdim          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
700243830Sdim          return E;
701221345Sdim        }
702221345Sdim
703221345Sdim        goto Corrected;
704221345Sdim      }
705221345Sdim    }
706221345Sdim
707221345Sdim    // We failed to correct; just fall through and let the parser deal with it.
708221345Sdim    Result.suppressDiagnostics();
709221345Sdim    return NameClassification::Unknown();
710221345Sdim
711234353Sdim  case LookupResult::NotFoundInCurrentInstantiation: {
712221345Sdim    // We performed name lookup into the current instantiation, and there were
713221345Sdim    // dependent bases, so we treat this result the same way as any other
714221345Sdim    // dependent nested-name-specifier.
715221345Sdim
716221345Sdim    // C++ [temp.res]p2:
717221345Sdim    //   A name used in a template declaration or definition and that is
718221345Sdim    //   dependent on a template-parameter is assumed not to name a type
719221345Sdim    //   unless the applicable name lookup finds a type name or the name is
720221345Sdim    //   qualified by the keyword typename.
721221345Sdim    //
722221345Sdim    // FIXME: If the next token is '<', we might want to ask the parser to
723221345Sdim    // perform some heroics to see if we actually have a
724221345Sdim    // template-argument-list, which would indicate a missing 'template'
725221345Sdim    // keyword here.
726243830Sdim    return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727243830Sdim                                      NameInfo, IsAddressOfOperand,
728243830Sdim                                      /*TemplateArgs=*/0);
729234353Sdim  }
730221345Sdim
731221345Sdim  case LookupResult::Found:
732221345Sdim  case LookupResult::FoundOverloaded:
733221345Sdim  case LookupResult::FoundUnresolvedValue:
734221345Sdim    break;
735221345Sdim
736221345Sdim  case LookupResult::Ambiguous:
737234353Sdim    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
738221345Sdim        hasAnyAcceptableTemplateNames(Result)) {
739221345Sdim      // C++ [temp.local]p3:
740221345Sdim      //   A lookup that finds an injected-class-name (10.2) can result in an
741221345Sdim      //   ambiguity in certain cases (for example, if it is found in more than
742221345Sdim      //   one base class). If all of the injected-class-names that are found
743221345Sdim      //   refer to specializations of the same class template, and if the name
744221345Sdim      //   is followed by a template-argument-list, the reference refers to the
745221345Sdim      //   class template itself and not a specialization thereof, and is not
746221345Sdim      //   ambiguous.
747221345Sdim      //
748221345Sdim      // This filtering can make an ambiguous result into an unambiguous one,
749221345Sdim      // so try again after filtering out template names.
750221345Sdim      FilterAcceptableTemplateNames(Result);
751221345Sdim      if (!Result.isAmbiguous()) {
752221345Sdim        IsFilteredTemplateName = true;
753221345Sdim        break;
754221345Sdim      }
755221345Sdim    }
756221345Sdim
757221345Sdim    // Diagnose the ambiguity and return an error.
758221345Sdim    return NameClassification::Error();
759221345Sdim  }
760221345Sdim
761234353Sdim  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
762221345Sdim      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
763221345Sdim    // C++ [temp.names]p3:
764221345Sdim    //   After name lookup (3.4) finds that a name is a template-name or that
765221345Sdim    //   an operator-function-id or a literal- operator-id refers to a set of
766221345Sdim    //   overloaded functions any member of which is a function template if
767221345Sdim    //   this is followed by a <, the < is always taken as the delimiter of a
768221345Sdim    //   template-argument-list and never as the less-than operator.
769221345Sdim    if (!IsFilteredTemplateName)
770221345Sdim      FilterAcceptableTemplateNames(Result);
771221345Sdim
772221345Sdim    if (!Result.empty()) {
773221345Sdim      bool IsFunctionTemplate;
774263508Sdim      bool IsVarTemplate;
775221345Sdim      TemplateName Template;
776221345Sdim      if (Result.end() - Result.begin() > 1) {
777221345Sdim        IsFunctionTemplate = true;
778221345Sdim        Template = Context.getOverloadedTemplateName(Result.begin(),
779221345Sdim                                                     Result.end());
780221345Sdim      } else {
781221345Sdim        TemplateDecl *TD
782221345Sdim          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
783221345Sdim        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
784263508Sdim        IsVarTemplate = isa<VarTemplateDecl>(TD);
785263508Sdim
786221345Sdim        if (SS.isSet() && !SS.isInvalid())
787221345Sdim          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
788221345Sdim                                                    /*TemplateKeyword=*/false,
789221345Sdim                                                      TD);
790221345Sdim        else
791221345Sdim          Template = TemplateName(TD);
792221345Sdim      }
793221345Sdim
794221345Sdim      if (IsFunctionTemplate) {
795221345Sdim        // Function templates always go through overload resolution, at which
796221345Sdim        // point we'll perform the various checks (e.g., accessibility) we need
797221345Sdim        // to based on which function we selected.
798221345Sdim        Result.suppressDiagnostics();
799221345Sdim
800221345Sdim        return NameClassification::FunctionTemplate(Template);
801221345Sdim      }
802263508Sdim
803263508Sdim      return IsVarTemplate ? NameClassification::VarTemplate(Template)
804263508Sdim                           : NameClassification::TypeTemplate(Template);
805221345Sdim    }
806221345Sdim  }
807243830Sdim
808221345Sdim  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
809221345Sdim  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810221345Sdim    DiagnoseUseOfDecl(Type, NameLoc);
811221345Sdim    QualType T = Context.getTypeDeclType(Type);
812243830Sdim    if (SS.isNotEmpty())
813243830Sdim      return buildNestedType(*this, SS, T, NameLoc);
814239462Sdim    return ParsedType::make(T);
815221345Sdim  }
816243830Sdim
817221345Sdim  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
818221345Sdim  if (!Class) {
819221345Sdim    // FIXME: It's unfortunate that we don't have a Type node for handling this.
820221345Sdim    if (ObjCCompatibleAliasDecl *Alias
821221345Sdim                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
822221345Sdim      Class = Alias->getClassInterface();
823221345Sdim  }
824221345Sdim
825221345Sdim  if (Class) {
826221345Sdim    DiagnoseUseOfDecl(Class, NameLoc);
827221345Sdim
828221345Sdim    if (NextToken.is(tok::period)) {
829221345Sdim      // Interface. <something> is parsed as a property reference expression.
830221345Sdim      // Just return "unknown" as a fall-through for now.
831221345Sdim      Result.suppressDiagnostics();
832221345Sdim      return NameClassification::Unknown();
833221345Sdim    }
834221345Sdim
835221345Sdim    QualType T = Context.getObjCInterfaceType(Class);
836221345Sdim    return ParsedType::make(T);
837221345Sdim  }
838239462Sdim
839243830Sdim  // We can have a type template here if we're classifying a template argument.
840243830Sdim  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
841243830Sdim    return NameClassification::TypeTemplate(
842243830Sdim        TemplateName(cast<TemplateDecl>(FirstDecl)));
843243830Sdim
844239462Sdim  // Check for a tag type hidden by a non-type decl in a few cases where it
845239462Sdim  // seems likely a type is wanted instead of the non-type that was found.
846263508Sdim  bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
847263508Sdim  if ((NextToken.is(tok::identifier) ||
848263508Sdim       (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
849263508Sdim      isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
850263508Sdim    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
851263508Sdim    DiagnoseUseOfDecl(Type, NameLoc);
852263508Sdim    QualType T = Context.getTypeDeclType(Type);
853263508Sdim    if (SS.isNotEmpty())
854263508Sdim      return buildNestedType(*this, SS, T, NameLoc);
855263508Sdim    return ParsedType::make(T);
856239462Sdim  }
857221345Sdim
858243830Sdim  if (FirstDecl->isCXXClassMember())
859234353Sdim    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
860221345Sdim
861221345Sdim  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862221345Sdim  return BuildDeclarationNameExpr(SS, Result, ADL);
863221345Sdim}
864221345Sdim
865198092Srdivacky// Determines the context to return to after temporarily entering a
866198092Srdivacky// context.  This depends in an unnecessarily complicated way on the
867198092Srdivacky// exact ordering of callbacks from the parser.
868193326SedDeclContext *Sema::getContainingDC(DeclContext *DC) {
869193326Sed
870198092Srdivacky  // Functions defined inline within classes aren't parsed until we've
871198092Srdivacky  // finished parsing the top-level class, so the top-level class is
872198092Srdivacky  // the context we'll need to return to.
873263508Sdim  // A Lambda call operator whose parent is a class must not be treated
874263508Sdim  // as an inline member function.  A Lambda can be used legally
875263508Sdim  // either as an in-class member initializer or a default argument.  These
876263508Sdim  // are parsed once the class has been marked complete and so the containing
877263508Sdim  // context would be the nested class (when the lambda is defined in one);
878263508Sdim  // If the class is not complete, then the lambda is being used in an
879263508Sdim  // ill-formed fashion (such as to specify the width of a bit-field, or
880263508Sdim  // in an array-bound) - in which case we still want to return the
881263508Sdim  // lexically containing DC (which could be a nested class).
882263508Sdim  if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
883198092Srdivacky    DC = DC->getLexicalParent();
884198092Srdivacky
885198092Srdivacky    // A function not defined within a class will always return to its
886198092Srdivacky    // lexical context.
887198092Srdivacky    if (!isa<CXXRecordDecl>(DC))
888198092Srdivacky      return DC;
889198092Srdivacky
890198092Srdivacky    // A C++ inline method/friend is parsed *after* the topmost class
891198092Srdivacky    // it was declared in is fully parsed ("complete");  the topmost
892198092Srdivacky    // class is the context we need to return to.
893193326Sed    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
894193326Sed      DC = RD;
895193326Sed
896193326Sed    // Return the declaration context of the topmost class the inline method is
897193326Sed    // declared in.
898193326Sed    return DC;
899193326Sed  }
900193326Sed
901193326Sed  return DC->getLexicalParent();
902193326Sed}
903193326Sed
904193326Sedvoid Sema::PushDeclContext(Scope *S, DeclContext *DC) {
905193326Sed  assert(getContainingDC(DC) == CurContext &&
906193326Sed      "The next DeclContext should be lexically contained in the current one.");
907193326Sed  CurContext = DC;
908193326Sed  S->setEntity(DC);
909193326Sed}
910193326Sed
911193326Sedvoid Sema::PopDeclContext() {
912193326Sed  assert(CurContext && "DeclContext imbalance!");
913193326Sed
914193326Sed  CurContext = getContainingDC(CurContext);
915212904Sdim  assert(CurContext && "Popped translation unit!");
916193326Sed}
917193326Sed
918194613Sed/// EnterDeclaratorContext - Used when we must lookup names in the context
919194613Sed/// of a declarator's nested name specifier.
920201361Srdivacky///
921194613Sedvoid Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
922201361Srdivacky  // C++0x [basic.lookup.unqual]p13:
923201361Srdivacky  //   A name used in the definition of a static data member of class
924201361Srdivacky  //   X (after the qualified-id of the static member) is looked up as
925201361Srdivacky  //   if the name was used in a member function of X.
926201361Srdivacky  // C++0x [basic.lookup.unqual]p14:
927201361Srdivacky  //   If a variable member of a namespace is defined outside of the
928201361Srdivacky  //   scope of its namespace then any name used in the definition of
929201361Srdivacky  //   the variable member (after the declarator-id) is looked up as
930201361Srdivacky  //   if the definition of the variable member occurred in its
931201361Srdivacky  //   namespace.
932201361Srdivacky  // Both of these imply that we should push a scope whose context
933201361Srdivacky  // is the semantic context of the declaration.  We can't use
934201361Srdivacky  // PushDeclContext here because that context is not necessarily
935201361Srdivacky  // lexically contained in the current context.  Fortunately,
936201361Srdivacky  // the containing scope should have the appropriate information.
937201361Srdivacky
938201361Srdivacky  assert(!S->getEntity() && "scope already has entity");
939201361Srdivacky
940201361Srdivacky#ifndef NDEBUG
941201361Srdivacky  Scope *Ancestor = S->getParent();
942201361Srdivacky  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
943201361Srdivacky  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
944201361Srdivacky#endif
945201361Srdivacky
946194613Sed  CurContext = DC;
947201361Srdivacky  S->setEntity(DC);
948194613Sed}
949194613Sed
950194613Sedvoid Sema::ExitDeclaratorContext(Scope *S) {
951201361Srdivacky  assert(S->getEntity() == CurContext && "Context imbalance!");
952194613Sed
953201361Srdivacky  // Switch back to the lexical context.  The safety of this is
954201361Srdivacky  // enforced by an assert in EnterDeclaratorContext.
955201361Srdivacky  Scope *Ancestor = S->getParent();
956201361Srdivacky  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
957263508Sdim  CurContext = Ancestor->getEntity();
958201361Srdivacky
959201361Srdivacky  // We don't need to do anything with the scope, which is going to
960201361Srdivacky  // disappear.
961194613Sed}
962194613Sed
963226633Sdim
964226633Sdimvoid Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
965226633Sdim  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
966226633Sdim  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
967226633Sdim    // We assume that the caller has already called
968226633Sdim    // ActOnReenterTemplateScope
969226633Sdim    FD = TFD->getTemplatedDecl();
970226633Sdim  }
971226633Sdim  if (!FD)
972226633Sdim    return;
973226633Sdim
974234353Sdim  // Same implementation as PushDeclContext, but enters the context
975234353Sdim  // from the lexical parent, rather than the top-level class.
976234353Sdim  assert(CurContext == FD->getLexicalParent() &&
977234353Sdim    "The next DeclContext should be lexically contained in the current one.");
978234353Sdim  CurContext = FD;
979234353Sdim  S->setEntity(CurContext);
980234353Sdim
981226633Sdim  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
982226633Sdim    ParmVarDecl *Param = FD->getParamDecl(P);
983226633Sdim    // If the parameter has an identifier, then add it to the scope
984226633Sdim    if (Param->getIdentifier()) {
985226633Sdim      S->AddDecl(Param);
986226633Sdim      IdResolver.AddDecl(Param);
987226633Sdim    }
988226633Sdim  }
989226633Sdim}
990226633Sdim
991226633Sdim
992234353Sdimvoid Sema::ActOnExitFunctionContext() {
993234353Sdim  // Same implementation as PopDeclContext, but returns to the lexical parent,
994234353Sdim  // rather than the top-level class.
995234353Sdim  assert(CurContext && "DeclContext imbalance!");
996234353Sdim  CurContext = CurContext->getLexicalParent();
997234353Sdim  assert(CurContext && "Popped translation unit!");
998234353Sdim}
999234353Sdim
1000234353Sdim
1001193326Sed/// \brief Determine whether we allow overloading of the function
1002193326Sed/// PrevDecl with another declaration.
1003193326Sed///
1004193326Sed/// This routine determines whether overloading is possible, not
1005193326Sed/// whether some new function is actually an overload. It will return
1006193326Sed/// true in C++ (where we can always provide overloads) or, as an
1007193326Sed/// extension, in C when the previous function is already an
1008193326Sed/// overloaded function declaration or has the "overloadable"
1009193326Sed/// attribute.
1010199512Srdivackystatic bool AllowOverloadingOfFunction(LookupResult &Previous,
1011199512Srdivacky                                       ASTContext &Context) {
1012234353Sdim  if (Context.getLangOpts().CPlusPlus)
1013193326Sed    return true;
1014193326Sed
1015199512Srdivacky  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1016193326Sed    return true;
1017193326Sed
1018199512Srdivacky  return (Previous.getResultKind() == LookupResult::Found
1019199512Srdivacky          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1020193326Sed}
1021193326Sed
1022193326Sed/// Add this decl to the scope shadowed decl chains.
1023198092Srdivackyvoid Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1024193326Sed  // Move up the scope chain until we find the nearest enclosing
1025193326Sed  // non-transparent context. The declaration will be introduced into this
1026193326Sed  // scope.
1027263508Sdim  while (S->getEntity() && S->getEntity()->isTransparentContext())
1028193326Sed    S = S->getParent();
1029193326Sed
1030193326Sed  // Add scoped declarations into their context, so that they can be
1031193326Sed  // found later. Declarations without a context won't be inserted
1032193326Sed  // into any context.
1033198092Srdivacky  if (AddToContext)
1034198092Srdivacky    CurContext->addDecl(D);
1035193326Sed
1036263508Sdim  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1037263508Sdim  // are function-local declarations.
1038263508Sdim  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1039226633Sdim      !D->getDeclContext()->getRedeclContext()->Equals(
1040263508Sdim        D->getLexicalDeclContext()->getRedeclContext()) &&
1041263508Sdim      !D->getLexicalDeclContext()->isFunctionOrMethod())
1042198092Srdivacky    return;
1043193326Sed
1044204643Srdivacky  // Template instantiations should also not be pushed into scope.
1045204643Srdivacky  if (isa<FunctionDecl>(D) &&
1046204643Srdivacky      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1047204643Srdivacky    return;
1048204643Srdivacky
1049198092Srdivacky  // If this replaces anything in the current scope,
1050198092Srdivacky  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1051198092Srdivacky                               IEnd = IdResolver.end();
1052198092Srdivacky  for (; I != IEnd; ++I) {
1053212904Sdim    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054212904Sdim      S->RemoveDecl(*I);
1055198092Srdivacky      IdResolver.RemoveDecl(*I);
1056198092Srdivacky
1057198092Srdivacky      // Should only need to replace one decl.
1058198092Srdivacky      break;
1059193326Sed    }
1060193326Sed  }
1061193326Sed
1062212904Sdim  S->AddDecl(D);
1063221345Sdim
1064221345Sdim  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1065221345Sdim    // Implicitly-generated labels may end up getting generated in an order that
1066221345Sdim    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1067221345Sdim    // the label at the appropriate place in the identifier chain.
1068221345Sdim    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1069221345Sdim      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1070221345Sdim      if (IDC == CurContext) {
1071221345Sdim        if (!S->isDeclScope(*I))
1072221345Sdim          continue;
1073221345Sdim      } else if (IDC->Encloses(CurContext))
1074221345Sdim        break;
1075221345Sdim    }
1076221345Sdim
1077221345Sdim    IdResolver.InsertDeclAfter(I, D);
1078221345Sdim  } else {
1079221345Sdim    IdResolver.AddDecl(D);
1080221345Sdim  }
1081193326Sed}
1082193326Sed
1083234353Sdimvoid Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1084234353Sdim  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1085234353Sdim    TUScope->AddDecl(D);
1086234353Sdim}
1087234353Sdim
1088263508Sdimbool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1089221345Sdim                         bool ExplicitInstantiationOrSpecialization) {
1090249423Sdim  return IdResolver.isDeclInScope(D, Ctx, S,
1091221345Sdim                                  ExplicitInstantiationOrSpecialization);
1092198092Srdivacky}
1093198092Srdivacky
1094212904SdimScope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1095212904Sdim  DeclContext *TargetDC = DC->getPrimaryContext();
1096212904Sdim  do {
1097263508Sdim    if (DeclContext *ScopeDC = S->getEntity())
1098212904Sdim      if (ScopeDC->getPrimaryContext() == TargetDC)
1099212904Sdim        return S;
1100212904Sdim  } while ((S = S->getParent()));
1101212904Sdim
1102212904Sdim  return 0;
1103212904Sdim}
1104212904Sdim
1105199512Srdivackystatic bool isOutOfScopePreviousDeclaration(NamedDecl *,
1106199512Srdivacky                                            DeclContext*,
1107199512Srdivacky                                            ASTContext&);
1108199512Srdivacky
1109199512Srdivacky/// Filters out lookup results that don't fall within the given scope
1110199512Srdivacky/// as determined by isDeclInScope.
1111223017Sdimvoid Sema::FilterLookupForScope(LookupResult &R,
1112223017Sdim                                DeclContext *Ctx, Scope *S,
1113223017Sdim                                bool ConsiderLinkage,
1114223017Sdim                                bool ExplicitInstantiationOrSpecialization) {
1115199512Srdivacky  LookupResult::Filter F = R.makeFilter();
1116199512Srdivacky  while (F.hasNext()) {
1117199512Srdivacky    NamedDecl *D = F.next();
1118199512Srdivacky
1119223017Sdim    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1120199512Srdivacky      continue;
1121199512Srdivacky
1122199512Srdivacky    if (ConsiderLinkage &&
1123223017Sdim        isOutOfScopePreviousDeclaration(D, Ctx, Context))
1124199512Srdivacky      continue;
1125199512Srdivacky
1126199512Srdivacky    F.erase();
1127199512Srdivacky  }
1128199512Srdivacky
1129199512Srdivacky  F.done();
1130199512Srdivacky}
1131199512Srdivacky
1132199512Srdivackystatic bool isUsingDecl(NamedDecl *D) {
1133199512Srdivacky  return isa<UsingShadowDecl>(D) ||
1134199512Srdivacky         isa<UnresolvedUsingTypenameDecl>(D) ||
1135199512Srdivacky         isa<UnresolvedUsingValueDecl>(D);
1136199512Srdivacky}
1137199512Srdivacky
1138199512Srdivacky/// Removes using shadow declarations from the lookup results.
1139199512Srdivackystatic void RemoveUsingDecls(LookupResult &R) {
1140199512Srdivacky  LookupResult::Filter F = R.makeFilter();
1141199512Srdivacky  while (F.hasNext())
1142199512Srdivacky    if (isUsingDecl(F.next()))
1143199512Srdivacky      F.erase();
1144199512Srdivacky
1145199512Srdivacky  F.done();
1146199512Srdivacky}
1147199512Srdivacky
1148212904Sdim/// \brief Check for this common pattern:
1149212904Sdim/// @code
1150212904Sdim/// class S {
1151212904Sdim///   S(const S&); // DO NOT IMPLEMENT
1152212904Sdim///   void operator=(const S&); // DO NOT IMPLEMENT
1153212904Sdim/// };
1154212904Sdim/// @endcode
1155212904Sdimstatic bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1156212904Sdim  // FIXME: Should check for private access too but access is set after we get
1157212904Sdim  // the decl here.
1158223017Sdim  if (D->doesThisDeclarationHaveABody())
1159212904Sdim    return false;
1160212904Sdim
1161212904Sdim  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1162212904Sdim    return CD->isCopyConstructor();
1163218893Sdim  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1164218893Sdim    return Method->isCopyAssignmentOperator();
1165218893Sdim  return false;
1166212904Sdim}
1167212904Sdim
1168249423Sdim// We need this to handle
1169249423Sdim//
1170249423Sdim// typedef struct {
1171249423Sdim//   void *foo() { return 0; }
1172249423Sdim// } A;
1173249423Sdim//
1174249423Sdim// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1175249423Sdim// for example. If 'A', foo will have external linkage. If we have '*A',
1176249423Sdim// foo will have no linkage. Since we can't know untill we get to the end
1177249423Sdim// of the typedef, this function finds out if D might have non external linkage.
1178249423Sdim// Callers should verify at the end of the TU if it D has external linkage or
1179249423Sdim// not.
1180249423Sdimbool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1181249423Sdim  const DeclContext *DC = D->getDeclContext();
1182249423Sdim  while (!DC->isTranslationUnit()) {
1183249423Sdim    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1184249423Sdim      if (!RD->hasNameForLinkage())
1185249423Sdim        return true;
1186249423Sdim    }
1187249423Sdim    DC = DC->getParent();
1188249423Sdim  }
1189249423Sdim
1190263508Sdim  return !D->isExternallyVisible();
1191249423Sdim}
1192249423Sdim
1193263508Sdim// FIXME: This needs to be refactored; some other isInMainFile users want
1194263508Sdim// these semantics.
1195263508Sdimstatic bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1196263508Sdim  if (S.TUKind != TU_Complete)
1197263508Sdim    return false;
1198263508Sdim  return S.SourceMgr.isInMainFile(Loc);
1199263508Sdim}
1200263508Sdim
1201212904Sdimbool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1202212904Sdim  assert(D);
1203212904Sdim
1204212904Sdim  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1205212904Sdim    return false;
1206212904Sdim
1207212904Sdim  // Ignore class templates.
1208218893Sdim  if (D->getDeclContext()->isDependentContext() ||
1209218893Sdim      D->getLexicalDeclContext()->isDependentContext())
1210212904Sdim    return false;
1211212904Sdim
1212212904Sdim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1213212904Sdim    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1214212904Sdim      return false;
1215212904Sdim
1216212904Sdim    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1217212904Sdim      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1218212904Sdim        return false;
1219212904Sdim    } else {
1220263508Sdim      // 'static inline' functions are defined in headers; don't warn.
1221263508Sdim      if (FD->isInlineSpecified() &&
1222263508Sdim          !isMainFileLoc(*this, FD->getLocation()))
1223212904Sdim        return false;
1224212904Sdim    }
1225212904Sdim
1226223017Sdim    if (FD->doesThisDeclarationHaveABody() &&
1227218893Sdim        Context.DeclMustBeEmitted(FD))
1228218893Sdim      return false;
1229218893Sdim  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1230263508Sdim    // Constants and utility variables are defined in headers with internal
1231263508Sdim    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1232263508Sdim    // like "inline".)
1233263508Sdim    if (!isMainFileLoc(*this, VD->getLocation()))
1234218893Sdim      return false;
1235218893Sdim
1236263508Sdim    if (Context.DeclMustBeEmitted(VD))
1237263508Sdim      return false;
1238263508Sdim
1239212904Sdim    if (VD->isStaticDataMember() &&
1240212904Sdim        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1241212904Sdim      return false;
1242218893Sdim  } else {
1243218893Sdim    return false;
1244212904Sdim  }
1245212904Sdim
1246218893Sdim  // Only warn for unused decls internal to the translation unit.
1247249423Sdim  return mightHaveNonExternalLinkage(D);
1248218893Sdim}
1249218893Sdim
1250218893Sdimvoid Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1251212904Sdim  if (!D)
1252212904Sdim    return;
1253212904Sdim
1254212904Sdim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1255263508Sdim    const FunctionDecl *First = FD->getFirstDecl();
1256212904Sdim    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1257212904Sdim      return; // First should already be in the vector.
1258212904Sdim  }
1259212904Sdim
1260212904Sdim  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1261263508Sdim    const VarDecl *First = VD->getFirstDecl();
1262212904Sdim    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1263212904Sdim      return; // First should already be in the vector.
1264212904Sdim  }
1265212904Sdim
1266239462Sdim  if (ShouldWarnIfUnusedFileScopedDecl(D))
1267239462Sdim    UnusedFileScopedDecls.push_back(D);
1268239462Sdim}
1269212904Sdim
1270199482Srdivackystatic bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1271203955Srdivacky  if (D->isInvalidDecl())
1272203955Srdivacky    return false;
1273203955Srdivacky
1274234353Sdim  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1275199482Srdivacky    return false;
1276203955Srdivacky
1277218893Sdim  if (isa<LabelDecl>(D))
1278218893Sdim    return true;
1279218893Sdim
1280203955Srdivacky  // White-list anything that isn't a local variable.
1281203955Srdivacky  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1282203955Srdivacky      !D->getDeclContext()->isFunctionOrMethod())
1283203955Srdivacky    return false;
1284203955Srdivacky
1285203955Srdivacky  // Types of valid local variables should be complete, so this should succeed.
1286234353Sdim  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1287206084Srdivacky
1288206084Srdivacky    // White-list anything with an __attribute__((unused)) type.
1289206084Srdivacky    QualType Ty = VD->getType();
1290206084Srdivacky
1291206084Srdivacky    // Only look at the outermost level of typedef.
1292243830Sdim    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1293206084Srdivacky      if (TT->getDecl()->hasAttr<UnusedAttr>())
1294206084Srdivacky        return false;
1295206084Srdivacky    }
1296206084Srdivacky
1297208600Srdivacky    // If we failed to complete the type for some reason, or if the type is
1298208600Srdivacky    // dependent, don't diagnose the variable.
1299208600Srdivacky    if (Ty->isIncompleteType() || Ty->isDependentType())
1300207619Srdivacky      return false;
1301207619Srdivacky
1302206084Srdivacky    if (const TagType *TT = Ty->getAs<TagType>()) {
1303206084Srdivacky      const TagDecl *Tag = TT->getDecl();
1304206084Srdivacky      if (Tag->hasAttr<UnusedAttr>())
1305206084Srdivacky        return false;
1306206084Srdivacky
1307206084Srdivacky      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1308263508Sdim        if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1309199482Srdivacky          return false;
1310234353Sdim
1311234353Sdim        if (const Expr *Init = VD->getInit()) {
1312243830Sdim          if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1313243830Sdim            Init = Cleanups->getSubExpr();
1314234353Sdim          const CXXConstructExpr *Construct =
1315234353Sdim            dyn_cast<CXXConstructExpr>(Init);
1316234353Sdim          if (Construct && !Construct->isElidable()) {
1317234353Sdim            CXXConstructorDecl *CD = Construct->getConstructor();
1318263508Sdim            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1319234353Sdim              return false;
1320234353Sdim          }
1321234353Sdim        }
1322199482Srdivacky      }
1323199482Srdivacky    }
1324206084Srdivacky
1325206084Srdivacky    // TODO: __attribute__((unused)) templates?
1326199482Srdivacky  }
1327199482Srdivacky
1328203955Srdivacky  return true;
1329199482Srdivacky}
1330199482Srdivacky
1331226633Sdimstatic void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1332226633Sdim                                     FixItHint &Hint) {
1333226633Sdim  if (isa<LabelDecl>(D)) {
1334226633Sdim    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1335234353Sdim                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1336226633Sdim    if (AfterColon.isInvalid())
1337226633Sdim      return;
1338226633Sdim    Hint = FixItHint::CreateRemoval(CharSourceRange::
1339226633Sdim                                    getCharRange(D->getLocStart(), AfterColon));
1340226633Sdim  }
1341226633Sdim  return;
1342226633Sdim}
1343226633Sdim
1344218893Sdim/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1345218893Sdim/// unless they are marked attr(unused).
1346208600Srdivackyvoid Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1347226633Sdim  FixItHint Hint;
1348208600Srdivacky  if (!ShouldDiagnoseUnusedDecl(D))
1349208600Srdivacky    return;
1350208600Srdivacky
1351226633Sdim  GenerateFixForUnusedDecl(D, Context, Hint);
1352226633Sdim
1353218893Sdim  unsigned DiagID;
1354208600Srdivacky  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1355218893Sdim    DiagID = diag::warn_unused_exception_param;
1356218893Sdim  else if (isa<LabelDecl>(D))
1357218893Sdim    DiagID = diag::warn_unused_label;
1358208600Srdivacky  else
1359218893Sdim    DiagID = diag::warn_unused_variable;
1360218893Sdim
1361226633Sdim  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1362208600Srdivacky}
1363208600Srdivacky
1364218893Sdimstatic void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1365218893Sdim  // Verify that we have no forward references left.  If so, there was a goto
1366218893Sdim  // or address of a label taken, but no definition of it.  Label fwd
1367218893Sdim  // definitions are indicated with a null substmt.
1368218893Sdim  if (L->getStmt() == 0)
1369218893Sdim    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1370218893Sdim}
1371218893Sdim
1372193326Sedvoid Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1373193326Sed  if (S->decl_empty()) return;
1374193326Sed  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1375198092Srdivacky         "Scope shouldn't contain decls!");
1376193326Sed
1377193326Sed  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1378193326Sed       I != E; ++I) {
1379212904Sdim    Decl *TmpD = (*I);
1380193326Sed    assert(TmpD && "This decl didn't get pushed??");
1381193326Sed
1382193326Sed    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1383193326Sed    NamedDecl *D = cast<NamedDecl>(TmpD);
1384193326Sed
1385193326Sed    if (!D->getDeclName()) continue;
1386193326Sed
1387198092Srdivacky    // Diagnose unused variables in this scope.
1388249423Sdim    if (!S->hasUnrecoverableErrorOccurred())
1389208600Srdivacky      DiagnoseUnusedDecl(D);
1390208600Srdivacky
1391218893Sdim    // If this was a forward reference to a label, verify it was defined.
1392218893Sdim    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1393218893Sdim      CheckPoppedLabel(LD, *this);
1394218893Sdim
1395193326Sed    // Remove this name from our lexical scope.
1396193326Sed    IdResolver.RemoveDecl(D);
1397193326Sed  }
1398263508Sdim  DiagnoseUnusedBackingIvarInAccessor(S);
1399193326Sed}
1400193326Sed
1401234353Sdimvoid Sema::ActOnStartFunctionDeclarator() {
1402234353Sdim  ++InFunctionDeclarator;
1403234353Sdim}
1404234353Sdim
1405234353Sdimvoid Sema::ActOnEndFunctionDeclarator() {
1406234353Sdim  assert(InFunctionDeclarator);
1407234353Sdim  --InFunctionDeclarator;
1408234353Sdim}
1409234353Sdim
1410207619Srdivacky/// \brief Look for an Objective-C class in the translation unit.
1411202379Srdivacky///
1412207619Srdivacky/// \param Id The name of the Objective-C class we're looking for. If
1413202379Srdivacky/// typo-correction fixes this name, the Id will be updated
1414202379Srdivacky/// to the fixed name.
1415202379Srdivacky///
1416207619Srdivacky/// \param IdLoc The location of the name in the translation unit.
1417207619Srdivacky///
1418239462Sdim/// \param DoTypoCorrection If true, this routine will attempt typo correction
1419207619Srdivacky/// if there is no class with the given name.
1420207619Srdivacky///
1421207619Srdivacky/// \returns The declaration of the named Objective-C class, or NULL if the
1422207619Srdivacky/// class could not be found.
1423202379SrdivackyObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1424207619Srdivacky                                              SourceLocation IdLoc,
1425224145Sdim                                              bool DoTypoCorrection) {
1426193326Sed  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1427193326Sed  // creation from this context.
1428207619Srdivacky  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1429198092Srdivacky
1430224145Sdim  if (!IDecl && DoTypoCorrection) {
1431202379Srdivacky    // Perform typo correction at the given location, but only if we
1432202379Srdivacky    // find an Objective-C class name.
1433234353Sdim    DeclFilterCCC<ObjCInterfaceDecl> Validator;
1434234353Sdim    if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1435234353Sdim                                       LookupOrdinaryName, TUScope, NULL,
1436234353Sdim                                       Validator)) {
1437263508Sdim      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1438234353Sdim      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1439202379Srdivacky      Id = IDecl->getIdentifier();
1440202379Srdivacky    }
1441202379Srdivacky  }
1442234353Sdim  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1443234353Sdim  // This routine must always return a class definition, if any.
1444234353Sdim  if (Def && Def->getDefinition())
1445234353Sdim      Def = Def->getDefinition();
1446234353Sdim  return Def;
1447193326Sed}
1448193326Sed
1449193326Sed/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1450193326Sed/// from S, where a non-field would be declared. This routine copes
1451193326Sed/// with the difference between C and C++ scoping rules in structs and
1452193326Sed/// unions. For example, the following code is well-formed in C but
1453193326Sed/// ill-formed in C++:
1454193326Sed/// @code
1455193326Sed/// struct S6 {
1456193326Sed///   enum { BAR } e;
1457193326Sed/// };
1458198092Srdivacky///
1459193326Sed/// void test_S6() {
1460193326Sed///   struct S6 a;
1461193326Sed///   a.e = BAR;
1462193326Sed/// }
1463193326Sed/// @endcode
1464193326Sed/// For the declaration of BAR, this routine will return a different
1465193326Sed/// scope. The scope S will be the scope of the unnamed enumeration
1466193326Sed/// within S6. In C++, this routine will return the scope associated
1467193326Sed/// with S6, because the enumeration's scope is a transparent
1468193326Sed/// context but structures can contain non-field names. In C, this
1469193326Sed/// routine will return the translation unit scope, since the
1470193326Sed/// enumeration's scope is a transparent context and structures cannot
1471193326Sed/// contain non-field names.
1472193326SedScope *Sema::getNonFieldDeclScope(Scope *S) {
1473193326Sed  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1474263508Sdim         (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1475234353Sdim         (S->isClassScope() && !getLangOpts().CPlusPlus))
1476193326Sed    S = S->getParent();
1477193326Sed  return S;
1478193326Sed}
1479193326Sed
1480249423Sdim/// \brief Looks up the declaration of "struct objc_super" and
1481249423Sdim/// saves it for later use in building builtin declaration of
1482249423Sdim/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1483249423Sdim/// pre-existing declaration exists no action takes place.
1484249423Sdimstatic void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1485249423Sdim                                        IdentifierInfo *II) {
1486249423Sdim  if (!II->isStr("objc_msgSendSuper"))
1487249423Sdim    return;
1488249423Sdim  ASTContext &Context = ThisSema.Context;
1489249423Sdim
1490249423Sdim  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1491249423Sdim                      SourceLocation(), Sema::LookupTagName);
1492249423Sdim  ThisSema.LookupName(Result, S);
1493249423Sdim  if (Result.getResultKind() == LookupResult::Found)
1494249423Sdim    if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1495249423Sdim      Context.setObjCSuperType(Context.getTagDeclType(TD));
1496249423Sdim}
1497249423Sdim
1498193326Sed/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1499193326Sed/// file scope.  lazily create a decl for it. ForRedeclaration is true
1500193326Sed/// if we're creating this built-in in anticipation of redeclaring the
1501193326Sed/// built-in.
1502193326SedNamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1503193326Sed                                     Scope *S, bool ForRedeclaration,
1504193326Sed                                     SourceLocation Loc) {
1505249423Sdim  LookupPredefedObjCSuperType(*this, S, II);
1506249423Sdim
1507193326Sed  Builtin::ID BID = (Builtin::ID)bid;
1508193326Sed
1509194179Sed  ASTContext::GetBuiltinTypeError Error;
1510198092Srdivacky  QualType R = Context.GetBuiltinType(BID, Error);
1511193326Sed  switch (Error) {
1512194179Sed  case ASTContext::GE_None:
1513193326Sed    // Okay
1514193326Sed    break;
1515193326Sed
1516198092Srdivacky  case ASTContext::GE_Missing_stdio:
1517193326Sed    if (ForRedeclaration)
1518218893Sdim      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1519193326Sed        << Context.BuiltinInfo.GetName(BID);
1520193326Sed    return 0;
1521198092Srdivacky
1522198092Srdivacky  case ASTContext::GE_Missing_setjmp:
1523198092Srdivacky    if (ForRedeclaration)
1524218893Sdim      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1525198092Srdivacky        << Context.BuiltinInfo.GetName(BID);
1526198092Srdivacky    return 0;
1527227737Sdim
1528227737Sdim  case ASTContext::GE_Missing_ucontext:
1529227737Sdim    if (ForRedeclaration)
1530227737Sdim      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1531227737Sdim        << Context.BuiltinInfo.GetName(BID);
1532227737Sdim    return 0;
1533193326Sed  }
1534193326Sed
1535193326Sed  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1536193326Sed    Diag(Loc, diag::ext_implicit_lib_function_decl)
1537193326Sed      << Context.BuiltinInfo.GetName(BID)
1538193326Sed      << R;
1539193326Sed    if (Context.BuiltinInfo.getHeaderName(BID) &&
1540218893Sdim        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1541226633Sdim          != DiagnosticsEngine::Ignored)
1542193326Sed      Diag(Loc, diag::note_please_include_header)
1543193326Sed        << Context.BuiltinInfo.getHeaderName(BID)
1544193326Sed        << Context.BuiltinInfo.GetName(BID);
1545193326Sed  }
1546193326Sed
1547263508Sdim  DeclContext *Parent = Context.getTranslationUnitDecl();
1548263508Sdim  if (getLangOpts().CPlusPlus) {
1549263508Sdim    LinkageSpecDecl *CLinkageDecl =
1550263508Sdim        LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1551263508Sdim                                LinkageSpecDecl::lang_c, false);
1552263508Sdim    Parent->addDecl(CLinkageDecl);
1553263508Sdim    Parent = CLinkageDecl;
1554263508Sdim  }
1555263508Sdim
1556193326Sed  FunctionDecl *New = FunctionDecl::Create(Context,
1557263508Sdim                                           Parent,
1558221345Sdim                                           Loc, Loc, II, R, /*TInfo=*/0,
1559212904Sdim                                           SC_Extern,
1560249423Sdim                                           false,
1561193326Sed                                           /*hasPrototype=*/true);
1562193326Sed  New->setImplicit();
1563193326Sed
1564193326Sed  // Create Decl objects for each parameter, adding them to the
1565193326Sed  // FunctionDecl.
1566218893Sdim  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1567226633Sdim    SmallVector<ParmVarDecl*, 16> Params;
1568221345Sdim    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1569221345Sdim      ParmVarDecl *parm =
1570221345Sdim        ParmVarDecl::Create(Context, New, SourceLocation(),
1571221345Sdim                            SourceLocation(), 0,
1572221345Sdim                            FT->getArgType(i), /*TInfo=*/0,
1573249423Sdim                            SC_None, 0);
1574221345Sdim      parm->setScopeInfo(0, i);
1575221345Sdim      Params.push_back(parm);
1576221345Sdim    }
1577226633Sdim    New->setParams(Params);
1578193326Sed  }
1579198092Srdivacky
1580198092Srdivacky  AddKnownFunctionAttributes(New);
1581263508Sdim  RegisterLocallyScopedExternCDecl(New, S);
1582198092Srdivacky
1583193326Sed  // TUScope is the translation-unit scope to insert this function into.
1584193326Sed  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1585193326Sed  // relate Scopes to DeclContexts, and probably eliminate CurContext
1586193326Sed  // entirely, but we're not there yet.
1587193326Sed  DeclContext *SavedContext = CurContext;
1588263508Sdim  CurContext = Parent;
1589193326Sed  PushOnScopeChains(New, TUScope);
1590193326Sed  CurContext = SavedContext;
1591193326Sed  return New;
1592193326Sed}
1593193326Sed
1594249423Sdim/// \brief Filter out any previous declarations that the given declaration
1595249423Sdim/// should not consider because they are not permitted to conflict, e.g.,
1596249423Sdim/// because they come from hidden sub-modules and do not refer to the same
1597249423Sdim/// entity.
1598249423Sdimstatic void filterNonConflictingPreviousDecls(ASTContext &context,
1599249423Sdim                                              NamedDecl *decl,
1600249423Sdim                                              LookupResult &previous){
1601249423Sdim  // This is only interesting when modules are enabled.
1602249423Sdim  if (!context.getLangOpts().Modules)
1603249423Sdim    return;
1604249423Sdim
1605249423Sdim  // Empty sets are uninteresting.
1606249423Sdim  if (previous.empty())
1607249423Sdim    return;
1608249423Sdim
1609249423Sdim  LookupResult::Filter filter = previous.makeFilter();
1610249423Sdim  while (filter.hasNext()) {
1611249423Sdim    NamedDecl *old = filter.next();
1612249423Sdim
1613249423Sdim    // Non-hidden declarations are never ignored.
1614249423Sdim    if (!old->isHidden())
1615249423Sdim      continue;
1616249423Sdim
1617263508Sdim    if (!old->isExternallyVisible())
1618249423Sdim      filter.erase();
1619249423Sdim  }
1620249423Sdim
1621249423Sdim  filter.done();
1622249423Sdim}
1623249423Sdim
1624234353Sdimbool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1625234353Sdim  QualType OldType;
1626234353Sdim  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1627234353Sdim    OldType = OldTypedef->getUnderlyingType();
1628234353Sdim  else
1629234353Sdim    OldType = Context.getTypeDeclType(Old);
1630234353Sdim  QualType NewType = New->getUnderlyingType();
1631234353Sdim
1632234353Sdim  if (NewType->isVariablyModifiedType()) {
1633234353Sdim    // Must not redefine a typedef with a variably-modified type.
1634234353Sdim    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1635234353Sdim    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1636234353Sdim      << Kind << NewType;
1637234353Sdim    if (Old->getLocation().isValid())
1638234353Sdim      Diag(Old->getLocation(), diag::note_previous_definition);
1639234353Sdim    New->setInvalidDecl();
1640234353Sdim    return true;
1641234353Sdim  }
1642234353Sdim
1643234353Sdim  if (OldType != NewType &&
1644234353Sdim      !OldType->isDependentType() &&
1645234353Sdim      !NewType->isDependentType() &&
1646234353Sdim      !Context.hasSameType(OldType, NewType)) {
1647234353Sdim    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1648234353Sdim    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1649234353Sdim      << Kind << NewType << OldType;
1650234353Sdim    if (Old->getLocation().isValid())
1651234353Sdim      Diag(Old->getLocation(), diag::note_previous_definition);
1652234353Sdim    New->setInvalidDecl();
1653234353Sdim    return true;
1654234353Sdim  }
1655234353Sdim  return false;
1656234353Sdim}
1657234353Sdim
1658221345Sdim/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1659193326Sed/// same name and scope as a previous declaration 'Old'.  Figure out
1660193326Sed/// how to resolve this situation, merging decls or emitting
1661193326Sed/// diagnostics as appropriate. If there was an error, set New to be invalid.
1662193326Sed///
1663221345Sdimvoid Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1664199512Srdivacky  // If the new decl is known invalid already, don't bother doing any
1665199512Srdivacky  // merging checks.
1666199512Srdivacky  if (New->isInvalidDecl()) return;
1667198092Srdivacky
1668193326Sed  // Allow multiple definitions for ObjC built-in typedefs.
1669193326Sed  // FIXME: Verify the underlying types are equivalent!
1670234353Sdim  if (getLangOpts().ObjC1) {
1671193326Sed    const IdentifierInfo *TypeID = New->getIdentifier();
1672193326Sed    switch (TypeID->getLength()) {
1673193326Sed    default: break;
1674198092Srdivacky    case 2:
1675239462Sdim      {
1676239462Sdim        if (!TypeID->isStr("id"))
1677239462Sdim          break;
1678239462Sdim        QualType T = New->getUnderlyingType();
1679239462Sdim        if (!T->isPointerType())
1680239462Sdim          break;
1681239462Sdim        if (!T->isVoidPointerType()) {
1682239462Sdim          QualType PT = T->getAs<PointerType>()->getPointeeType();
1683239462Sdim          if (!PT->isStructureType())
1684239462Sdim            break;
1685239462Sdim        }
1686239462Sdim        Context.setObjCIdRedefinitionType(T);
1687239462Sdim        // Install the built-in type for 'id', ignoring the current definition.
1688239462Sdim        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1689239462Sdim        return;
1690239462Sdim      }
1691193326Sed    case 5:
1692193326Sed      if (!TypeID->isStr("Class"))
1693193326Sed        break;
1694226633Sdim      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1695198092Srdivacky      // Install the built-in type for 'Class', ignoring the current definition.
1696198092Srdivacky      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1697193326Sed      return;
1698193326Sed    case 3:
1699193326Sed      if (!TypeID->isStr("SEL"))
1700193326Sed        break;
1701226633Sdim      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1702199990Srdivacky      // Install the built-in type for 'SEL', ignoring the current definition.
1703199990Srdivacky      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1704193326Sed      return;
1705193326Sed    }
1706193326Sed    // Fall through - the typedef name was not a builtin type.
1707193326Sed  }
1708199512Srdivacky
1709193326Sed  // Verify the old decl was also a type.
1710201361Srdivacky  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1711201361Srdivacky  if (!Old) {
1712198092Srdivacky    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1713193326Sed      << New->getDeclName();
1714199512Srdivacky
1715199512Srdivacky    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1716193326Sed    if (OldD->getLocation().isValid())
1717193326Sed      Diag(OldD->getLocation(), diag::note_previous_definition);
1718199512Srdivacky
1719193326Sed    return New->setInvalidDecl();
1720193326Sed  }
1721193326Sed
1722199512Srdivacky  // If the old declaration is invalid, just give up here.
1723199512Srdivacky  if (Old->isInvalidDecl())
1724199512Srdivacky    return New->setInvalidDecl();
1725199512Srdivacky
1726193326Sed  // If the typedef types are not identical, reject them in all languages and
1727193326Sed  // with any extensions enabled.
1728234353Sdim  if (isIncompatibleTypedef(Old, New))
1729234353Sdim    return;
1730193326Sed
1731263508Sdim  // The types match.  Link up the redeclaration chain and merge attributes if
1732263508Sdim  // the old declaration was a typedef.
1733263508Sdim  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1734263508Sdim    New->setPreviousDecl(Typedef);
1735263508Sdim    mergeDeclAttributes(New, Old);
1736263508Sdim  }
1737201361Srdivacky
1738234353Sdim  if (getLangOpts().MicrosoftExt)
1739193326Sed    return;
1740193326Sed
1741234353Sdim  if (getLangOpts().CPlusPlus) {
1742202379Srdivacky    // C++ [dcl.typedef]p2:
1743202379Srdivacky    //   In a given non-class scope, a typedef specifier can be used to
1744202379Srdivacky    //   redefine the name of any type declared in that scope to refer
1745202379Srdivacky    //   to the type to which it already refers.
1746193326Sed    if (!isa<CXXRecordDecl>(CurContext))
1747193326Sed      return;
1748202379Srdivacky
1749202379Srdivacky    // C++0x [dcl.typedef]p4:
1750202379Srdivacky    //   In a given class scope, a typedef specifier can be used to redefine
1751202379Srdivacky    //   any class-name declared in that scope that is not also a typedef-name
1752202379Srdivacky    //   to refer to the type to which it already refers.
1753202379Srdivacky    //
1754202379Srdivacky    // This wording came in via DR424, which was a correction to the
1755202379Srdivacky    // wording in DR56, which accidentally banned code like:
1756202379Srdivacky    //
1757202379Srdivacky    //   struct S {
1758202379Srdivacky    //     typedef struct A { } A;
1759202379Srdivacky    //   };
1760202379Srdivacky    //
1761202379Srdivacky    // in the C++03 standard. We implement the C++0x semantics, which
1762202379Srdivacky    // allow the above but disallow
1763202379Srdivacky    //
1764202379Srdivacky    //   struct S {
1765202379Srdivacky    //     typedef int I;
1766202379Srdivacky    //     typedef int I;
1767202379Srdivacky    //   };
1768202379Srdivacky    //
1769202379Srdivacky    // since that was the intent of DR56.
1770221345Sdim    if (!isa<TypedefNameDecl>(Old))
1771202379Srdivacky      return;
1772202379Srdivacky
1773193326Sed    Diag(New->getLocation(), diag::err_redefinition)
1774193326Sed      << New->getDeclName();
1775193326Sed    Diag(Old->getLocation(), diag::note_previous_definition);
1776193326Sed    return New->setInvalidDecl();
1777193326Sed  }
1778193326Sed
1779234353Sdim  // Modules always permit redefinition of typedefs, as does C11.
1780234353Sdim  if (getLangOpts().Modules || getLangOpts().C11)
1781234353Sdim    return;
1782234353Sdim
1783193326Sed  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1784193326Sed  // is normally mapped to an error, but can be controlled with
1785193576Sed  // -Wtypedef-redefinition.  If either the original or the redefinition is
1786193576Sed  // in a system header, don't emit this for compatibility with GCC.
1787204643Srdivacky  if (getDiagnostics().getSuppressSystemWarnings() &&
1788193576Sed      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1789193576Sed       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1790193326Sed    return;
1791198092Srdivacky
1792193326Sed  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1793193326Sed    << New->getDeclName();
1794193326Sed  Diag(Old->getLocation(), diag::note_previous_definition);
1795193326Sed  return;
1796193326Sed}
1797193326Sed
1798193326Sed/// DeclhasAttr - returns true if decl Declaration already has the target
1799193326Sed/// attribute.
1800198092Srdivackystatic bool
1801212904SdimDeclHasAttr(const Decl *D, const Attr *A) {
1802239462Sdim  // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1803239462Sdim  // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1804239462Sdim  // responsible for making sure they are consistent.
1805239462Sdim  const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1806239462Sdim  if (AA)
1807239462Sdim    return false;
1808239462Sdim
1809243830Sdim  // The following thread safety attributes can also be duplicated.
1810243830Sdim  switch (A->getKind()) {
1811243830Sdim    case attr::ExclusiveLocksRequired:
1812243830Sdim    case attr::SharedLocksRequired:
1813243830Sdim    case attr::LocksExcluded:
1814243830Sdim    case attr::ExclusiveLockFunction:
1815243830Sdim    case attr::SharedLockFunction:
1816243830Sdim    case attr::UnlockFunction:
1817243830Sdim    case attr::ExclusiveTrylockFunction:
1818243830Sdim    case attr::SharedTrylockFunction:
1819243830Sdim    case attr::GuardedBy:
1820243830Sdim    case attr::PtGuardedBy:
1821243830Sdim    case attr::AcquiredBefore:
1822243830Sdim    case attr::AcquiredAfter:
1823243830Sdim      return false;
1824243830Sdim    default:
1825243830Sdim      ;
1826243830Sdim  }
1827243830Sdim
1828212904Sdim  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1829226633Sdim  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1830212904Sdim  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1831212904Sdim    if ((*i)->getKind() == A->getKind()) {
1832226633Sdim      if (Ann) {
1833226633Sdim        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1834226633Sdim          return true;
1835226633Sdim        continue;
1836226633Sdim      }
1837212904Sdim      // FIXME: Don't hardcode this check
1838212904Sdim      if (OA && isa<OwnershipAttr>(*i))
1839212904Sdim        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1840193326Sed      return true;
1841212904Sdim    }
1842193326Sed
1843193326Sed  return false;
1844193326Sed}
1845193326Sed
1846249423Sdimstatic bool isAttributeTargetADefinition(Decl *D) {
1847249423Sdim  if (VarDecl *VD = dyn_cast<VarDecl>(D))
1848249423Sdim    return VD->isThisDeclarationADefinition();
1849249423Sdim  if (TagDecl *TD = dyn_cast<TagDecl>(D))
1850249423Sdim    return TD->isCompleteDefinition() || TD->isBeingDefined();
1851249423Sdim  return true;
1852249423Sdim}
1853249423Sdim
1854249423Sdim/// Merge alignment attributes from \p Old to \p New, taking into account the
1855249423Sdim/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1856249423Sdim///
1857249423Sdim/// \return \c true if any attributes were added to \p New.
1858249423Sdimstatic bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1859249423Sdim  // Look for alignas attributes on Old, and pick out whichever attribute
1860249423Sdim  // specifies the strictest alignment requirement.
1861249423Sdim  AlignedAttr *OldAlignasAttr = 0;
1862249423Sdim  AlignedAttr *OldStrictestAlignAttr = 0;
1863249423Sdim  unsigned OldAlign = 0;
1864249423Sdim  for (specific_attr_iterator<AlignedAttr>
1865249423Sdim         I = Old->specific_attr_begin<AlignedAttr>(),
1866249423Sdim         E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1867249423Sdim    // FIXME: We have no way of representing inherited dependent alignments
1868249423Sdim    // in a case like:
1869249423Sdim    //   template<int A, int B> struct alignas(A) X;
1870249423Sdim    //   template<int A, int B> struct alignas(B) X {};
1871249423Sdim    // For now, we just ignore any alignas attributes which are not on the
1872249423Sdim    // definition in such a case.
1873249423Sdim    if (I->isAlignmentDependent())
1874249423Sdim      return false;
1875249423Sdim
1876249423Sdim    if (I->isAlignas())
1877249423Sdim      OldAlignasAttr = *I;
1878249423Sdim
1879249423Sdim    unsigned Align = I->getAlignment(S.Context);
1880249423Sdim    if (Align > OldAlign) {
1881249423Sdim      OldAlign = Align;
1882249423Sdim      OldStrictestAlignAttr = *I;
1883249423Sdim    }
1884249423Sdim  }
1885249423Sdim
1886249423Sdim  // Look for alignas attributes on New.
1887249423Sdim  AlignedAttr *NewAlignasAttr = 0;
1888249423Sdim  unsigned NewAlign = 0;
1889249423Sdim  for (specific_attr_iterator<AlignedAttr>
1890249423Sdim         I = New->specific_attr_begin<AlignedAttr>(),
1891249423Sdim         E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1892249423Sdim    if (I->isAlignmentDependent())
1893249423Sdim      return false;
1894249423Sdim
1895249423Sdim    if (I->isAlignas())
1896249423Sdim      NewAlignasAttr = *I;
1897249423Sdim
1898249423Sdim    unsigned Align = I->getAlignment(S.Context);
1899249423Sdim    if (Align > NewAlign)
1900249423Sdim      NewAlign = Align;
1901249423Sdim  }
1902249423Sdim
1903249423Sdim  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1904249423Sdim    // Both declarations have 'alignas' attributes. We require them to match.
1905249423Sdim    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1906249423Sdim    // fall short. (If two declarations both have alignas, they must both match
1907249423Sdim    // every definition, and so must match each other if there is a definition.)
1908249423Sdim
1909249423Sdim    // If either declaration only contains 'alignas(0)' specifiers, then it
1910249423Sdim    // specifies the natural alignment for the type.
1911249423Sdim    if (OldAlign == 0 || NewAlign == 0) {
1912249423Sdim      QualType Ty;
1913249423Sdim      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1914249423Sdim        Ty = VD->getType();
1915249423Sdim      else
1916249423Sdim        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1917249423Sdim
1918249423Sdim      if (OldAlign == 0)
1919249423Sdim        OldAlign = S.Context.getTypeAlign(Ty);
1920249423Sdim      if (NewAlign == 0)
1921249423Sdim        NewAlign = S.Context.getTypeAlign(Ty);
1922249423Sdim    }
1923249423Sdim
1924249423Sdim    if (OldAlign != NewAlign) {
1925249423Sdim      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1926249423Sdim        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1927249423Sdim        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1928249423Sdim      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1929249423Sdim    }
1930249423Sdim  }
1931249423Sdim
1932249423Sdim  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1933249423Sdim    // C++11 [dcl.align]p6:
1934249423Sdim    //   if any declaration of an entity has an alignment-specifier,
1935249423Sdim    //   every defining declaration of that entity shall specify an
1936249423Sdim    //   equivalent alignment.
1937249423Sdim    // C11 6.7.5/7:
1938249423Sdim    //   If the definition of an object does not have an alignment
1939249423Sdim    //   specifier, any other declaration of that object shall also
1940249423Sdim    //   have no alignment specifier.
1941249423Sdim    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1942249423Sdim      << OldAlignasAttr->isC11();
1943249423Sdim    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1944249423Sdim      << OldAlignasAttr->isC11();
1945249423Sdim  }
1946249423Sdim
1947249423Sdim  bool AnyAdded = false;
1948249423Sdim
1949249423Sdim  // Ensure we have an attribute representing the strictest alignment.
1950249423Sdim  if (OldAlign > NewAlign) {
1951249423Sdim    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1952249423Sdim    Clone->setInherited(true);
1953249423Sdim    New->addAttr(Clone);
1954249423Sdim    AnyAdded = true;
1955249423Sdim  }
1956249423Sdim
1957249423Sdim  // Ensure we have an alignas attribute if the old declaration had one.
1958249423Sdim  if (OldAlignasAttr && !NewAlignasAttr &&
1959249423Sdim      !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1960249423Sdim    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1961249423Sdim    Clone->setInherited(true);
1962249423Sdim    New->addAttr(Clone);
1963249423Sdim    AnyAdded = true;
1964249423Sdim  }
1965249423Sdim
1966249423Sdim  return AnyAdded;
1967249423Sdim}
1968249423Sdim
1969249423Sdimstatic bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1970249423Sdim                               bool Override) {
1971239462Sdim  InheritableAttr *NewAttr = NULL;
1972249423Sdim  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1973239462Sdim  if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1974249423Sdim    NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1975249423Sdim                                      AA->getIntroduced(), AA->getDeprecated(),
1976249423Sdim                                      AA->getObsoleted(), AA->getUnavailable(),
1977249423Sdim                                      AA->getMessage(), Override,
1978249423Sdim                                      AttrSpellingListIndex);
1979239462Sdim  else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1980249423Sdim    NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1981249423Sdim                                    AttrSpellingListIndex);
1982249423Sdim  else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1983249423Sdim    NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1984249423Sdim                                        AttrSpellingListIndex);
1985239462Sdim  else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1986249423Sdim    NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1987249423Sdim                                   AttrSpellingListIndex);
1988239462Sdim  else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1989249423Sdim    NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1990249423Sdim                                   AttrSpellingListIndex);
1991239462Sdim  else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1992249423Sdim    NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1993249423Sdim                                FA->getFormatIdx(), FA->getFirstArg(),
1994249423Sdim                                AttrSpellingListIndex);
1995239462Sdim  else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1996249423Sdim    NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1997249423Sdim                                 AttrSpellingListIndex);
1998249423Sdim  else if (isa<AlignedAttr>(Attr))
1999249423Sdim    // AlignedAttrs are handled separately, because we need to handle all
2000249423Sdim    // such attributes on a declaration at the same time.
2001249423Sdim    NewAttr = 0;
2002239462Sdim  else if (!DeclHasAttr(D, Attr))
2003249423Sdim    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2004239462Sdim
2005239462Sdim  if (NewAttr) {
2006239462Sdim    NewAttr->setInherited(true);
2007239462Sdim    D->addAttr(NewAttr);
2008239462Sdim    return true;
2009239462Sdim  }
2010239462Sdim
2011239462Sdim  return false;
2012239462Sdim}
2013239462Sdim
2014239462Sdimstatic const Decl *getDefinition(const Decl *D) {
2015239462Sdim  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2016239462Sdim    return TD->getDefinition();
2017263508Sdim  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2018263508Sdim    const VarDecl *Def = VD->getDefinition();
2019263508Sdim    if (Def)
2020263508Sdim      return Def;
2021263508Sdim    return VD->getActingDefinition();
2022263508Sdim  }
2023239462Sdim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2024239462Sdim    const FunctionDecl* Def;
2025263508Sdim    if (FD->isDefined(Def))
2026239462Sdim      return Def;
2027239462Sdim  }
2028239462Sdim  return NULL;
2029239462Sdim}
2030239462Sdim
2031239462Sdimstatic bool hasAttribute(const Decl *D, attr::Kind Kind) {
2032239462Sdim  for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2033239462Sdim       I != E; ++I) {
2034239462Sdim    Attr *Attribute = *I;
2035239462Sdim    if (Attribute->getKind() == Kind)
2036239462Sdim      return true;
2037239462Sdim  }
2038239462Sdim  return false;
2039239462Sdim}
2040239462Sdim
2041239462Sdim/// checkNewAttributesAfterDef - If we already have a definition, check that
2042239462Sdim/// there are no new attributes in this declaration.
2043239462Sdimstatic void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2044239462Sdim  if (!New->hasAttrs())
2045239462Sdim    return;
2046239462Sdim
2047239462Sdim  const Decl *Def = getDefinition(Old);
2048239462Sdim  if (!Def || Def == New)
2049239462Sdim    return;
2050239462Sdim
2051239462Sdim  AttrVec &NewAttributes = New->getAttrs();
2052239462Sdim  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2053239462Sdim    const Attr *NewAttribute = NewAttributes[I];
2054263508Sdim
2055263508Sdim    if (isa<AliasAttr>(NewAttribute)) {
2056263508Sdim      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2057263508Sdim        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2058263508Sdim      else {
2059263508Sdim        VarDecl *VD = cast<VarDecl>(New);
2060263508Sdim        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2061263508Sdim                                VarDecl::TentativeDefinition
2062263508Sdim                            ? diag::err_alias_after_tentative
2063263508Sdim                            : diag::err_redefinition;
2064263508Sdim        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2065263508Sdim        S.Diag(Def->getLocation(), diag::note_previous_definition);
2066263508Sdim        VD->setInvalidDecl();
2067263508Sdim      }
2068263508Sdim      ++I;
2069263508Sdim      continue;
2070263508Sdim    }
2071263508Sdim
2072263508Sdim    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2073263508Sdim      // Tentative definitions are only interesting for the alias check above.
2074263508Sdim      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2075263508Sdim        ++I;
2076263508Sdim        continue;
2077263508Sdim      }
2078263508Sdim    }
2079263508Sdim
2080239462Sdim    if (hasAttribute(Def, NewAttribute->getKind())) {
2081239462Sdim      ++I;
2082239462Sdim      continue; // regular attr merging will take care of validating this.
2083239462Sdim    }
2084249423Sdim
2085249423Sdim    if (isa<C11NoReturnAttr>(NewAttribute)) {
2086249423Sdim      // C's _Noreturn is allowed to be added to a function after it is defined.
2087249423Sdim      ++I;
2088249423Sdim      continue;
2089249423Sdim    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2090249423Sdim      if (AA->isAlignas()) {
2091249423Sdim        // C++11 [dcl.align]p6:
2092249423Sdim        //   if any declaration of an entity has an alignment-specifier,
2093249423Sdim        //   every defining declaration of that entity shall specify an
2094249423Sdim        //   equivalent alignment.
2095249423Sdim        // C11 6.7.5/7:
2096249423Sdim        //   If the definition of an object does not have an alignment
2097249423Sdim        //   specifier, any other declaration of that object shall also
2098249423Sdim        //   have no alignment specifier.
2099249423Sdim        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2100249423Sdim          << AA->isC11();
2101249423Sdim        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2102249423Sdim          << AA->isC11();
2103249423Sdim        NewAttributes.erase(NewAttributes.begin() + I);
2104249423Sdim        --E;
2105249423Sdim        continue;
2106249423Sdim      }
2107249423Sdim    }
2108249423Sdim
2109239462Sdim    S.Diag(NewAttribute->getLocation(),
2110239462Sdim           diag::warn_attribute_precede_definition);
2111239462Sdim    S.Diag(Def->getLocation(), diag::note_previous_definition);
2112239462Sdim    NewAttributes.erase(NewAttributes.begin() + I);
2113239462Sdim    --E;
2114239462Sdim  }
2115239462Sdim}
2116239462Sdim
2117221345Sdim/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2118249423Sdimvoid Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2119249423Sdim                               AvailabilityMergeKind AMK) {
2120263508Sdim  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2121263508Sdim    UsedAttr *NewAttr = OldAttr->clone(Context);
2122263508Sdim    NewAttr->setInherited(true);
2123263508Sdim    New->addAttr(NewAttr);
2124263508Sdim  }
2125263508Sdim
2126249423Sdim  if (!Old->hasAttrs() && !New->hasAttrs())
2127249423Sdim    return;
2128249423Sdim
2129239462Sdim  // attributes declared post-definition are currently ignored
2130239462Sdim  checkNewAttributesAfterDef(*this, New, Old);
2131239462Sdim
2132234353Sdim  if (!Old->hasAttrs())
2133212904Sdim    return;
2134221345Sdim
2135234353Sdim  bool foundAny = New->hasAttrs();
2136221345Sdim
2137212904Sdim  // Ensure that any moving of objects within the allocated map is done before
2138212904Sdim  // we process them.
2139234353Sdim  if (!foundAny) New->setAttrs(AttrVec());
2140221345Sdim
2141218893Sdim  for (specific_attr_iterator<InheritableAttr>
2142234353Sdim         i = Old->specific_attr_begin<InheritableAttr>(),
2143234353Sdim         e = Old->specific_attr_end<InheritableAttr>();
2144234353Sdim       i != e; ++i) {
2145249423Sdim    bool Override = false;
2146226633Sdim    // Ignore deprecated/unavailable/availability attributes if requested.
2147249423Sdim    if (isa<DeprecatedAttr>(*i) ||
2148249423Sdim        isa<UnavailableAttr>(*i) ||
2149249423Sdim        isa<AvailabilityAttr>(*i)) {
2150249423Sdim      switch (AMK) {
2151249423Sdim      case AMK_None:
2152249423Sdim        continue;
2153226633Sdim
2154249423Sdim      case AMK_Redeclaration:
2155249423Sdim        break;
2156249423Sdim
2157249423Sdim      case AMK_Override:
2158249423Sdim        Override = true;
2159249423Sdim        break;
2160249423Sdim      }
2161249423Sdim    }
2162249423Sdim
2163263508Sdim    // Already handled.
2164263508Sdim    if (isa<UsedAttr>(*i))
2165263508Sdim      continue;
2166263508Sdim
2167249423Sdim    if (mergeDeclAttribute(*this, New, *i, Override))
2168221345Sdim      foundAny = true;
2169193326Sed  }
2170221345Sdim
2171249423Sdim  if (mergeAlignedAttrs(*this, New, Old))
2172249423Sdim    foundAny = true;
2173249423Sdim
2174234353Sdim  if (!foundAny) New->dropAttrs();
2175193326Sed}
2176193326Sed
2177221345Sdim/// mergeParamDeclAttributes - Copy attributes from the old parameter
2178221345Sdim/// to the new one.
2179221345Sdimstatic void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2180221345Sdim                                     const ParmVarDecl *oldDecl,
2181249423Sdim                                     Sema &S) {
2182249423Sdim  // C++11 [dcl.attr.depend]p2:
2183249423Sdim  //   The first declaration of a function shall specify the
2184249423Sdim  //   carries_dependency attribute for its declarator-id if any declaration
2185249423Sdim  //   of the function specifies the carries_dependency attribute.
2186249423Sdim  if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2187249423Sdim      !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2188249423Sdim    S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2189249423Sdim           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2190249423Sdim    // Find the first declaration of the parameter.
2191249423Sdim    // FIXME: Should we build redeclaration chains for function parameters?
2192249423Sdim    const FunctionDecl *FirstFD =
2193263508Sdim      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2194249423Sdim    const ParmVarDecl *FirstVD =
2195249423Sdim      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2196249423Sdim    S.Diag(FirstVD->getLocation(),
2197249423Sdim           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2198249423Sdim  }
2199249423Sdim
2200221345Sdim  if (!oldDecl->hasAttrs())
2201221345Sdim    return;
2202221345Sdim
2203221345Sdim  bool foundAny = newDecl->hasAttrs();
2204221345Sdim
2205221345Sdim  // Ensure that any moving of objects within the allocated map is
2206221345Sdim  // done before we process them.
2207221345Sdim  if (!foundAny) newDecl->setAttrs(AttrVec());
2208221345Sdim
2209221345Sdim  for (specific_attr_iterator<InheritableParamAttr>
2210221345Sdim       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2211221345Sdim       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2212221345Sdim    if (!DeclHasAttr(newDecl, *i)) {
2213249423Sdim      InheritableAttr *newAttr =
2214249423Sdim        cast<InheritableParamAttr>((*i)->clone(S.Context));
2215221345Sdim      newAttr->setInherited(true);
2216221345Sdim      newDecl->addAttr(newAttr);
2217221345Sdim      foundAny = true;
2218221345Sdim    }
2219221345Sdim  }
2220221345Sdim
2221221345Sdim  if (!foundAny) newDecl->dropAttrs();
2222221345Sdim}
2223221345Sdim
2224212904Sdimnamespace {
2225212904Sdim
2226193326Sed/// Used in MergeFunctionDecl to keep track of function parameters in
2227193326Sed/// C.
2228193326Sedstruct GNUCompatibleParamWarning {
2229193326Sed  ParmVarDecl *OldParm;
2230193326Sed  ParmVarDecl *NewParm;
2231193326Sed  QualType PromotedType;
2232193326Sed};
2233193326Sed
2234212904Sdim}
2235200583Srdivacky
2236200583Srdivacky/// getSpecialMember - get the special member enum for a method.
2237207619SrdivackySema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2238200583Srdivacky  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2239223017Sdim    if (Ctor->isDefaultConstructor())
2240223017Sdim      return Sema::CXXDefaultConstructor;
2241223017Sdim
2242201361Srdivacky    if (Ctor->isCopyConstructor())
2243200583Srdivacky      return Sema::CXXCopyConstructor;
2244223017Sdim
2245223017Sdim    if (Ctor->isMoveConstructor())
2246223017Sdim      return Sema::CXXMoveConstructor;
2247223017Sdim  } else if (isa<CXXDestructorDecl>(MD)) {
2248200583Srdivacky    return Sema::CXXDestructor;
2249223017Sdim  } else if (MD->isCopyAssignmentOperator()) {
2250223017Sdim    return Sema::CXXCopyAssignment;
2251226633Sdim  } else if (MD->isMoveAssignmentOperator()) {
2252226633Sdim    return Sema::CXXMoveAssignment;
2253223017Sdim  }
2254223017Sdim
2255223017Sdim  return Sema::CXXInvalid;
2256200583Srdivacky}
2257200583Srdivacky
2258210299Sed/// canRedefineFunction - checks if a function can be redefined. Currently,
2259204643Srdivacky/// only extern inline functions can be redefined, and even then only in
2260204643Srdivacky/// GNU89 mode.
2261204643Srdivackystatic bool canRedefineFunction(const FunctionDecl *FD,
2262204643Srdivacky                                const LangOptions& LangOpts) {
2263224145Sdim  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2264224145Sdim          !LangOpts.CPlusPlus &&
2265204643Srdivacky          FD->isInlineSpecified() &&
2266212904Sdim          FD->getStorageClass() == SC_Extern);
2267204643Srdivacky}
2268204643Srdivacky
2269263508Sdimconst AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2270263508Sdim  const AttributedType *AT = T->getAs<AttributedType>();
2271263508Sdim  while (AT && !AT->isCallingConv())
2272263508Sdim    AT = AT->getModifiedType()->getAs<AttributedType>();
2273263508Sdim  return AT;
2274243830Sdim}
2275243830Sdim
2276249423Sdimtemplate <typename T>
2277249423Sdimstatic bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2278249423Sdim  const DeclContext *DC = Old->getDeclContext();
2279249423Sdim  if (DC->isRecord())
2280249423Sdim    return false;
2281249423Sdim
2282249423Sdim  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2283251662Sdim  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2284249423Sdim    return true;
2285251662Sdim  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2286249423Sdim    return true;
2287249423Sdim  return false;
2288249423Sdim}
2289249423Sdim
2290193326Sed/// MergeFunctionDecl - We just parsed a function 'New' from
2291193326Sed/// declarator D which has the same name and scope as a previous
2292193326Sed/// declaration 'Old'.  Figure out how to resolve this situation,
2293193326Sed/// merging decls or emitting diagnostics as appropriate.
2294193326Sed///
2295193326Sed/// In C++, New and Old must be declarations that are not
2296193326Sed/// overloaded. Use IsOverload to determine whether New and Old are
2297193326Sed/// overloaded, and to select the Old declaration that New should be
2298193326Sed/// merged with.
2299193326Sed///
2300193326Sed/// Returns true if there was an error, false otherwise.
2301263508Sdimbool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2302263508Sdim                             bool MergeTypeWithOld) {
2303193326Sed  // Verify the old decl was also a function.
2304195099Sed  FunctionDecl *Old = 0;
2305198092Srdivacky  if (FunctionTemplateDecl *OldFunctionTemplate
2306195099Sed        = dyn_cast<FunctionTemplateDecl>(OldD))
2307195099Sed    Old = OldFunctionTemplate->getTemplatedDecl();
2308198092Srdivacky  else
2309195099Sed    Old = dyn_cast<FunctionDecl>(OldD);
2310193326Sed  if (!Old) {
2311200583Srdivacky    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2312249423Sdim      if (New->getFriendObjectKind()) {
2313249423Sdim        Diag(New->getLocation(), diag::err_using_decl_friend);
2314249423Sdim        Diag(Shadow->getTargetDecl()->getLocation(),
2315249423Sdim             diag::note_using_decl_target);
2316249423Sdim        Diag(Shadow->getUsingDecl()->getLocation(),
2317249423Sdim             diag::note_using_decl) << 0;
2318249423Sdim        return true;
2319249423Sdim      }
2320249423Sdim
2321200583Srdivacky      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2322200583Srdivacky      Diag(Shadow->getTargetDecl()->getLocation(),
2323200583Srdivacky           diag::note_using_decl_target);
2324200583Srdivacky      Diag(Shadow->getUsingDecl()->getLocation(),
2325200583Srdivacky           diag::note_using_decl) << 0;
2326200583Srdivacky      return true;
2327200583Srdivacky    }
2328200583Srdivacky
2329193326Sed    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2330193326Sed      << New->getDeclName();
2331193326Sed    Diag(OldD->getLocation(), diag::note_previous_definition);
2332193326Sed    return true;
2333193326Sed  }
2334193326Sed
2335263508Sdim  // If the old declaration is invalid, just give up here.
2336263508Sdim  if (Old->isInvalidDecl())
2337263508Sdim    return true;
2338263508Sdim
2339193326Sed  // Determine whether the previous declaration was a definition,
2340193326Sed  // implicit declaration, or a declaration.
2341193326Sed  diag::kind PrevDiag;
2342193326Sed  if (Old->isThisDeclarationADefinition())
2343193326Sed    PrevDiag = diag::note_previous_definition;
2344193326Sed  else if (Old->isImplicit())
2345193326Sed    PrevDiag = diag::note_previous_implicit_declaration;
2346198092Srdivacky  else
2347193326Sed    PrevDiag = diag::note_previous_declaration;
2348198092Srdivacky
2349204643Srdivacky  // Don't complain about this if we're in GNU89 mode and the old function
2350204643Srdivacky  // is an extern inline function.
2351249423Sdim  // Don't complain about specializations. They are not supposed to have
2352249423Sdim  // storage classes.
2353193326Sed  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2354212904Sdim      New->getStorageClass() == SC_Static &&
2355263508Sdim      Old->hasExternalFormalLinkage() &&
2356249423Sdim      !New->getTemplateSpecializationInfo() &&
2357234353Sdim      !canRedefineFunction(Old, getLangOpts())) {
2358234353Sdim    if (getLangOpts().MicrosoftExt) {
2359221345Sdim      Diag(New->getLocation(), diag::warn_static_non_static) << New;
2360221345Sdim      Diag(Old->getLocation(), PrevDiag);
2361221345Sdim    } else {
2362221345Sdim      Diag(New->getLocation(), diag::err_static_non_static) << New;
2363221345Sdim      Diag(Old->getLocation(), PrevDiag);
2364221345Sdim      return true;
2365221345Sdim    }
2366193326Sed  }
2367193326Sed
2368263508Sdim
2369263508Sdim  // If a function is first declared with a calling convention, but is later
2370263508Sdim  // declared or defined without one, all following decls assume the calling
2371263508Sdim  // convention of the first.
2372203955Srdivacky  //
2373243830Sdim  // It's OK if a function is first declared without a calling convention,
2374243830Sdim  // but is later declared or defined with the default calling convention.
2375243830Sdim  //
2376263508Sdim  // To test if either decl has an explicit calling convention, we look for
2377263508Sdim  // AttributedType sugar nodes on the type as written.  If they are missing or
2378263508Sdim  // were canonicalized away, we assume the calling convention was implicit.
2379203955Srdivacky  //
2380203955Srdivacky  // Note also that we DO NOT return at this point, because we still have
2381203955Srdivacky  // other tests to run.
2382263508Sdim  QualType OldQType = Context.getCanonicalType(Old->getType());
2383263508Sdim  QualType NewQType = Context.getCanonicalType(New->getType());
2384218893Sdim  const FunctionType *OldType = cast<FunctionType>(OldQType);
2385263508Sdim  const FunctionType *NewType = cast<FunctionType>(NewQType);
2386218893Sdim  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2387218893Sdim  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2388218893Sdim  bool RequiresAdjustment = false;
2389243830Sdim
2390263508Sdim  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2391263508Sdim    FunctionDecl *First = Old->getFirstDecl();
2392263508Sdim    const FunctionType *FT =
2393263508Sdim        First->getType().getCanonicalType()->castAs<FunctionType>();
2394263508Sdim    FunctionType::ExtInfo FI = FT->getExtInfo();
2395263508Sdim    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2396263508Sdim    if (!NewCCExplicit) {
2397263508Sdim      // Inherit the CC from the previous declaration if it was specified
2398263508Sdim      // there but not here.
2399263508Sdim      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2400263508Sdim      RequiresAdjustment = true;
2401263508Sdim    } else {
2402263508Sdim      // Calling conventions aren't compatible, so complain.
2403263508Sdim      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2404263508Sdim      Diag(New->getLocation(), diag::err_cconv_change)
2405263508Sdim        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2406263508Sdim        << !FirstCCExplicit
2407263508Sdim        << (!FirstCCExplicit ? "" :
2408263508Sdim            FunctionType::getNameForCallConv(FI.getCC()));
2409243830Sdim
2410263508Sdim      // Put the note on the first decl, since it is the one that matters.
2411263508Sdim      Diag(First->getLocation(), diag::note_previous_declaration);
2412263508Sdim      return true;
2413263508Sdim    }
2414203955Srdivacky  }
2415203955Srdivacky
2416203955Srdivacky  // FIXME: diagnose the other way around?
2417218893Sdim  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2418218893Sdim    NewTypeInfo = NewTypeInfo.withNoReturn(true);
2419218893Sdim    RequiresAdjustment = true;
2420203955Srdivacky  }
2421203955Srdivacky
2422210299Sed  // Merge regparm attribute.
2423221345Sdim  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2424221345Sdim      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2425221345Sdim    if (NewTypeInfo.getHasRegParm()) {
2426210299Sed      Diag(New->getLocation(), diag::err_regparm_mismatch)
2427210299Sed        << NewType->getRegParmType()
2428210299Sed        << OldType->getRegParmType();
2429210299Sed      Diag(Old->getLocation(), diag::note_previous_declaration);
2430210299Sed      return true;
2431210299Sed    }
2432218893Sdim
2433218893Sdim    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2434218893Sdim    RequiresAdjustment = true;
2435210299Sed  }
2436218893Sdim
2437226633Sdim  // Merge ns_returns_retained attribute.
2438226633Sdim  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2439226633Sdim    if (NewTypeInfo.getProducesResult()) {
2440226633Sdim      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2441226633Sdim      Diag(Old->getLocation(), diag::note_previous_declaration);
2442226633Sdim      return true;
2443226633Sdim    }
2444226633Sdim
2445226633Sdim    NewTypeInfo = NewTypeInfo.withProducesResult(true);
2446226633Sdim    RequiresAdjustment = true;
2447226633Sdim  }
2448226633Sdim
2449218893Sdim  if (RequiresAdjustment) {
2450263508Sdim    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2451263508Sdim    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2452263508Sdim    New->setType(QualType(AdjustedType, 0));
2453218893Sdim    NewQType = Context.getCanonicalType(New->getType());
2454263508Sdim    NewType = cast<FunctionType>(NewQType);
2455218893Sdim  }
2456249423Sdim
2457249423Sdim  // If this redeclaration makes the function inline, we may need to add it to
2458249423Sdim  // UndefinedButUsed.
2459249423Sdim  if (!Old->isInlined() && New->isInlined() &&
2460249423Sdim      !New->hasAttr<GNUInlineAttr>() &&
2461249423Sdim      (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2462249423Sdim      Old->isUsed(false) &&
2463249423Sdim      !Old->isDefined() && !New->isThisDeclarationADefinition())
2464249423Sdim    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2465249423Sdim                                           SourceLocation()));
2466249423Sdim
2467249423Sdim  // If this redeclaration makes it newly gnu_inline, we don't want to warn
2468249423Sdim  // about it.
2469249423Sdim  if (New->hasAttr<GNUInlineAttr>() &&
2470249423Sdim      Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2471249423Sdim    UndefinedButUsed.erase(Old->getCanonicalDecl());
2472249423Sdim  }
2473210299Sed
2474234353Sdim  if (getLangOpts().CPlusPlus) {
2475193326Sed    // (C++98 13.1p2):
2476193326Sed    //   Certain function declarations cannot be overloaded:
2477198092Srdivacky    //     -- Function declarations that differ only in the return type
2478193326Sed    //        cannot be overloaded.
2479251662Sdim
2480251662Sdim    // Go back to the type source info to compare the declared return types,
2481263508Sdim    // per C++1y [dcl.type.auto]p13:
2482251662Sdim    //   Redeclarations or specializations of a function or function template
2483251662Sdim    //   with a declared return type that uses a placeholder type shall also
2484251662Sdim    //   use that placeholder, not a deduced type.
2485251662Sdim    QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2486251662Sdim      ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2487251662Sdim      : OldType)->getResultType();
2488251662Sdim    QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2489251662Sdim      ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2490251662Sdim      : NewType)->getResultType();
2491208600Srdivacky    QualType ResQT;
2492263508Sdim    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2493263508Sdim        !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2494263508Sdim          New->isLocalExternDecl())) {
2495251662Sdim      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2496251662Sdim          OldDeclaredReturnType->isObjCObjectPointerType())
2497208600Srdivacky        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2498208600Srdivacky      if (ResQT.isNull()) {
2499218893Sdim        if (New->isCXXClassMember() && New->isOutOfLine())
2500218893Sdim          Diag(New->getLocation(),
2501218893Sdim               diag::err_member_def_does_not_match_ret_type) << New;
2502218893Sdim        else
2503218893Sdim          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2504208600Srdivacky        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2505208600Srdivacky        return true;
2506208600Srdivacky      }
2507208600Srdivacky      else
2508208600Srdivacky        NewQType = ResQT;
2509193326Sed    }
2510193326Sed
2511251662Sdim    QualType OldReturnType = OldType->getResultType();
2512251662Sdim    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2513251662Sdim    if (OldReturnType != NewReturnType) {
2514251662Sdim      // If this function has a deduced return type and has already been
2515251662Sdim      // defined, copy the deduced value from the old declaration.
2516251662Sdim      AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2517251662Sdim      if (OldAT && OldAT->isDeduced()) {
2518263508Sdim        New->setType(
2519263508Sdim            SubstAutoType(New->getType(),
2520263508Sdim                          OldAT->isDependentType() ? Context.DependentTy
2521263508Sdim                                                   : OldAT->getDeducedType()));
2522251662Sdim        NewQType = Context.getCanonicalType(
2523263508Sdim            SubstAutoType(NewQType,
2524263508Sdim                          OldAT->isDependentType() ? Context.DependentTy
2525263508Sdim                                                   : OldAT->getDeducedType()));
2526251662Sdim      }
2527251662Sdim    }
2528251662Sdim
2529251662Sdim    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2530251662Sdim    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2531200583Srdivacky    if (OldMethod && NewMethod) {
2532207619Srdivacky      // Preserve triviality.
2533207619Srdivacky      NewMethod->setTrivial(OldMethod->isTrivial());
2534207619Srdivacky
2535226633Sdim      // MSVC allows explicit template specialization at class scope:
2536226633Sdim      // 2 CXMethodDecls referring to the same function will be injected.
2537226633Sdim      // We don't want a redeclartion error.
2538226633Sdim      bool IsClassScopeExplicitSpecialization =
2539226633Sdim                              OldMethod->isFunctionTemplateSpecialization() &&
2540226633Sdim                              NewMethod->isFunctionTemplateSpecialization();
2541207619Srdivacky      bool isFriend = NewMethod->getFriendObjectKind();
2542207619Srdivacky
2543226633Sdim      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2544226633Sdim          !IsClassScopeExplicitSpecialization) {
2545200583Srdivacky        //    -- Member function declarations with the same name and the
2546200583Srdivacky        //       same parameter types cannot be overloaded if any of them
2547200583Srdivacky        //       is a static member function declaration.
2548263508Sdim        if (OldMethod->isStatic() != NewMethod->isStatic()) {
2549200583Srdivacky          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2550200583Srdivacky          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2551200583Srdivacky          return true;
2552200583Srdivacky        }
2553239462Sdim
2554200583Srdivacky        // C++ [class.mem]p1:
2555200583Srdivacky        //   [...] A member shall not be declared twice in the
2556200583Srdivacky        //   member-specification, except that a nested class or member
2557200583Srdivacky        //   class template can be declared and then later defined.
2558239462Sdim        if (ActiveTemplateInstantiations.empty()) {
2559239462Sdim          unsigned NewDiag;
2560239462Sdim          if (isa<CXXConstructorDecl>(OldMethod))
2561239462Sdim            NewDiag = diag::err_constructor_redeclared;
2562239462Sdim          else if (isa<CXXDestructorDecl>(NewMethod))
2563239462Sdim            NewDiag = diag::err_destructor_redeclared;
2564239462Sdim          else if (isa<CXXConversionDecl>(NewMethod))
2565239462Sdim            NewDiag = diag::err_conv_function_redeclared;
2566239462Sdim          else
2567239462Sdim            NewDiag = diag::err_member_redeclared;
2568200583Srdivacky
2569239462Sdim          Diag(New->getLocation(), NewDiag);
2570239462Sdim        } else {
2571239462Sdim          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2572239462Sdim            << New << New->getType();
2573239462Sdim        }
2574193326Sed        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2575207619Srdivacky
2576207619Srdivacky      // Complain if this is an explicit declaration of a special
2577207619Srdivacky      // member that was initially declared implicitly.
2578207619Srdivacky      //
2579207619Srdivacky      // As an exception, it's okay to befriend such methods in order
2580207619Srdivacky      // to permit the implicit constructor/destructor/operator calls.
2581207619Srdivacky      } else if (OldMethod->isImplicit()) {
2582207619Srdivacky        if (isFriend) {
2583207619Srdivacky          NewMethod->setImplicit();
2584207619Srdivacky        } else {
2585200583Srdivacky          Diag(NewMethod->getLocation(),
2586200583Srdivacky               diag::err_definition_of_implicitly_declared_member)
2587207619Srdivacky            << New << getSpecialMember(OldMethod);
2588200583Srdivacky          return true;
2589200583Srdivacky        }
2590239462Sdim      } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2591223017Sdim        Diag(NewMethod->getLocation(),
2592223017Sdim             diag::err_definition_of_explicitly_defaulted_member)
2593223017Sdim          << getSpecialMember(OldMethod);
2594223017Sdim        return true;
2595193326Sed      }
2596193326Sed    }
2597193326Sed
2598249423Sdim    // C++11 [dcl.attr.noreturn]p1:
2599249423Sdim    //   The first declaration of a function shall specify the noreturn
2600249423Sdim    //   attribute if any declaration of that function specifies the noreturn
2601249423Sdim    //   attribute.
2602249423Sdim    if (New->hasAttr<CXX11NoReturnAttr>() &&
2603249423Sdim        !Old->hasAttr<CXX11NoReturnAttr>()) {
2604249423Sdim      Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2605249423Sdim           diag::err_noreturn_missing_on_first_decl);
2606263508Sdim      Diag(Old->getFirstDecl()->getLocation(),
2607249423Sdim           diag::note_noreturn_missing_first_decl);
2608249423Sdim    }
2609249423Sdim
2610249423Sdim    // C++11 [dcl.attr.depend]p2:
2611249423Sdim    //   The first declaration of a function shall specify the
2612249423Sdim    //   carries_dependency attribute for its declarator-id if any declaration
2613249423Sdim    //   of the function specifies the carries_dependency attribute.
2614249423Sdim    if (New->hasAttr<CarriesDependencyAttr>() &&
2615249423Sdim        !Old->hasAttr<CarriesDependencyAttr>()) {
2616249423Sdim      Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2617249423Sdim           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2618263508Sdim      Diag(Old->getFirstDecl()->getLocation(),
2619249423Sdim           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2620249423Sdim    }
2621249423Sdim
2622193326Sed    // (C++98 8.3.5p3):
2623193326Sed    //   All declarations for a function shall agree exactly in both the
2624193326Sed    //   return type and the parameter-type-list.
2625218893Sdim    // We also want to respect all the extended bits except noreturn.
2626218893Sdim
2627218893Sdim    // noreturn should now match unless the old type info didn't have it.
2628218893Sdim    QualType OldQTypeForComparison = OldQType;
2629218893Sdim    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2630218893Sdim      assert(OldQType == QualType(OldType, 0));
2631218893Sdim      const FunctionType *OldTypeForComparison
2632218893Sdim        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2633218893Sdim      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2634218893Sdim      assert(OldQTypeForComparison.isCanonical());
2635218893Sdim    }
2636218893Sdim
2637249423Sdim    if (haveIncompatibleLanguageLinkages(Old, New)) {
2638263508Sdim      // As a special case, retain the language linkage from previous
2639263508Sdim      // declarations of a friend function as an extension.
2640263508Sdim      //
2641263508Sdim      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2642263508Sdim      // and is useful because there's otherwise no way to specify language
2643263508Sdim      // linkage within class scope.
2644263508Sdim      //
2645263508Sdim      // Check cautiously as the friend object kind isn't yet complete.
2646263508Sdim      if (New->getFriendObjectKind() != Decl::FOK_None) {
2647263508Sdim        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2648263508Sdim        Diag(Old->getLocation(), PrevDiag);
2649263508Sdim      } else {
2650263508Sdim        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2651263508Sdim        Diag(Old->getLocation(), PrevDiag);
2652263508Sdim        return true;
2653263508Sdim      }
2654249423Sdim    }
2655249423Sdim
2656218893Sdim    if (OldQTypeForComparison == NewQType)
2657263508Sdim      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2658193326Sed
2659263508Sdim    if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2660263508Sdim        New->isLocalExternDecl()) {
2661263508Sdim      // It's OK if we couldn't merge types for a local function declaraton
2662263508Sdim      // if either the old or new type is dependent. We'll merge the types
2663263508Sdim      // when we instantiate the function.
2664263508Sdim      return false;
2665263508Sdim    }
2666263508Sdim
2667193326Sed    // Fall through for conflicting redeclarations and redefinitions.
2668193326Sed  }
2669193326Sed
2670193326Sed  // C: Function types need to be compatible, not identical. This handles
2671193326Sed  // duplicate function decls like "void f(int); void f(enum X);" properly.
2672234353Sdim  if (!getLangOpts().CPlusPlus &&
2673193326Sed      Context.typesAreCompatible(OldQType, NewQType)) {
2674198092Srdivacky    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2675198092Srdivacky    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2676193326Sed    const FunctionProtoType *OldProto = 0;
2677263508Sdim    if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2678193326Sed        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2679193326Sed      // The old declaration provided a function prototype, but the
2680193326Sed      // new declaration does not. Merge in the prototype.
2681193326Sed      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2682226633Sdim      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2683193326Sed                                                 OldProto->arg_type_end());
2684193326Sed      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2685249423Sdim                                         ParamTypes,
2686218893Sdim                                         OldProto->getExtProtoInfo());
2687193326Sed      New->setType(NewQType);
2688193326Sed      New->setHasInheritedPrototype();
2689193326Sed
2690193326Sed      // Synthesize a parameter for each argument type.
2691226633Sdim      SmallVector<ParmVarDecl*, 16> Params;
2692198092Srdivacky      for (FunctionProtoType::arg_type_iterator
2693198092Srdivacky             ParamType = OldProto->arg_type_begin(),
2694193326Sed             ParamEnd = OldProto->arg_type_end();
2695193326Sed           ParamType != ParamEnd; ++ParamType) {
2696193326Sed        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2697221345Sdim                                                 SourceLocation(),
2698193326Sed                                                 SourceLocation(), 0,
2699200583Srdivacky                                                 *ParamType, /*TInfo=*/0,
2700249423Sdim                                                 SC_None,
2701207619Srdivacky                                                 0);
2702221345Sdim        Param->setScopeInfo(0, Params.size());
2703193326Sed        Param->setImplicit();
2704193326Sed        Params.push_back(Param);
2705193326Sed      }
2706193326Sed
2707226633Sdim      New->setParams(Params);
2708198092Srdivacky    }
2709193326Sed
2710263508Sdim    return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2711193326Sed  }
2712193326Sed
2713193326Sed  // GNU C permits a K&R definition to follow a prototype declaration
2714193326Sed  // if the declared types of the parameters in the K&R definition
2715193326Sed  // match the types in the prototype declaration, even when the
2716193326Sed  // promoted types of the parameters from the K&R definition differ
2717193326Sed  // from the types in the prototype. GCC then keeps the types from
2718193326Sed  // the prototype.
2719193326Sed  //
2720193326Sed  // If a variadic prototype is followed by a non-variadic K&R definition,
2721193326Sed  // the K&R definition becomes variadic.  This is sort of an edge case, but
2722193326Sed  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2723193326Sed  // C99 6.9.1p8.
2724234353Sdim  if (!getLangOpts().CPlusPlus &&
2725193326Sed      Old->hasPrototype() && !New->hasPrototype() &&
2726198092Srdivacky      New->getType()->getAs<FunctionProtoType>() &&
2727193326Sed      Old->getNumParams() == New->getNumParams()) {
2728226633Sdim    SmallVector<QualType, 16> ArgTypes;
2729226633Sdim    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2730198092Srdivacky    const FunctionProtoType *OldProto
2731198092Srdivacky      = Old->getType()->getAs<FunctionProtoType>();
2732198092Srdivacky    const FunctionProtoType *NewProto
2733198092Srdivacky      = New->getType()->getAs<FunctionProtoType>();
2734198092Srdivacky
2735193326Sed    // Determine whether this is the GNU C extension.
2736193326Sed    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2737193326Sed                                               NewProto->getResultType());
2738193326Sed    bool LooseCompatible = !MergedReturn.isNull();
2739198092Srdivacky    for (unsigned Idx = 0, End = Old->getNumParams();
2740193326Sed         LooseCompatible && Idx != End; ++Idx) {
2741193326Sed      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2742193326Sed      ParmVarDecl *NewParm = New->getParamDecl(Idx);
2743198092Srdivacky      if (Context.typesAreCompatible(OldParm->getType(),
2744193326Sed                                     NewProto->getArgType(Idx))) {
2745193326Sed        ArgTypes.push_back(NewParm->getType());
2746193326Sed      } else if (Context.typesAreCompatible(OldParm->getType(),
2747212904Sdim                                            NewParm->getType(),
2748212904Sdim                                            /*CompareUnqualified=*/true)) {
2749198092Srdivacky        GNUCompatibleParamWarning Warn
2750193326Sed          = { OldParm, NewParm, NewProto->getArgType(Idx) };
2751193326Sed        Warnings.push_back(Warn);
2752193326Sed        ArgTypes.push_back(NewParm->getType());
2753193326Sed      } else
2754193326Sed        LooseCompatible = false;
2755193326Sed    }
2756193326Sed
2757193326Sed    if (LooseCompatible) {
2758193326Sed      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2759193326Sed        Diag(Warnings[Warn].NewParm->getLocation(),
2760193326Sed             diag::ext_param_promoted_not_compatible_with_prototype)
2761193326Sed          << Warnings[Warn].PromotedType
2762193326Sed          << Warnings[Warn].OldParm->getType();
2763212904Sdim        if (Warnings[Warn].OldParm->getLocation().isValid())
2764212904Sdim          Diag(Warnings[Warn].OldParm->getLocation(),
2765212904Sdim               diag::note_previous_declaration);
2766193326Sed      }
2767193326Sed
2768263508Sdim      if (MergeTypeWithOld)
2769263508Sdim        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2770263508Sdim                                             OldProto->getExtProtoInfo()));
2771263508Sdim      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2772193326Sed    }
2773193326Sed
2774193326Sed    // Fall through to diagnose conflicting types.
2775193326Sed  }
2776193326Sed
2777251662Sdim  // A function that has already been declared has been redeclared or
2778251662Sdim  // defined with a different type; show an appropriate diagnostic.
2779251662Sdim
2780251662Sdim  // If the previous declaration was an implicitly-generated builtin
2781251662Sdim  // declaration, then at the very least we should use a specialized note.
2782251662Sdim  unsigned BuiltinID;
2783251662Sdim  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2784251662Sdim    // If it's actually a library-defined builtin function like 'malloc'
2785251662Sdim    // or 'printf', just warn about the incompatible redeclaration.
2786193326Sed    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2787193326Sed      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2788193326Sed      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2789193326Sed        << Old << Old->getType();
2790251662Sdim
2791251662Sdim      // If this is a global redeclaration, just forget hereafter
2792251662Sdim      // about the "builtin-ness" of the function.
2793251662Sdim      //
2794251662Sdim      // Doing this for local extern declarations is problematic.  If
2795251662Sdim      // the builtin declaration remains visible, a second invalid
2796251662Sdim      // local declaration will produce a hard error; if it doesn't
2797251662Sdim      // remain visible, a single bogus local redeclaration (which is
2798251662Sdim      // actually only a warning) could break all the downstream code.
2799263508Sdim      if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2800251662Sdim        New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2801251662Sdim
2802193326Sed      return false;
2803193326Sed    }
2804193326Sed
2805193326Sed    PrevDiag = diag::note_previous_builtin_declaration;
2806193326Sed  }
2807193326Sed
2808193326Sed  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2809193326Sed  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2810193326Sed  return true;
2811193326Sed}
2812193326Sed
2813193326Sed/// \brief Completes the merge of two function declarations that are
2814198092Srdivacky/// known to be compatible.
2815193326Sed///
2816193326Sed/// This routine handles the merging of attributes and other
2817263508Sdim/// properties of function declarations from the old declaration to
2818193326Sed/// the new declaration, once we know that New is in fact a
2819193326Sed/// redeclaration of Old.
2820193326Sed///
2821193326Sed/// \returns false
2822234353Sdimbool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2823263508Sdim                                        Scope *S, bool MergeTypeWithOld) {
2824193326Sed  // Merge the attributes
2825234353Sdim  mergeDeclAttributes(New, Old);
2826193326Sed
2827193326Sed  // Merge "pure" flag.
2828193326Sed  if (Old->isPure())
2829193326Sed    New->setPure();
2830193326Sed
2831249423Sdim  // Merge "used" flag.
2832263508Sdim  if (Old->getMostRecentDecl()->isUsed(false))
2833263508Sdim    New->setIsUsed();
2834249423Sdim
2835221345Sdim  // Merge attributes from the parameters.  These can mismatch with K&R
2836221345Sdim  // declarations.
2837221345Sdim  if (New->getNumParams() == Old->getNumParams())
2838221345Sdim    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2839221345Sdim      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2840249423Sdim                               *this);
2841221345Sdim
2842234353Sdim  if (getLangOpts().CPlusPlus)
2843234353Sdim    return MergeCXXFunctionDecl(New, Old, S);
2844193326Sed
2845249423Sdim  // Merge the function types so the we get the composite types for the return
2846263508Sdim  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2847263508Sdim  // was visible.
2848249423Sdim  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2849263508Sdim  if (!Merged.isNull() && MergeTypeWithOld)
2850249423Sdim    New->setType(Merged);
2851249423Sdim
2852193326Sed  return false;
2853193326Sed}
2854193326Sed
2855224145Sdim
2856221345Sdimvoid Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2857234353Sdim                                ObjCMethodDecl *oldMethod) {
2858226633Sdim
2859239462Sdim  // Merge the attributes, including deprecated/unavailable
2860251662Sdim  AvailabilityMergeKind MergeKind =
2861251662Sdim    isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2862251662Sdim                                                   : AMK_Override;
2863251662Sdim  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2864221345Sdim
2865221345Sdim  // Merge attributes from the parameters.
2866239462Sdim  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2867239462Sdim                                       oe = oldMethod->param_end();
2868226633Sdim  for (ObjCMethodDecl::param_iterator
2869221345Sdim         ni = newMethod->param_begin(), ne = newMethod->param_end();
2870239462Sdim       ni != ne && oi != oe; ++ni, ++oi)
2871249423Sdim    mergeParamDeclAttributes(*ni, *oi, *this);
2872226633Sdim
2873249423Sdim  CheckObjCMethodOverride(newMethod, oldMethod);
2874221345Sdim}
2875221345Sdim
2876221345Sdim/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2877221345Sdim/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2878218893Sdim/// emitting diagnostics as appropriate.
2879193326Sed///
2880218893Sdim/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2881234353Sdim/// to here in AddInitializerToDecl. We can't check them before the initializer
2882234353Sdim/// is attached.
2883263508Sdimvoid Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2884263508Sdim                             bool MergeTypeWithOld) {
2885218893Sdim  if (New->isInvalidDecl() || Old->isInvalidDecl())
2886199512Srdivacky    return;
2887198092Srdivacky
2888193326Sed  QualType MergedT;
2889234353Sdim  if (getLangOpts().CPlusPlus) {
2890251662Sdim    if (New->getType()->isUndeducedType()) {
2891218893Sdim      // We don't know what the new type is until the initializer is attached.
2892218893Sdim      return;
2893221345Sdim    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2894221345Sdim      // These could still be something that needs exception specs checked.
2895221345Sdim      return MergeVarDeclExceptionSpecs(New, Old);
2896221345Sdim    }
2897200583Srdivacky    // C++ [basic.link]p10:
2898200583Srdivacky    //   [...] the types specified by all declarations referring to a given
2899200583Srdivacky    //   object or function shall be identical, except that declarations for an
2900200583Srdivacky    //   array object can specify array types that differ by the presence or
2901200583Srdivacky    //   absence of a major array bound (8.3.4).
2902198092Srdivacky    else if (Old->getType()->isIncompleteArrayType() &&
2903198092Srdivacky             New->getType()->isArrayType()) {
2904249423Sdim      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2905249423Sdim      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2906249423Sdim      if (Context.hasSameType(OldArray->getElementType(),
2907249423Sdim                              NewArray->getElementType()))
2908198092Srdivacky        MergedT = New->getType();
2909200583Srdivacky    } else if (Old->getType()->isArrayType() &&
2910263508Sdim               New->getType()->isIncompleteArrayType()) {
2911249423Sdim      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2912249423Sdim      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2913249423Sdim      if (Context.hasSameType(OldArray->getElementType(),
2914249423Sdim                              NewArray->getElementType()))
2915200583Srdivacky        MergedT = Old->getType();
2916263508Sdim    } else if (New->getType()->isObjCObjectPointerType() &&
2917263508Sdim               Old->getType()->isObjCObjectPointerType()) {
2918263508Sdim      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2919263508Sdim                                              Old->getType());
2920198092Srdivacky    }
2921193326Sed  } else {
2922263508Sdim    // C 6.2.7p2:
2923263508Sdim    //   All declarations that refer to the same object or function shall have
2924263508Sdim    //   compatible type.
2925193326Sed    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2926193326Sed  }
2927193326Sed  if (MergedT.isNull()) {
2928263508Sdim    // It's OK if we couldn't merge types if either type is dependent, for a
2929263508Sdim    // block-scope variable. In other cases (static data members of class
2930263508Sdim    // templates, variable templates, ...), we require the types to be
2931263508Sdim    // equivalent.
2932263508Sdim    // FIXME: The C++ standard doesn't say anything about this.
2933263508Sdim    if ((New->getType()->isDependentType() ||
2934263508Sdim         Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2935263508Sdim      // If the old type was dependent, we can't merge with it, so the new type
2936263508Sdim      // becomes dependent for now. We'll reproduce the original type when we
2937263508Sdim      // instantiate the TypeSourceInfo for the variable.
2938263508Sdim      if (!New->getType()->isDependentType() && MergeTypeWithOld)
2939263508Sdim        New->setType(Context.DependentTy);
2940263508Sdim      return;
2941263508Sdim    }
2942263508Sdim
2943263508Sdim    // FIXME: Even if this merging succeeds, some other non-visible declaration
2944263508Sdim    // of this variable might have an incompatible type. For instance:
2945263508Sdim    //
2946263508Sdim    //   extern int arr[];
2947263508Sdim    //   void f() { extern int arr[2]; }
2948263508Sdim    //   void g() { extern int arr[3]; }
2949263508Sdim    //
2950263508Sdim    // Neither C nor C++ requires a diagnostic for this, but we should still try
2951263508Sdim    // to diagnose it.
2952198092Srdivacky    Diag(New->getLocation(), diag::err_redefinition_different_type)
2953243830Sdim      << New->getDeclName() << New->getType() << Old->getType();
2954193326Sed    Diag(Old->getLocation(), diag::note_previous_definition);
2955193326Sed    return New->setInvalidDecl();
2956193326Sed  }
2957249423Sdim
2958249423Sdim  // Don't actually update the type on the new declaration if the old
2959263508Sdim  // declaration was an extern declaration in a different scope.
2960263508Sdim  if (MergeTypeWithOld)
2961249423Sdim    New->setType(MergedT);
2962218893Sdim}
2963193326Sed
2964263508Sdimstatic bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2965263508Sdim                                  LookupResult &Previous) {
2966263508Sdim  // C11 6.2.7p4:
2967263508Sdim  //   For an identifier with internal or external linkage declared
2968263508Sdim  //   in a scope in which a prior declaration of that identifier is
2969263508Sdim  //   visible, if the prior declaration specifies internal or
2970263508Sdim  //   external linkage, the type of the identifier at the later
2971263508Sdim  //   declaration becomes the composite type.
2972263508Sdim  //
2973263508Sdim  // If the variable isn't visible, we do not merge with its type.
2974263508Sdim  if (Previous.isShadowed())
2975263508Sdim    return false;
2976263508Sdim
2977263508Sdim  if (S.getLangOpts().CPlusPlus) {
2978263508Sdim    // C++11 [dcl.array]p3:
2979263508Sdim    //   If there is a preceding declaration of the entity in the same
2980263508Sdim    //   scope in which the bound was specified, an omitted array bound
2981263508Sdim    //   is taken to be the same as in that earlier declaration.
2982263508Sdim    return NewVD->isPreviousDeclInSameBlockScope() ||
2983263508Sdim           (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2984263508Sdim            !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2985263508Sdim  } else {
2986263508Sdim    // If the old declaration was function-local, don't merge with its
2987263508Sdim    // type unless we're in the same function.
2988263508Sdim    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2989263508Sdim           OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2990263508Sdim  }
2991263508Sdim}
2992263508Sdim
2993218893Sdim/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2994218893Sdim/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2995218893Sdim/// situation, merging decls or emitting diagnostics as appropriate.
2996218893Sdim///
2997218893Sdim/// Tentative definition rules (C99 6.9.2p2) are checked by
2998218893Sdim/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2999218893Sdim/// definitions here, since the initializer hasn't been attached.
3000218893Sdim///
3001263508Sdimvoid Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3002218893Sdim  // If the new decl is already invalid, don't do any other checking.
3003218893Sdim  if (New->isInvalidDecl())
3004218893Sdim    return;
3005218893Sdim
3006263508Sdim  // Verify the old decl was also a variable or variable template.
3007218893Sdim  VarDecl *Old = 0;
3008263508Sdim  if (Previous.isSingleResult() &&
3009263508Sdim      (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
3010263508Sdim    if (New->getDescribedVarTemplate())
3011263508Sdim      Old = Old->getDescribedVarTemplate() ? Old : 0;
3012263508Sdim    else
3013263508Sdim      Old = Old->getDescribedVarTemplate() ? 0 : Old;
3014263508Sdim  }
3015263508Sdim  if (!Old) {
3016218893Sdim    Diag(New->getLocation(), diag::err_redefinition_different_kind)
3017218893Sdim      << New->getDeclName();
3018218893Sdim    Diag(Previous.getRepresentativeDecl()->getLocation(),
3019218893Sdim         diag::note_previous_definition);
3020218893Sdim    return New->setInvalidDecl();
3021218893Sdim  }
3022218893Sdim
3023251662Sdim  if (!shouldLinkPossiblyHiddenDecl(Old, New))
3024251662Sdim    return;
3025251662Sdim
3026218893Sdim  // C++ [class.mem]p1:
3027218893Sdim  //   A member shall not be declared twice in the member-specification [...]
3028218893Sdim  //
3029218893Sdim  // Here, we need only consider static data members.
3030218893Sdim  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3031218893Sdim    Diag(New->getLocation(), diag::err_duplicate_member)
3032218893Sdim      << New->getIdentifier();
3033218893Sdim    Diag(Old->getLocation(), diag::note_previous_declaration);
3034218893Sdim    New->setInvalidDecl();
3035218893Sdim  }
3036218893Sdim
3037234353Sdim  mergeDeclAttributes(New, Old);
3038234353Sdim  // Warn if an already-declared variable is made a weak_import in a subsequent
3039234353Sdim  // declaration
3040224145Sdim  if (New->getAttr<WeakImportAttr>() &&
3041224145Sdim      Old->getStorageClass() == SC_None &&
3042224145Sdim      !Old->getAttr<WeakImportAttr>()) {
3043224145Sdim    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3044224145Sdim    Diag(Old->getLocation(), diag::note_previous_definition);
3045224145Sdim    // Remove weak_import attribute on new declaration.
3046224145Sdim    New->dropAttr<WeakImportAttr>();
3047224145Sdim  }
3048218893Sdim
3049218893Sdim  // Merge the types.
3050263508Sdim  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3051263508Sdim
3052218893Sdim  if (New->isInvalidDecl())
3053218893Sdim    return;
3054218893Sdim
3055249423Sdim  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3056212904Sdim  if (New->getStorageClass() == SC_Static &&
3057249423Sdim      !New->isStaticDataMember() &&
3058263508Sdim      Old->hasExternalFormalLinkage()) {
3059193326Sed    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3060193326Sed    Diag(Old->getLocation(), diag::note_previous_definition);
3061193326Sed    return New->setInvalidDecl();
3062193326Sed  }
3063198092Srdivacky  // C99 6.2.2p4:
3064193326Sed  //   For an identifier declared with the storage-class specifier
3065193326Sed  //   extern in a scope in which a prior declaration of that
3066193326Sed  //   identifier is visible,23) if the prior declaration specifies
3067193326Sed  //   internal or external linkage, the linkage of the identifier at
3068193326Sed  //   the later declaration is the same as the linkage specified at
3069193326Sed  //   the prior declaration. If no prior declaration is visible, or
3070193326Sed  //   if the prior declaration specifies no linkage, then the
3071193326Sed  //   identifier has external linkage.
3072193326Sed  if (New->hasExternalStorage() && Old->hasLinkage())
3073193326Sed    /* Okay */;
3074249423Sdim  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3075249423Sdim           !New->isStaticDataMember() &&
3076249423Sdim           Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3077193326Sed    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3078193326Sed    Diag(Old->getLocation(), diag::note_previous_definition);
3079193326Sed    return New->setInvalidDecl();
3080193326Sed  }
3081193326Sed
3082218893Sdim  // Check if extern is followed by non-extern and vice-versa.
3083218893Sdim  if (New->hasExternalStorage() &&
3084218893Sdim      !Old->hasLinkage() && Old->isLocalVarDecl()) {
3085218893Sdim    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3086218893Sdim    Diag(Old->getLocation(), diag::note_previous_definition);
3087218893Sdim    return New->setInvalidDecl();
3088218893Sdim  }
3089249423Sdim  if (Old->hasLinkage() && New->isLocalVarDecl() &&
3090249423Sdim      !New->hasExternalStorage()) {
3091218893Sdim    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3092218893Sdim    Diag(Old->getLocation(), diag::note_previous_definition);
3093218893Sdim    return New->setInvalidDecl();
3094218893Sdim  }
3095218893Sdim
3096193326Sed  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3097198092Srdivacky
3098193326Sed  // FIXME: The test for external storage here seems wrong? We still
3099193326Sed  // need to check for mismatches.
3100193326Sed  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3101193326Sed      // Don't complain about out-of-line definitions of static members.
3102193326Sed      !(Old->getLexicalDeclContext()->isRecord() &&
3103193326Sed        !New->getLexicalDeclContext()->isRecord())) {
3104193326Sed    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3105193326Sed    Diag(Old->getLocation(), diag::note_previous_definition);
3106193326Sed    return New->setInvalidDecl();
3107193326Sed  }
3108193326Sed
3109251662Sdim  if (New->getTLSKind() != Old->getTLSKind()) {
3110251662Sdim    if (!Old->getTLSKind()) {
3111251662Sdim      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3112251662Sdim      Diag(Old->getLocation(), diag::note_previous_declaration);
3113251662Sdim    } else if (!New->getTLSKind()) {
3114251662Sdim      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3115251662Sdim      Diag(Old->getLocation(), diag::note_previous_declaration);
3116251662Sdim    } else {
3117251662Sdim      // Do not allow redeclaration to change the variable between requiring
3118251662Sdim      // static and dynamic initialization.
3119251662Sdim      // FIXME: GCC allows this, but uses the TLS keyword on the first
3120251662Sdim      // declaration to determine the kind. Do we need to be compatible here?
3121251662Sdim      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3122251662Sdim        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3123251662Sdim      Diag(Old->getLocation(), diag::note_previous_declaration);
3124251662Sdim    }
3125193326Sed  }
3126193326Sed
3127203955Srdivacky  // C++ doesn't have tentative definitions, so go right ahead and check here.
3128203955Srdivacky  const VarDecl *Def;
3129234353Sdim  if (getLangOpts().CPlusPlus &&
3130203955Srdivacky      New->isThisDeclarationADefinition() == VarDecl::Definition &&
3131203955Srdivacky      (Def = Old->getDefinition())) {
3132263508Sdim    Diag(New->getLocation(), diag::err_redefinition) << New;
3133203955Srdivacky    Diag(Def->getLocation(), diag::note_previous_definition);
3134203955Srdivacky    New->setInvalidDecl();
3135203955Srdivacky    return;
3136203955Srdivacky  }
3137203955Srdivacky
3138249423Sdim  if (haveIncompatibleLanguageLinkages(Old, New)) {
3139249423Sdim    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3140249423Sdim    Diag(Old->getLocation(), diag::note_previous_definition);
3141249423Sdim    New->setInvalidDecl();
3142249423Sdim    return;
3143249423Sdim  }
3144249423Sdim
3145249423Sdim  // Merge "used" flag.
3146263508Sdim  if (Old->getMostRecentDecl()->isUsed(false))
3147263508Sdim    New->setIsUsed();
3148249423Sdim
3149193326Sed  // Keep a chain of previous declarations.
3150263508Sdim  New->setPreviousDecl(Old);
3151193326Sed
3152202879Srdivacky  // Inherit access appropriately.
3153202879Srdivacky  New->setAccess(Old->getAccess());
3154263508Sdim
3155263508Sdim  if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3156263508Sdim    if (New->isStaticDataMember() && New->isOutOfLine())
3157263508Sdim      VTD->setAccess(New->getAccess());
3158263508Sdim  }
3159202379Srdivacky}
3160198092Srdivacky
3161193326Sed/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3162193326Sed/// no declarator (e.g. "struct foo;") is parsed.
3163212904SdimDecl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3164221345Sdim                                       DeclSpec &DS) {
3165243830Sdim  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3166223017Sdim}
3167223017Sdim
3168263508Sdimstatic void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3169263508Sdim  if (!S.Context.getLangOpts().CPlusPlus)
3170263508Sdim    return;
3171263508Sdim
3172263508Sdim  if (isa<CXXRecordDecl>(Tag->getParent())) {
3173263508Sdim    // If this tag is the direct child of a class, number it if
3174263508Sdim    // it is anonymous.
3175263508Sdim    if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3176263508Sdim      return;
3177263508Sdim    MangleNumberingContext &MCtx =
3178263508Sdim        S.Context.getManglingNumberContext(Tag->getParent());
3179263508Sdim    S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3180263508Sdim    return;
3181263508Sdim  }
3182263508Sdim
3183263508Sdim  // If this tag isn't a direct child of a class, number it if it is local.
3184263508Sdim  Decl *ManglingContextDecl;
3185263508Sdim  if (MangleNumberingContext *MCtx =
3186263508Sdim          S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3187263508Sdim                                          ManglingContextDecl)) {
3188263508Sdim    S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3189263508Sdim  }
3190263508Sdim}
3191263508Sdim
3192223017Sdim/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3193249423Sdim/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3194223017Sdim/// parameters to cope with template friend declarations.
3195223017SdimDecl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3196223017Sdim                                       DeclSpec &DS,
3197249423Sdim                                       MultiTemplateParamsArg TemplateParams,
3198249423Sdim                                       bool IsExplicitInstantiation) {
3199198092Srdivacky  Decl *TagD = 0;
3200193326Sed  TagDecl *Tag = 0;
3201193326Sed  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3202193326Sed      DS.getTypeSpecType() == DeclSpec::TST_struct ||
3203243830Sdim      DS.getTypeSpecType() == DeclSpec::TST_interface ||
3204193326Sed      DS.getTypeSpecType() == DeclSpec::TST_union ||
3205193326Sed      DS.getTypeSpecType() == DeclSpec::TST_enum) {
3206212904Sdim    TagD = DS.getRepAsDecl();
3207198092Srdivacky
3208198092Srdivacky    if (!TagD) // We probably had an error
3209212904Sdim      return 0;
3210193326Sed
3211198092Srdivacky    // Note that the above type specs guarantee that the
3212198092Srdivacky    // type rep is a Decl, whereas in many of the others
3213198092Srdivacky    // it's a Type.
3214234353Sdim    if (isa<TagDecl>(TagD))
3215234353Sdim      Tag = cast<TagDecl>(TagD);
3216234353Sdim    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3217234353Sdim      Tag = CTD->getTemplatedDecl();
3218193326Sed  }
3219193326Sed
3220234353Sdim  if (Tag) {
3221263508Sdim    HandleTagNumbering(*this, Tag);
3222226633Sdim    Tag->setFreeStanding();
3223234353Sdim    if (Tag->isInvalidDecl())
3224234353Sdim      return Tag;
3225234353Sdim  }
3226226633Sdim
3227201361Srdivacky  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3228201361Srdivacky    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3229201361Srdivacky    // or incomplete types shall not be restrict-qualified."
3230201361Srdivacky    if (TypeQuals & DeclSpec::TQ_restrict)
3231201361Srdivacky      Diag(DS.getRestrictSpecLoc(),
3232201361Srdivacky           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3233201361Srdivacky           << DS.getSourceRange();
3234201361Srdivacky  }
3235201361Srdivacky
3236226633Sdim  if (DS.isConstexprSpecified()) {
3237226633Sdim    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3238226633Sdim    // and definitions of functions and variables.
3239226633Sdim    if (Tag)
3240226633Sdim      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3241226633Sdim        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3242226633Sdim            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3243243830Sdim            DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3244243830Sdim            DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3245226633Sdim    else
3246226633Sdim      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3247226633Sdim    // Don't emit warnings after this error.
3248226633Sdim    return TagD;
3249226633Sdim  }
3250226633Sdim
3251249423Sdim  DiagnoseFunctionSpecifiers(DS);
3252249423Sdim
3253198092Srdivacky  if (DS.isFriendSpecified()) {
3254218893Sdim    // If we're dealing with a decl but not a TagDecl, assume that
3255218893Sdim    // whatever routines created it handled the friendship aspect.
3256218893Sdim    if (TagD && !Tag)
3257212904Sdim      return 0;
3258223017Sdim    return ActOnFriendTypeDecl(S, DS, TemplateParams);
3259198092Srdivacky  }
3260221345Sdim
3261249423Sdim  CXXScopeSpec &SS = DS.getTypeSpecScope();
3262249423Sdim  bool IsExplicitSpecialization =
3263249423Sdim    !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3264249423Sdim  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3265249423Sdim      !IsExplicitInstantiation && !IsExplicitSpecialization) {
3266249423Sdim    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3267249423Sdim    // nested-name-specifier unless it is an explicit instantiation
3268249423Sdim    // or an explicit specialization.
3269249423Sdim    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3270249423Sdim    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3271249423Sdim      << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3272249423Sdim          DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3273249423Sdim          DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3274249423Sdim          DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3275249423Sdim      << SS.getRange();
3276249423Sdim    return 0;
3277249423Sdim  }
3278249423Sdim
3279249423Sdim  // Track whether this decl-specifier declares anything.
3280249423Sdim  bool DeclaresAnything = true;
3281249423Sdim
3282249423Sdim  // Handle anonymous struct definitions.
3283193326Sed  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3284226633Sdim    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3285193326Sed        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3286234353Sdim      if (getLangOpts().CPlusPlus ||
3287193326Sed          Record->getDeclContext()->isRecord())
3288208600Srdivacky        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
3289193326Sed
3290249423Sdim      DeclaresAnything = false;
3291193326Sed    }
3292218893Sdim  }
3293193326Sed
3294249423Sdim  // Check for Microsoft C extension: anonymous struct member.
3295234353Sdim  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3296218893Sdim      CurContext->isRecord() &&
3297218893Sdim      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3298218893Sdim    // Handle 2 kinds of anonymous struct:
3299218893Sdim    //   struct STRUCT;
3300218893Sdim    // and
3301218893Sdim    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3302218893Sdim    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3303226633Sdim    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3304218893Sdim        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3305218893Sdim         DS.getRepAsType().get()->isStructureType())) {
3306234353Sdim      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3307218893Sdim        << DS.getSourceRange();
3308218893Sdim      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3309218893Sdim    }
3310193326Sed  }
3311249423Sdim
3312249423Sdim  // Skip all the checks below if we have a type error.
3313249423Sdim  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3314249423Sdim      (TagD && TagD->isInvalidDecl()))
3315249423Sdim    return TagD;
3316249423Sdim
3317249423Sdim  if (getLangOpts().CPlusPlus &&
3318210299Sed      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3319210299Sed    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3320210299Sed      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3321249423Sdim          !Enum->getIdentifier() && !Enum->isInvalidDecl())
3322249423Sdim        DeclaresAnything = false;
3323221345Sdim
3324221345Sdim  if (!DS.isMissingDeclaratorOk()) {
3325249423Sdim    // Customize diagnostic for a typedef missing a name.
3326249423Sdim    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3327234353Sdim      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3328193326Sed        << DS.getSourceRange();
3329249423Sdim    else
3330249423Sdim      DeclaresAnything = false;
3331193326Sed  }
3332198092Srdivacky
3333249423Sdim  if (DS.isModulePrivateSpecified() &&
3334249423Sdim      Tag && Tag->getDeclContext()->isFunctionOrMethod())
3335249423Sdim    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3336249423Sdim      << Tag->getTagKind()
3337249423Sdim      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3338249423Sdim
3339249423Sdim  ActOnDocumentableDecl(TagD);
3340249423Sdim
3341249423Sdim  // C 6.7/2:
3342249423Sdim  //   A declaration [...] shall declare at least a declarator [...], a tag,
3343249423Sdim  //   or the members of an enumeration.
3344249423Sdim  // C++ [dcl.dcl]p3:
3345249423Sdim  //   [If there are no declarators], and except for the declaration of an
3346249423Sdim  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3347249423Sdim  //   names into the program, or shall redeclare a name introduced by a
3348249423Sdim  //   previous declaration.
3349249423Sdim  if (!DeclaresAnything) {
3350249423Sdim    // In C, we allow this as a (popular) extension / bug. Don't bother
3351249423Sdim    // producing further diagnostics for redundant qualifiers after this.
3352249423Sdim    Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3353221345Sdim    return TagD;
3354249423Sdim  }
3355221345Sdim
3356249423Sdim  // C++ [dcl.stc]p1:
3357249423Sdim  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3358249423Sdim  //   init-declarator-list of the declaration shall not be empty.
3359249423Sdim  // C++ [dcl.fct.spec]p1:
3360249423Sdim  //   If a cv-qualifier appears in a decl-specifier-seq, the
3361249423Sdim  //   init-declarator-list of the declaration shall not be empty.
3362249423Sdim  //
3363249423Sdim  // Spurious qualifiers here appear to be valid in C.
3364249423Sdim  unsigned DiagID = diag::warn_standalone_specifier;
3365249423Sdim  if (getLangOpts().CPlusPlus)
3366249423Sdim    DiagID = diag::ext_standalone_specifier;
3367249423Sdim
3368221345Sdim  // Note that a linkage-specification sets a storage class, but
3369221345Sdim  // 'extern "C" struct foo;' is actually valid and not theoretically
3370221345Sdim  // useless.
3371249423Sdim  if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3372249423Sdim    if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3373249423Sdim      Diag(DS.getStorageClassSpecLoc(), DiagID)
3374249423Sdim        << DeclSpec::getSpecifierName(SCS);
3375221345Sdim
3376251662Sdim  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3377251662Sdim    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3378251662Sdim      << DeclSpec::getSpecifierName(TSCS);
3379221345Sdim  if (DS.getTypeQualifiers()) {
3380221345Sdim    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3381249423Sdim      Diag(DS.getConstSpecLoc(), DiagID) << "const";
3382221345Sdim    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3383249423Sdim      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3384221345Sdim    // Restrict is covered above.
3385249423Sdim    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3386249423Sdim      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3387221345Sdim  }
3388221345Sdim
3389234353Sdim  // Warn about ignored type attributes, for example:
3390234353Sdim  // __attribute__((aligned)) struct A;
3391234353Sdim  // Attributes should be placed after tag to apply to type declaration.
3392234353Sdim  if (!DS.getAttributes().empty()) {
3393234353Sdim    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3394234353Sdim    if (TypeSpecType == DeclSpec::TST_class ||
3395234353Sdim        TypeSpecType == DeclSpec::TST_struct ||
3396243830Sdim        TypeSpecType == DeclSpec::TST_interface ||
3397234353Sdim        TypeSpecType == DeclSpec::TST_union ||
3398234353Sdim        TypeSpecType == DeclSpec::TST_enum) {
3399234353Sdim      AttributeList* attrs = DS.getAttributes().getList();
3400234353Sdim      while (attrs) {
3401243830Sdim        Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3402234353Sdim        << attrs->getName()
3403234353Sdim        << (TypeSpecType == DeclSpec::TST_class ? 0 :
3404234353Sdim            TypeSpecType == DeclSpec::TST_struct ? 1 :
3405243830Sdim            TypeSpecType == DeclSpec::TST_union ? 2 :
3406243830Sdim            TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3407234353Sdim        attrs = attrs->getNext();
3408234353Sdim      }
3409234353Sdim    }
3410234353Sdim  }
3411221345Sdim
3412212904Sdim  return TagD;
3413193326Sed}
3414193326Sed
3415201361Srdivacky/// We are trying to inject an anonymous member into the given scope;
3416199512Srdivacky/// check if there's an existing declaration that can't be overloaded.
3417199512Srdivacky///
3418199512Srdivacky/// \return true if this is a forbidden redeclaration
3419201361Srdivackystatic bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3420201361Srdivacky                                         Scope *S,
3421202879Srdivacky                                         DeclContext *Owner,
3422201361Srdivacky                                         DeclarationName Name,
3423201361Srdivacky                                         SourceLocation NameLoc,
3424201361Srdivacky                                         unsigned diagnostic) {
3425201361Srdivacky  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3426201361Srdivacky                 Sema::ForRedeclaration);
3427201361Srdivacky  if (!SemaRef.LookupName(R, S)) return false;
3428199512Srdivacky
3429201361Srdivacky  if (R.getAsSingle<TagDecl>())
3430199512Srdivacky    return false;
3431199512Srdivacky
3432199512Srdivacky  // Pick a representative declaration.
3433201361Srdivacky  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3434218893Sdim  assert(PrevDecl && "Expected a non-null Decl");
3435199512Srdivacky
3436218893Sdim  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3437218893Sdim    return false;
3438218893Sdim
3439201361Srdivacky  SemaRef.Diag(NameLoc, diagnostic) << Name;
3440201361Srdivacky  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3441199512Srdivacky
3442199512Srdivacky  return true;
3443199512Srdivacky}
3444199512Srdivacky
3445193326Sed/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3446193326Sed/// anonymous struct or union AnonRecord into the owning context Owner
3447193326Sed/// and scope S. This routine will be invoked just after we realize
3448193326Sed/// that an unnamed union or struct is actually an anonymous union or
3449193326Sed/// struct, e.g.,
3450193326Sed///
3451193326Sed/// @code
3452193326Sed/// union {
3453193326Sed///   int i;
3454193326Sed///   float f;
3455193326Sed/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3456193326Sed///    // f into the surrounding scope.x
3457193326Sed/// @endcode
3458193326Sed///
3459193326Sed/// This routine is recursive, injecting the names of nested anonymous
3460193326Sed/// structs/unions into the owning context and scope as well.
3461208600Srdivackystatic bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3462263508Sdim                                         DeclContext *Owner,
3463263508Sdim                                         RecordDecl *AnonRecord,
3464263508Sdim                                         AccessSpecifier AS,
3465263508Sdim                                         SmallVectorImpl<NamedDecl *> &Chaining,
3466263508Sdim                                         bool MSAnonStruct) {
3467199512Srdivacky  unsigned diagKind
3468199512Srdivacky    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3469199512Srdivacky                            : diag::err_anonymous_struct_member_redecl;
3470199512Srdivacky
3471193326Sed  bool Invalid = false;
3472218893Sdim
3473218893Sdim  // Look every FieldDecl and IndirectFieldDecl with a name.
3474218893Sdim  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3475218893Sdim                               DEnd = AnonRecord->decls_end();
3476218893Sdim       D != DEnd; ++D) {
3477218893Sdim    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3478218893Sdim        cast<NamedDecl>(*D)->getDeclName()) {
3479218893Sdim      ValueDecl *VD = cast<ValueDecl>(*D);
3480218893Sdim      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3481218893Sdim                                       VD->getLocation(), diagKind)) {
3482193326Sed        // C++ [class.union]p2:
3483193326Sed        //   The names of the members of an anonymous union shall be
3484193326Sed        //   distinct from the names of any other entity in the
3485193326Sed        //   scope in which the anonymous union is declared.
3486193326Sed        Invalid = true;
3487193326Sed      } else {
3488193326Sed        // C++ [class.union]p2:
3489193326Sed        //   For the purpose of name lookup, after the anonymous union
3490193326Sed        //   definition, the members of the anonymous union are
3491193326Sed        //   considered to have been defined in the scope in which the
3492193326Sed        //   anonymous union is declared.
3493218893Sdim        unsigned OldChainingSize = Chaining.size();
3494218893Sdim        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3495218893Sdim          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3496218893Sdim               PE = IF->chain_end(); PI != PE; ++PI)
3497218893Sdim            Chaining.push_back(*PI);
3498218893Sdim        else
3499218893Sdim          Chaining.push_back(VD);
3500208600Srdivacky
3501218893Sdim        assert(Chaining.size() >= 2);
3502218893Sdim        NamedDecl **NamedChain =
3503218893Sdim          new (SemaRef.Context)NamedDecl*[Chaining.size()];
3504218893Sdim        for (unsigned i = 0; i < Chaining.size(); i++)
3505218893Sdim          NamedChain[i] = Chaining[i];
3506218893Sdim
3507218893Sdim        IndirectFieldDecl* IndirectField =
3508218893Sdim          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3509218893Sdim                                    VD->getIdentifier(), VD->getType(),
3510218893Sdim                                    NamedChain, Chaining.size());
3511218893Sdim
3512218893Sdim        IndirectField->setAccess(AS);
3513218893Sdim        IndirectField->setImplicit();
3514218893Sdim        SemaRef.PushOnScopeChains(IndirectField, S);
3515218893Sdim
3516208600Srdivacky        // That includes picking up the appropriate access specifier.
3517218893Sdim        if (AS != AS_none) IndirectField->setAccess(AS);
3518218893Sdim
3519218893Sdim        Chaining.resize(OldChainingSize);
3520193326Sed      }
3521193326Sed    }
3522193326Sed  }
3523193326Sed
3524193326Sed  return Invalid;
3525193326Sed}
3526193326Sed
3527207619Srdivacky/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3528207619Srdivacky/// a VarDecl::StorageClass. Any error reporting is up to the caller:
3529212904Sdim/// illegal input values are mapped to SC_None.
3530212904Sdimstatic StorageClass
3531251662SdimStorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3532251662Sdim  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3533251662Sdim  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3534251662Sdim         "Parser allowed 'typedef' as storage class VarDecl.");
3535207619Srdivacky  switch (StorageClassSpec) {
3536212904Sdim  case DeclSpec::SCS_unspecified:    return SC_None;
3537251662Sdim  case DeclSpec::SCS_extern:
3538251662Sdim    if (DS.isExternInLinkageSpec())
3539251662Sdim      return SC_None;
3540251662Sdim    return SC_Extern;
3541212904Sdim  case DeclSpec::SCS_static:         return SC_Static;
3542212904Sdim  case DeclSpec::SCS_auto:           return SC_Auto;
3543212904Sdim  case DeclSpec::SCS_register:       return SC_Register;
3544212904Sdim  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3545207619Srdivacky    // Illegal SCSs map to None: error reporting is up to the caller.
3546207619Srdivacky  case DeclSpec::SCS_mutable:        // Fall through.
3547212904Sdim  case DeclSpec::SCS_typedef:        return SC_None;
3548207619Srdivacky  }
3549207619Srdivacky  llvm_unreachable("unknown storage class specifier");
3550207619Srdivacky}
3551207619Srdivacky
3552218893Sdim/// BuildAnonymousStructOrUnion - Handle the declaration of an
3553193326Sed/// anonymous structure or union. Anonymous unions are a C++ feature
3554234353Sdim/// (C++ [class.union]) and a C11 feature; anonymous structures
3555234353Sdim/// are a C11 feature and GNU C++ extension.
3556212904SdimDecl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3557212904Sdim                                             AccessSpecifier AS,
3558212904Sdim                                             RecordDecl *Record) {
3559193326Sed  DeclContext *Owner = Record->getDeclContext();
3560193326Sed
3561193326Sed  // Diagnose whether this anonymous struct/union is an extension.
3562234353Sdim  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3563193326Sed    Diag(Record->getLocation(), diag::ext_anonymous_union);
3564234353Sdim  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3565234353Sdim    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3566234353Sdim  else if (!Record->isUnion() && !getLangOpts().C11)
3567234353Sdim    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3568198092Srdivacky
3569193326Sed  // C and C++ require different kinds of checks for anonymous
3570193326Sed  // structs/unions.
3571193326Sed  bool Invalid = false;
3572234353Sdim  if (getLangOpts().CPlusPlus) {
3573193326Sed    const char* PrevSpec = 0;
3574198092Srdivacky    unsigned DiagID;
3575234353Sdim    if (Record->isUnion()) {
3576234353Sdim      // C++ [class.union]p6:
3577234353Sdim      //   Anonymous unions declared in a named namespace or in the
3578234353Sdim      //   global namespace shall be declared static.
3579234353Sdim      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3580234353Sdim          (isa<TranslationUnitDecl>(Owner) ||
3581234353Sdim           (isa<NamespaceDecl>(Owner) &&
3582234353Sdim            cast<NamespaceDecl>(Owner)->getDeclName()))) {
3583234353Sdim        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3584234353Sdim          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3585234353Sdim
3586234353Sdim        // Recover by adding 'static'.
3587234353Sdim        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3588234353Sdim                               PrevSpec, DiagID);
3589234353Sdim      }
3590234353Sdim      // C++ [class.union]p6:
3591234353Sdim      //   A storage class is not allowed in a declaration of an
3592234353Sdim      //   anonymous union in a class scope.
3593234353Sdim      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3594234353Sdim               isa<RecordDecl>(Owner)) {
3595234353Sdim        Diag(DS.getStorageClassSpecLoc(),
3596234353Sdim             diag::err_anonymous_union_with_storage_spec)
3597234353Sdim          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3598234353Sdim
3599234353Sdim        // Recover by removing the storage specifier.
3600234353Sdim        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3601234353Sdim                               SourceLocation(),
3602234353Sdim                               PrevSpec, DiagID);
3603234353Sdim      }
3604198092Srdivacky    }
3605193326Sed
3606223017Sdim    // Ignore const/volatile/restrict qualifiers.
3607223017Sdim    if (DS.getTypeQualifiers()) {
3608223017Sdim      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3609223017Sdim        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3610249423Sdim          << Record->isUnion() << "const"
3611223017Sdim          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3612223017Sdim      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3613249423Sdim        Diag(DS.getVolatileSpecLoc(),
3614234353Sdim             diag::ext_anonymous_struct_union_qualified)
3615249423Sdim          << Record->isUnion() << "volatile"
3616223017Sdim          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3617223017Sdim      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3618249423Sdim        Diag(DS.getRestrictSpecLoc(),
3619234353Sdim             diag::ext_anonymous_struct_union_qualified)
3620249423Sdim          << Record->isUnion() << "restrict"
3621223017Sdim          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3622249423Sdim      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3623249423Sdim        Diag(DS.getAtomicSpecLoc(),
3624249423Sdim             diag::ext_anonymous_struct_union_qualified)
3625249423Sdim          << Record->isUnion() << "_Atomic"
3626249423Sdim          << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3627223017Sdim
3628223017Sdim      DS.ClearTypeQualifiers();
3629223017Sdim    }
3630223017Sdim
3631198092Srdivacky    // C++ [class.union]p2:
3632193326Sed    //   The member-specification of an anonymous union shall only
3633193326Sed    //   define non-static data members. [Note: nested types and
3634193326Sed    //   functions cannot be declared within an anonymous union. ]
3635195341Sed    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3636195341Sed                                 MemEnd = Record->decls_end();
3637193326Sed         Mem != MemEnd; ++Mem) {
3638193326Sed      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3639193326Sed        // C++ [class.union]p3:
3640193326Sed        //   An anonymous union shall not have private or protected
3641193326Sed        //   members (clause 11).
3642208600Srdivacky        assert(FD->getAccess() != AS_none);
3643208600Srdivacky        if (FD->getAccess() != AS_public) {
3644193326Sed          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3645193326Sed            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3646193326Sed          Invalid = true;
3647193326Sed        }
3648212904Sdim
3649223017Sdim        // C++ [class.union]p1
3650223017Sdim        //   An object of a class with a non-trivial constructor, a non-trivial
3651223017Sdim        //   copy constructor, a non-trivial destructor, or a non-trivial copy
3652223017Sdim        //   assignment operator cannot be a member of a union, nor can an
3653223017Sdim        //   array of such objects.
3654234353Sdim        if (CheckNontrivialField(FD))
3655212904Sdim          Invalid = true;
3656193326Sed      } else if ((*Mem)->isImplicit()) {
3657193326Sed        // Any implicit members are fine.
3658193326Sed      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3659193326Sed        // This is a type that showed up in an
3660193326Sed        // elaborated-type-specifier inside the anonymous struct or
3661193326Sed        // union, but which actually declares a type outside of the
3662193326Sed        // anonymous struct or union. It's okay.
3663193326Sed      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3664193326Sed        if (!MemRecord->isAnonymousStructOrUnion() &&
3665193326Sed            MemRecord->getDeclName()) {
3666218893Sdim          // Visual C++ allows type definition in anonymous struct or union.
3667234353Sdim          if (getLangOpts().MicrosoftExt)
3668218893Sdim            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3669218893Sdim              << (int)Record->isUnion();
3670218893Sdim          else {
3671218893Sdim            // This is a nested type declaration.
3672218893Sdim            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3673218893Sdim              << (int)Record->isUnion();
3674218893Sdim            Invalid = true;
3675218893Sdim          }
3676249423Sdim        } else {
3677249423Sdim          // This is an anonymous type definition within another anonymous type.
3678249423Sdim          // This is a popular extension, provided by Plan9, MSVC and GCC, but
3679249423Sdim          // not part of standard C++.
3680249423Sdim          Diag(MemRecord->getLocation(),
3681249423Sdim               diag::ext_anonymous_record_with_anonymous_type)
3682249423Sdim            << (int)Record->isUnion();
3683193326Sed        }
3684210299Sed      } else if (isa<AccessSpecDecl>(*Mem)) {
3685210299Sed        // Any access specifier is fine.
3686193326Sed      } else {
3687193326Sed        // We have something that isn't a non-static data
3688193326Sed        // member. Complain about it.
3689193326Sed        unsigned DK = diag::err_anonymous_record_bad_member;
3690193326Sed        if (isa<TypeDecl>(*Mem))
3691193326Sed          DK = diag::err_anonymous_record_with_type;
3692193326Sed        else if (isa<FunctionDecl>(*Mem))
3693193326Sed          DK = diag::err_anonymous_record_with_function;
3694193326Sed        else if (isa<VarDecl>(*Mem))
3695193326Sed          DK = diag::err_anonymous_record_with_static;
3696218893Sdim
3697218893Sdim        // Visual C++ allows type definition in anonymous struct or union.
3698234353Sdim        if (getLangOpts().MicrosoftExt &&
3699218893Sdim            DK == diag::err_anonymous_record_with_type)
3700218893Sdim          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3701193326Sed            << (int)Record->isUnion();
3702218893Sdim        else {
3703218893Sdim          Diag((*Mem)->getLocation(), DK)
3704218893Sdim              << (int)Record->isUnion();
3705193326Sed          Invalid = true;
3706218893Sdim        }
3707193326Sed      }
3708193326Sed    }
3709198092Srdivacky  }
3710193326Sed
3711193326Sed  if (!Record->isUnion() && !Owner->isRecord()) {
3712193326Sed    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3713234353Sdim      << (int)getLangOpts().CPlusPlus;
3714193326Sed    Invalid = true;
3715193326Sed  }
3716193326Sed
3717198398Srdivacky  // Mock up a declarator.
3718224145Sdim  Declarator Dc(DS, Declarator::MemberContext);
3719210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3720200583Srdivacky  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3721198398Srdivacky
3722198092Srdivacky  // Create a declaration for this anonymous struct/union.
3723193326Sed  NamedDecl *Anon = 0;
3724193326Sed  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3725221345Sdim    Anon = FieldDecl::Create(Context, OwningClass,
3726234353Sdim                             DS.getLocStart(),
3727221345Sdim                             Record->getLocation(),
3728198092Srdivacky                             /*IdentifierInfo=*/0,
3729193326Sed                             Context.getTypeDeclType(Record),
3730200583Srdivacky                             TInfo,
3731223017Sdim                             /*BitWidth=*/0, /*Mutable=*/false,
3732239462Sdim                             /*InitStyle=*/ICIS_NoInit);
3733208600Srdivacky    Anon->setAccess(AS);
3734234353Sdim    if (getLangOpts().CPlusPlus)
3735193326Sed      FieldCollector->Add(cast<FieldDecl>(Anon));
3736193326Sed  } else {
3737207619Srdivacky    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3738251662Sdim    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3739207619Srdivacky    if (SCSpec == DeclSpec::SCS_mutable) {
3740193326Sed      // mutable can only appear on non-static class members, so it's always
3741193326Sed      // an error here
3742193326Sed      Diag(Record->getLocation(), diag::err_mutable_nonmember);
3743193326Sed      Invalid = true;
3744212904Sdim      SC = SC_None;
3745193326Sed    }
3746193326Sed
3747221345Sdim    Anon = VarDecl::Create(Context, Owner,
3748234353Sdim                           DS.getLocStart(),
3749221345Sdim                           Record->getLocation(), /*IdentifierInfo=*/0,
3750193326Sed                           Context.getTypeDeclType(Record),
3751249423Sdim                           TInfo, SC);
3752226633Sdim
3753226633Sdim    // Default-initialize the implicit variable. This initialization will be
3754226633Sdim    // trivial in almost all cases, except if a union member has an in-class
3755226633Sdim    // initializer:
3756226633Sdim    //   union { int n = 0; };
3757226633Sdim    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3758193326Sed  }
3759193326Sed  Anon->setImplicit();
3760193326Sed
3761193326Sed  // Add the anonymous struct/union object to the current
3762193326Sed  // context. We'll be referencing this object when we refer to one of
3763193326Sed  // its members.
3764195341Sed  Owner->addDecl(Anon);
3765207619Srdivacky
3766193326Sed  // Inject the members of the anonymous struct/union into the owning
3767193326Sed  // context and into the identifier resolver chain for name lookup
3768193326Sed  // purposes.
3769226633Sdim  SmallVector<NamedDecl*, 2> Chain;
3770218893Sdim  Chain.push_back(Anon);
3771218893Sdim
3772218893Sdim  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3773218893Sdim                                          Chain, false))
3774193326Sed    Invalid = true;
3775193326Sed
3776193326Sed  // Mark this as an anonymous struct/union type. Note that we do not
3777193326Sed  // do this until after we have already checked and injected the
3778193326Sed  // members of this anonymous struct/union type, because otherwise
3779193326Sed  // the members could be injected twice: once by DeclContext when it
3780193326Sed  // builds its lookup table, and once by
3781198092Srdivacky  // InjectAnonymousStructOrUnionMembers.
3782193326Sed  Record->setAnonymousStructOrUnion(true);
3783193326Sed
3784193326Sed  if (Invalid)
3785193326Sed    Anon->setInvalidDecl();
3786193326Sed
3787212904Sdim  return Anon;
3788193326Sed}
3789193326Sed
3790218893Sdim/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3791218893Sdim/// Microsoft C anonymous structure.
3792218893Sdim/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3793218893Sdim/// Example:
3794218893Sdim///
3795218893Sdim/// struct A { int a; };
3796218893Sdim/// struct B { struct A; int b; };
3797218893Sdim///
3798218893Sdim/// void foo() {
3799218893Sdim///   B var;
3800218893Sdim///   var.a = 3;
3801218893Sdim/// }
3802218893Sdim///
3803218893SdimDecl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3804218893Sdim                                           RecordDecl *Record) {
3805218893Sdim
3806218893Sdim  // If there is no Record, get the record via the typedef.
3807218893Sdim  if (!Record)
3808218893Sdim    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3809193326Sed
3810218893Sdim  // Mock up a declarator.
3811218893Sdim  Declarator Dc(DS, Declarator::TypeNameContext);
3812218893Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3813218893Sdim  assert(TInfo && "couldn't build declarator info for anonymous struct");
3814218893Sdim
3815218893Sdim  // Create a declaration for this anonymous struct.
3816218893Sdim  NamedDecl* Anon = FieldDecl::Create(Context,
3817218893Sdim                             cast<RecordDecl>(CurContext),
3818234353Sdim                             DS.getLocStart(),
3819234353Sdim                             DS.getLocStart(),
3820218893Sdim                             /*IdentifierInfo=*/0,
3821218893Sdim                             Context.getTypeDeclType(Record),
3822218893Sdim                             TInfo,
3823223017Sdim                             /*BitWidth=*/0, /*Mutable=*/false,
3824239462Sdim                             /*InitStyle=*/ICIS_NoInit);
3825218893Sdim  Anon->setImplicit();
3826218893Sdim
3827218893Sdim  // Add the anonymous struct object to the current context.
3828218893Sdim  CurContext->addDecl(Anon);
3829218893Sdim
3830218893Sdim  // Inject the members of the anonymous struct into the current
3831218893Sdim  // context and into the identifier resolver chain for name lookup
3832218893Sdim  // purposes.
3833226633Sdim  SmallVector<NamedDecl*, 2> Chain;
3834218893Sdim  Chain.push_back(Anon);
3835218893Sdim
3836234353Sdim  RecordDecl *RecordDef = Record->getDefinition();
3837234353Sdim  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3838234353Sdim                                                        RecordDef, AS_none,
3839234353Sdim                                                        Chain, true))
3840218893Sdim    Anon->setInvalidDecl();
3841218893Sdim
3842218893Sdim  return Anon;
3843218893Sdim}
3844218893Sdim
3845193326Sed/// GetNameForDeclarator - Determine the full declaration name for the
3846193326Sed/// given Declarator.
3847212904SdimDeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3848198893Srdivacky  return GetNameFromUnqualifiedId(D.getName());
3849198893Srdivacky}
3850193326Sed
3851212904Sdim/// \brief Retrieves the declaration name from a parsed unqualified-id.
3852212904SdimDeclarationNameInfo
3853212904SdimSema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3854212904Sdim  DeclarationNameInfo NameInfo;
3855212904Sdim  NameInfo.setLoc(Name.StartLocation);
3856212904Sdim
3857198893Srdivacky  switch (Name.getKind()) {
3858199990Srdivacky
3859224145Sdim  case UnqualifiedId::IK_ImplicitSelfParam:
3860212904Sdim  case UnqualifiedId::IK_Identifier:
3861212904Sdim    NameInfo.setName(Name.Identifier);
3862212904Sdim    NameInfo.setLoc(Name.StartLocation);
3863212904Sdim    return NameInfo;
3864199990Srdivacky
3865212904Sdim  case UnqualifiedId::IK_OperatorFunctionId:
3866212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3867212904Sdim                                           Name.OperatorFunctionId.Operator));
3868212904Sdim    NameInfo.setLoc(Name.StartLocation);
3869212904Sdim    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3870212904Sdim      = Name.OperatorFunctionId.SymbolLocations[0];
3871212904Sdim    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3872212904Sdim      = Name.EndLocation.getRawEncoding();
3873212904Sdim    return NameInfo;
3874202379Srdivacky
3875212904Sdim  case UnqualifiedId::IK_LiteralOperatorId:
3876212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3877212904Sdim                                                           Name.Identifier));
3878212904Sdim    NameInfo.setLoc(Name.StartLocation);
3879212904Sdim    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3880212904Sdim    return NameInfo;
3881202379Srdivacky
3882212904Sdim  case UnqualifiedId::IK_ConversionFunctionId: {
3883212904Sdim    TypeSourceInfo *TInfo;
3884212904Sdim    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3885212904Sdim    if (Ty.isNull())
3886212904Sdim      return DeclarationNameInfo();
3887212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3888212904Sdim                                               Context.getCanonicalType(Ty)));
3889212904Sdim    NameInfo.setLoc(Name.StartLocation);
3890212904Sdim    NameInfo.setNamedTypeInfo(TInfo);
3891212904Sdim    return NameInfo;
3892212904Sdim  }
3893202379Srdivacky
3894212904Sdim  case UnqualifiedId::IK_ConstructorName: {
3895212904Sdim    TypeSourceInfo *TInfo;
3896212904Sdim    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3897212904Sdim    if (Ty.isNull())
3898212904Sdim      return DeclarationNameInfo();
3899212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3900212904Sdim                                              Context.getCanonicalType(Ty)));
3901212904Sdim    NameInfo.setLoc(Name.StartLocation);
3902212904Sdim    NameInfo.setNamedTypeInfo(TInfo);
3903212904Sdim    return NameInfo;
3904212904Sdim  }
3905202379Srdivacky
3906212904Sdim  case UnqualifiedId::IK_ConstructorTemplateId: {
3907212904Sdim    // In well-formed code, we can only have a constructor
3908212904Sdim    // template-id that refers to the current context, so go there
3909212904Sdim    // to find the actual type being constructed.
3910212904Sdim    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3911212904Sdim    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3912212904Sdim      return DeclarationNameInfo();
3913212904Sdim
3914212904Sdim    // Determine the type of the class being constructed.
3915212904Sdim    QualType CurClassType = Context.getTypeDeclType(CurClass);
3916212904Sdim
3917212904Sdim    // FIXME: Check two things: that the template-id names the same type as
3918212904Sdim    // CurClassType, and that the template-id does not occur when the name
3919212904Sdim    // was qualified.
3920212904Sdim
3921212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3922212904Sdim                                    Context.getCanonicalType(CurClassType)));
3923212904Sdim    NameInfo.setLoc(Name.StartLocation);
3924212904Sdim    // FIXME: should we retrieve TypeSourceInfo?
3925212904Sdim    NameInfo.setNamedTypeInfo(0);
3926212904Sdim    return NameInfo;
3927193326Sed  }
3928212904Sdim
3929212904Sdim  case UnqualifiedId::IK_DestructorName: {
3930212904Sdim    TypeSourceInfo *TInfo;
3931212904Sdim    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3932212904Sdim    if (Ty.isNull())
3933212904Sdim      return DeclarationNameInfo();
3934212904Sdim    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3935212904Sdim                                              Context.getCanonicalType(Ty)));
3936212904Sdim    NameInfo.setLoc(Name.StartLocation);
3937212904Sdim    NameInfo.setNamedTypeInfo(TInfo);
3938212904Sdim    return NameInfo;
3939212904Sdim  }
3940212904Sdim
3941212904Sdim  case UnqualifiedId::IK_TemplateId: {
3942212904Sdim    TemplateName TName = Name.TemplateId->Template.get();
3943212904Sdim    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3944212904Sdim    return Context.getNameForTemplate(TName, TNameLoc);
3945212904Sdim  }
3946212904Sdim
3947212904Sdim  } // switch (Name.getKind())
3948212904Sdim
3949226633Sdim  llvm_unreachable("Unknown name kind");
3950193326Sed}
3951193326Sed
3952226633Sdimstatic QualType getCoreType(QualType Ty) {
3953226633Sdim  do {
3954226633Sdim    if (Ty->isPointerType() || Ty->isReferenceType())
3955226633Sdim      Ty = Ty->getPointeeType();
3956226633Sdim    else if (Ty->isArrayType())
3957226633Sdim      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3958226633Sdim    else
3959226633Sdim      return Ty.withoutLocalFastQualifiers();
3960226633Sdim  } while (true);
3961226633Sdim}
3962226633Sdim
3963226633Sdim/// hasSimilarParameters - Determine whether the C++ functions Declaration
3964226633Sdim/// and Definition have "nearly" matching parameters. This heuristic is
3965226633Sdim/// used to improve diagnostics in the case where an out-of-line function
3966226633Sdim/// definition doesn't match any declaration within the class or namespace.
3967226633Sdim/// Also sets Params to the list of indices to the parameters that differ
3968226633Sdim/// between the declaration and the definition. If hasSimilarParameters
3969226633Sdim/// returns true and Params is empty, then all of the parameters match.
3970226633Sdimstatic bool hasSimilarParameters(ASTContext &Context,
3971193326Sed                                     FunctionDecl *Declaration,
3972226633Sdim                                     FunctionDecl *Definition,
3973249423Sdim                                     SmallVectorImpl<unsigned> &Params) {
3974226633Sdim  Params.clear();
3975193326Sed  if (Declaration->param_size() != Definition->param_size())
3976193326Sed    return false;
3977193326Sed  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3978193326Sed    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3979193326Sed    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3980193326Sed
3981226633Sdim    // The parameter types are identical
3982226633Sdim    if (Context.hasSameType(DefParamTy, DeclParamTy))
3983226633Sdim      continue;
3984226633Sdim
3985226633Sdim    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3986226633Sdim    QualType DefParamBaseTy = getCoreType(DefParamTy);
3987226633Sdim    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3988226633Sdim    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3989226633Sdim
3990226633Sdim    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3991226633Sdim        (DeclTyName && DeclTyName == DefTyName))
3992226633Sdim      Params.push_back(Idx);
3993226633Sdim    else  // The two parameters aren't even close
3994193326Sed      return false;
3995193326Sed  }
3996193326Sed
3997193326Sed  return true;
3998193326Sed}
3999193326Sed
4000207619Srdivacky/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4001207619Srdivacky/// declarator needs to be rebuilt in the current instantiation.
4002207619Srdivacky/// Any bits of declarator which appear before the name are valid for
4003207619Srdivacky/// consideration here.  That's specifically the type in the decl spec
4004207619Srdivacky/// and the base type in any member-pointer chunks.
4005207619Srdivackystatic bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4006207619Srdivacky                                                    DeclarationName Name) {
4007207619Srdivacky  // The types we specifically need to rebuild are:
4008207619Srdivacky  //   - typenames, typeofs, and decltypes
4009207619Srdivacky  //   - types which will become injected class names
4010207619Srdivacky  // Of course, we also need to rebuild any type referencing such a
4011207619Srdivacky  // type.  It's safest to just say "dependent", but we call out a
4012207619Srdivacky  // few cases here.
4013207619Srdivacky
4014207619Srdivacky  DeclSpec &DS = D.getMutableDeclSpec();
4015207619Srdivacky  switch (DS.getTypeSpecType()) {
4016207619Srdivacky  case DeclSpec::TST_typename:
4017207619Srdivacky  case DeclSpec::TST_typeofType:
4018226633Sdim  case DeclSpec::TST_underlyingType:
4019226633Sdim  case DeclSpec::TST_atomic: {
4020207619Srdivacky    // Grab the type from the parser.
4021207619Srdivacky    TypeSourceInfo *TSI = 0;
4022212904Sdim    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4023207619Srdivacky    if (T.isNull() || !T->isDependentType()) break;
4024207619Srdivacky
4025207619Srdivacky    // Make sure there's a type source info.  This isn't really much
4026207619Srdivacky    // of a waste; most dependent types should have type source info
4027207619Srdivacky    // attached already.
4028207619Srdivacky    if (!TSI)
4029207619Srdivacky      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4030207619Srdivacky
4031207619Srdivacky    // Rebuild the type in the current instantiation.
4032207619Srdivacky    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4033207619Srdivacky    if (!TSI) return true;
4034207619Srdivacky
4035207619Srdivacky    // Store the new type back in the decl spec.
4036212904Sdim    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4037212904Sdim    DS.UpdateTypeRep(LocType);
4038207619Srdivacky    break;
4039207619Srdivacky  }
4040207619Srdivacky
4041243830Sdim  case DeclSpec::TST_decltype:
4042212904Sdim  case DeclSpec::TST_typeofExpr: {
4043212904Sdim    Expr *E = DS.getRepAsExpr();
4044212904Sdim    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4045212904Sdim    if (Result.isInvalid()) return true;
4046212904Sdim    DS.UpdateExprRep(Result.get());
4047212904Sdim    break;
4048212904Sdim  }
4049212904Sdim
4050207619Srdivacky  default:
4051207619Srdivacky    // Nothing to do for these decl specs.
4052207619Srdivacky    break;
4053207619Srdivacky  }
4054207619Srdivacky
4055207619Srdivacky  // It doesn't matter what order we do this in.
4056207619Srdivacky  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4057207619Srdivacky    DeclaratorChunk &Chunk = D.getTypeObject(I);
4058207619Srdivacky
4059207619Srdivacky    // The only type information in the declarator which can come
4060207619Srdivacky    // before the declaration name is the base type of a member
4061207619Srdivacky    // pointer.
4062207619Srdivacky    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4063207619Srdivacky      continue;
4064207619Srdivacky
4065207619Srdivacky    // Rebuild the scope specifier in-place.
4066207619Srdivacky    CXXScopeSpec &SS = Chunk.Mem.Scope();
4067207619Srdivacky    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4068207619Srdivacky      return true;
4069207619Srdivacky  }
4070207619Srdivacky
4071207619Srdivacky  return false;
4072207619Srdivacky}
4073207619Srdivacky
4074224145SdimDecl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4075234353Sdim  D.setFunctionDefinitionKind(FDK_Declaration);
4076243830Sdim  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4077234353Sdim
4078234353Sdim  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4079239462Sdim      Dcl && Dcl->getDeclContext()->isFileContext())
4080234353Sdim    Dcl->setTopLevelDeclInObjCContainer();
4081234353Sdim
4082234353Sdim  return Dcl;
4083212904Sdim}
4084193326Sed
4085221345Sdim/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4086221345Sdim///   If T is the name of a class, then each of the following shall have a
4087221345Sdim///   name different from T:
4088221345Sdim///     - every static data member of class T;
4089221345Sdim///     - every member function of class T
4090221345Sdim///     - every member of class T that is itself a type;
4091221345Sdim/// \returns true if the declaration name violates these rules.
4092221345Sdimbool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4093221345Sdim                                   DeclarationNameInfo NameInfo) {
4094221345Sdim  DeclarationName Name = NameInfo.getName();
4095221345Sdim
4096221345Sdim  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4097221345Sdim    if (Record->getIdentifier() && Record->getDeclName() == Name) {
4098221345Sdim      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4099221345Sdim      return true;
4100221345Sdim    }
4101221345Sdim
4102221345Sdim  return false;
4103221345Sdim}
4104234353Sdim
4105234353Sdim/// \brief Diagnose a declaration whose declarator-id has the given
4106234353Sdim/// nested-name-specifier.
4107234353Sdim///
4108234353Sdim/// \param SS The nested-name-specifier of the declarator-id.
4109234353Sdim///
4110234353Sdim/// \param DC The declaration context to which the nested-name-specifier
4111234353Sdim/// resolves.
4112234353Sdim///
4113234353Sdim/// \param Name The name of the entity being declared.
4114234353Sdim///
4115234353Sdim/// \param Loc The location of the name of the entity being declared.
4116234353Sdim///
4117234353Sdim/// \returns true if we cannot safely recover from this error, false otherwise.
4118234353Sdimbool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4119234353Sdim                                        DeclarationName Name,
4120234353Sdim                                      SourceLocation Loc) {
4121234353Sdim  DeclContext *Cur = CurContext;
4122263508Sdim  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4123234353Sdim    Cur = Cur->getParent();
4124221345Sdim
4125234353Sdim  // C++ [dcl.meaning]p1:
4126234353Sdim  //   A declarator-id shall not be qualified except for the definition
4127234353Sdim  //   of a member function (9.3) or static data member (9.4) outside of
4128234353Sdim  //   its class, the definition or explicit instantiation of a function
4129234353Sdim  //   or variable member of a namespace outside of its namespace, or the
4130234353Sdim  //   definition of an explicit specialization outside of its namespace,
4131234353Sdim  //   or the declaration of a friend function that is a member of
4132234353Sdim  //   another class or namespace (11.3). [...]
4133234353Sdim
4134234353Sdim  // The user provided a superfluous scope specifier that refers back to the
4135234353Sdim  // class or namespaces in which the entity is already declared.
4136234353Sdim  //
4137234353Sdim  // class X {
4138234353Sdim  //   void X::f();
4139234353Sdim  // };
4140234353Sdim  if (Cur->Equals(DC)) {
4141243830Sdim    Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4142243830Sdim                                   : diag::err_member_extra_qualification)
4143234353Sdim      << Name << FixItHint::CreateRemoval(SS.getRange());
4144234353Sdim    SS.clear();
4145234353Sdim    return false;
4146234353Sdim  }
4147234353Sdim
4148234353Sdim  // Check whether the qualifying scope encloses the scope of the original
4149234353Sdim  // declaration.
4150234353Sdim  if (!Cur->Encloses(DC)) {
4151234353Sdim    if (Cur->isRecord())
4152234353Sdim      Diag(Loc, diag::err_member_qualification)
4153234353Sdim        << Name << SS.getRange();
4154234353Sdim    else if (isa<TranslationUnitDecl>(DC))
4155234353Sdim      Diag(Loc, diag::err_invalid_declarator_global_scope)
4156234353Sdim        << Name << SS.getRange();
4157234353Sdim    else if (isa<FunctionDecl>(Cur))
4158234353Sdim      Diag(Loc, diag::err_invalid_declarator_in_function)
4159234353Sdim        << Name << SS.getRange();
4160263508Sdim    else if (isa<BlockDecl>(Cur))
4161263508Sdim      Diag(Loc, diag::err_invalid_declarator_in_block)
4162263508Sdim        << Name << SS.getRange();
4163234353Sdim    else
4164234353Sdim      Diag(Loc, diag::err_invalid_declarator_scope)
4165234353Sdim      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4166234353Sdim
4167234353Sdim    return true;
4168234353Sdim  }
4169234353Sdim
4170234353Sdim  if (Cur->isRecord()) {
4171234353Sdim    // Cannot qualify members within a class.
4172234353Sdim    Diag(Loc, diag::err_member_qualification)
4173234353Sdim      << Name << SS.getRange();
4174234353Sdim    SS.clear();
4175234353Sdim
4176234353Sdim    // C++ constructors and destructors with incorrect scopes can break
4177234353Sdim    // our AST invariants by having the wrong underlying types. If
4178234353Sdim    // that's the case, then drop this declaration entirely.
4179234353Sdim    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4180234353Sdim         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4181234353Sdim        !Context.hasSameType(Name.getCXXNameType(),
4182234353Sdim                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4183234353Sdim      return true;
4184234353Sdim
4185234353Sdim    return false;
4186234353Sdim  }
4187234353Sdim
4188234353Sdim  // C++11 [dcl.meaning]p1:
4189234353Sdim  //   [...] "The nested-name-specifier of the qualified declarator-id shall
4190234353Sdim  //   not begin with a decltype-specifer"
4191234353Sdim  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4192234353Sdim  while (SpecLoc.getPrefix())
4193234353Sdim    SpecLoc = SpecLoc.getPrefix();
4194234353Sdim  if (dyn_cast_or_null<DecltypeType>(
4195234353Sdim        SpecLoc.getNestedNameSpecifier()->getAsType()))
4196234353Sdim    Diag(Loc, diag::err_decltype_in_declarator)
4197234353Sdim      << SpecLoc.getTypeLoc().getSourceRange();
4198234353Sdim
4199234353Sdim  return false;
4200234353Sdim}
4201234353Sdim
4202249423SdimNamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4203249423Sdim                                  MultiTemplateParamsArg TemplateParamLists) {
4204212904Sdim  // TODO: consider using NameInfo for diagnostic.
4205212904Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4206212904Sdim  DeclarationName Name = NameInfo.getName();
4207212904Sdim
4208193326Sed  // All of these full declarators require an identifier.  If it doesn't have
4209193326Sed  // one, the ParsedFreeStandingDeclSpec action should be used.
4210193326Sed  if (!Name) {
4211193326Sed    if (!D.isInvalidType())  // Reject this if we think it is valid.
4212234353Sdim      Diag(D.getDeclSpec().getLocStart(),
4213193326Sed           diag::err_declarator_need_ident)
4214193326Sed        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4215212904Sdim    return 0;
4216218893Sdim  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4217218893Sdim    return 0;
4218198092Srdivacky
4219193326Sed  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4220193326Sed  // we find one that is.
4221193326Sed  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4222193326Sed         (S->getFlags() & Scope::TemplateParamScope) != 0)
4223193326Sed    S = S->getParent();
4224198092Srdivacky
4225207619Srdivacky  DeclContext *DC = CurContext;
4226207619Srdivacky  if (D.getCXXScopeSpec().isInvalid())
4227207619Srdivacky    D.setInvalidType();
4228207619Srdivacky  else if (D.getCXXScopeSpec().isSet()) {
4229218893Sdim    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4230218893Sdim                                        UPPC_DeclarationQualifier))
4231218893Sdim      return 0;
4232218893Sdim
4233207619Srdivacky    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4234207619Srdivacky    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4235263508Sdim    if (!DC || isa<EnumDecl>(DC)) {
4236207619Srdivacky      // If we could not compute the declaration context, it's because the
4237207619Srdivacky      // declaration context is dependent but does not refer to a class,
4238207619Srdivacky      // class template, or class template partial specialization. Complain
4239207619Srdivacky      // and return early, to avoid the coming semantic disaster.
4240207619Srdivacky      Diag(D.getIdentifierLoc(),
4241207619Srdivacky           diag::err_template_qualified_declarator_no_match)
4242207619Srdivacky        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4243207619Srdivacky        << D.getCXXScopeSpec().getRange();
4244212904Sdim      return 0;
4245207619Srdivacky    }
4246207619Srdivacky    bool IsDependentContext = DC->isDependentContext();
4247201361Srdivacky
4248207619Srdivacky    if (!IsDependentContext &&
4249207619Srdivacky        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4250212904Sdim      return 0;
4251207619Srdivacky
4252234353Sdim    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4253234353Sdim      Diag(D.getIdentifierLoc(),
4254234353Sdim           diag::err_member_def_undefined_record)
4255234353Sdim        << Name << DC << D.getCXXScopeSpec().getRange();
4256234353Sdim      D.setInvalidType();
4257234353Sdim    } else if (!D.getDeclSpec().isFriendSpecified()) {
4258234353Sdim      if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4259234353Sdim                                      Name, D.getIdentifierLoc())) {
4260234353Sdim        if (DC->isRecord())
4261234353Sdim          return 0;
4262234353Sdim
4263218893Sdim        D.setInvalidType();
4264218893Sdim      }
4265198092Srdivacky    }
4266207619Srdivacky
4267207619Srdivacky    // Check whether we need to rebuild the type of the given
4268207619Srdivacky    // declaration in the current instantiation.
4269207619Srdivacky    if (EnteringContext && IsDependentContext &&
4270207619Srdivacky        TemplateParamLists.size() != 0) {
4271207619Srdivacky      ContextRAII SavedContext(*this, DC);
4272207619Srdivacky      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4273207619Srdivacky        D.setInvalidType();
4274207619Srdivacky    }
4275198092Srdivacky  }
4276221345Sdim
4277221345Sdim  if (DiagnoseClassNameShadow(DC, NameInfo))
4278221345Sdim    // If this is a typedef, we'll end up spewing multiple diagnostics.
4279221345Sdim    // Just return early; it's safer.
4280221345Sdim    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4281221345Sdim      return 0;
4282218893Sdim
4283210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4284210299Sed  QualType R = TInfo->getType();
4285193326Sed
4286218893Sdim  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4287218893Sdim                                      UPPC_DeclarationType))
4288218893Sdim    D.setInvalidType();
4289218893Sdim
4290212904Sdim  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4291199512Srdivacky                        ForRedeclaration);
4292199512Srdivacky
4293193326Sed  // See if this is a redefinition of a variable in the same scope.
4294207619Srdivacky  if (!D.getCXXScopeSpec().isSet()) {
4295199512Srdivacky    bool IsLinkageLookup = false;
4296263508Sdim    bool CreateBuiltins = false;
4297193326Sed
4298193326Sed    // If the declaration we're planning to build will be a function
4299193326Sed    // or object with linkage, then look for another declaration with
4300193326Sed    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4301263508Sdim    //
4302263508Sdim    // If the declaration we're planning to build will be declared with
4303263508Sdim    // external linkage in the translation unit, create any builtin with
4304263508Sdim    // the same name.
4305193326Sed    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4306193326Sed      /* Do nothing*/;
4307263508Sdim    else if (CurContext->isFunctionOrMethod() &&
4308263508Sdim             (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4309263508Sdim              R->isFunctionType())) {
4310199512Srdivacky      IsLinkageLookup = true;
4311263508Sdim      CreateBuiltins =
4312263508Sdim          CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4313263508Sdim    } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4314263508Sdim               D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4315263508Sdim      CreateBuiltins = true;
4316193326Sed
4317199512Srdivacky    if (IsLinkageLookup)
4318199512Srdivacky      Previous.clear(LookupRedeclarationWithLinkage);
4319199512Srdivacky
4320263508Sdim    LookupName(Previous, S, CreateBuiltins);
4321193326Sed  } else { // Something like "int foo::x;"
4322199512Srdivacky    LookupQualifiedName(Previous, DC);
4323198092Srdivacky
4324234353Sdim    // C++ [dcl.meaning]p1:
4325234353Sdim    //   When the declarator-id is qualified, the declaration shall refer to a
4326234353Sdim    //  previously declared member of the class or namespace to which the
4327234353Sdim    //  qualifier refers (or, in the case of a namespace, of an element of the
4328234353Sdim    //  inline namespace set of that namespace (7.3.1)) or to a specialization
4329234353Sdim    //  thereof; [...]
4330193326Sed    //
4331234353Sdim    // Note that we already checked the context above, and that we do not have
4332234353Sdim    // enough information to make sure that Previous contains the declaration
4333234353Sdim    // we want to match. For example, given:
4334193326Sed    //
4335193326Sed    //   class X {
4336193326Sed    //     void f();
4337193326Sed    //     void f(float);
4338193326Sed    //   };
4339193326Sed    //
4340193326Sed    //   void X::f(int) { } // ill-formed
4341193326Sed    //
4342234353Sdim    // In this case, Previous will point to the overload set
4343193326Sed    // containing the two f's declared in X, but neither of them
4344198092Srdivacky    // matches.
4345234353Sdim
4346234353Sdim    // C++ [dcl.meaning]p1:
4347234353Sdim    //   [...] the member shall not merely have been introduced by a
4348234353Sdim    //   using-declaration in the scope of the class or namespace nominated by
4349234353Sdim    //   the nested-name-specifier of the declarator-id.
4350234353Sdim    RemoveUsingDecls(Previous);
4351193326Sed  }
4352193326Sed
4353199512Srdivacky  if (Previous.isSingleResult() &&
4354199512Srdivacky      Previous.getFoundDecl()->isTemplateParameter()) {
4355193326Sed    // Maybe we will complain about the shadowed template parameter.
4356198092Srdivacky    if (!D.isInvalidType())
4357234353Sdim      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4358234353Sdim                                      Previous.getFoundDecl());
4359198092Srdivacky
4360193326Sed    // Just pretend that we didn't see the previous declaration.
4361199512Srdivacky    Previous.clear();
4362193326Sed  }
4363193326Sed
4364193326Sed  // In C++, the previous declaration we find might be a tag type
4365193326Sed  // (class or enum). In this case, the new declaration will hide the
4366193326Sed  // tag type. Note that this does does not apply if we're declaring a
4367193326Sed  // typedef (C++ [dcl.typedef]p4).
4368199512Srdivacky  if (Previous.isSingleTagDecl() &&
4369193326Sed      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4370199512Srdivacky    Previous.clear();
4371193326Sed
4372249423Sdim  // Check that there are no default arguments other than in the parameters
4373249423Sdim  // of a function declaration (C++ only).
4374249423Sdim  if (getLangOpts().CPlusPlus)
4375249423Sdim    CheckExtraCXXDefaultArguments(D);
4376249423Sdim
4377249423Sdim  NamedDecl *New;
4378249423Sdim
4379226633Sdim  bool AddToScope = true;
4380193326Sed  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4381195099Sed    if (TemplateParamLists.size()) {
4382195099Sed      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4383212904Sdim      return 0;
4384195099Sed    }
4385198092Srdivacky
4386226633Sdim    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4387193326Sed  } else if (R->isFunctionType()) {
4388226633Sdim    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4389243830Sdim                                  TemplateParamLists,
4390226633Sdim                                  AddToScope);
4391193326Sed  } else {
4392263508Sdim    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4393263508Sdim                                  AddToScope);
4394193326Sed  }
4395193326Sed
4396193326Sed  if (New == 0)
4397212904Sdim    return 0;
4398198092Srdivacky
4399198092Srdivacky  // If this has an identifier and is not an invalid redeclaration or
4400198092Srdivacky  // function template specialization, add it to the scope stack.
4401226633Sdim  if (New->getDeclName() && AddToScope &&
4402263508Sdim       !(D.isRedeclaration() && New->isInvalidDecl())) {
4403263508Sdim    // Only make a locally-scoped extern declaration visible if it is the first
4404263508Sdim    // declaration of this entity. Qualified lookup for such an entity should
4405263508Sdim    // only find this declaration if there is no visible declaration of it.
4406263508Sdim    bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4407263508Sdim    PushOnScopeChains(New, S, AddToContext);
4408263508Sdim    if (!AddToContext)
4409263508Sdim      CurContext->addHiddenDecl(New);
4410263508Sdim  }
4411198092Srdivacky
4412212904Sdim  return New;
4413193326Sed}
4414193326Sed
4415243830Sdim/// Helper method to turn variable array types into constant array
4416243830Sdim/// types in certain situations which would otherwise be errors (for
4417243830Sdim/// GCC compatibility).
4418193326Sedstatic QualType TryToFixInvalidVariablyModifiedType(QualType T,
4419193326Sed                                                    ASTContext &Context,
4420212904Sdim                                                    bool &SizeIsNegative,
4421212904Sdim                                                    llvm::APSInt &Oversized) {
4422193326Sed  // This method tries to turn a variable array into a constant
4423193326Sed  // array even when the size isn't an ICE.  This is necessary
4424193326Sed  // for compatibility with code that depends on gcc's buggy
4425193326Sed  // constant expression folding, like struct {char x[(int)(char*)2];}
4426193326Sed  SizeIsNegative = false;
4427212904Sdim  Oversized = 0;
4428212904Sdim
4429212904Sdim  if (T->isDependentType())
4430212904Sdim    return QualType();
4431212904Sdim
4432198092Srdivacky  QualifierCollector Qs;
4433198092Srdivacky  const Type *Ty = Qs.strip(T);
4434198092Srdivacky
4435198092Srdivacky  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4436193326Sed    QualType Pointee = PTy->getPointeeType();
4437193326Sed    QualType FixedType =
4438212904Sdim        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4439212904Sdim                                            Oversized);
4440193326Sed    if (FixedType.isNull()) return FixedType;
4441193326Sed    FixedType = Context.getPointerType(FixedType);
4442218893Sdim    return Qs.apply(Context, FixedType);
4443193326Sed  }
4444218893Sdim  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4445218893Sdim    QualType Inner = PTy->getInnerType();
4446218893Sdim    QualType FixedType =
4447218893Sdim        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4448218893Sdim                                            Oversized);
4449218893Sdim    if (FixedType.isNull()) return FixedType;
4450218893Sdim    FixedType = Context.getParenType(FixedType);
4451218893Sdim    return Qs.apply(Context, FixedType);
4452218893Sdim  }
4453193326Sed
4454193326Sed  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4455193326Sed  if (!VLATy)
4456193326Sed    return QualType();
4457193326Sed  // FIXME: We should probably handle this case
4458193326Sed  if (VLATy->getElementType()->isVariablyModifiedType())
4459193326Sed    return QualType();
4460198092Srdivacky
4461234353Sdim  llvm::APSInt Res;
4462193326Sed  if (!VLATy->getSizeExpr() ||
4463234353Sdim      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4464193326Sed    return QualType();
4465193326Sed
4466212904Sdim  // Check whether the array size is negative.
4467212904Sdim  if (Res.isSigned() && Res.isNegative()) {
4468212904Sdim    SizeIsNegative = true;
4469212904Sdim    return QualType();
4470198092Srdivacky  }
4471193326Sed
4472212904Sdim  // Check whether the array is too large to be addressed.
4473212904Sdim  unsigned ActiveSizeBits
4474212904Sdim    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4475212904Sdim                                              Res);
4476212904Sdim  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4477212904Sdim    Oversized = Res;
4478212904Sdim    return QualType();
4479212904Sdim  }
4480212904Sdim
4481212904Sdim  return Context.getConstantArrayType(VLATy->getElementType(),
4482212904Sdim                                      Res, ArrayType::Normal, 0);
4483193326Sed}
4484193326Sed
4485243830Sdimstatic void
4486243830SdimFixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4487249423Sdim  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4488249423Sdim    PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4489249423Sdim    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4490249423Sdim                                      DstPTL.getPointeeLoc());
4491249423Sdim    DstPTL.setStarLoc(SrcPTL.getStarLoc());
4492243830Sdim    return;
4493243830Sdim  }
4494249423Sdim  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4495249423Sdim    ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4496249423Sdim    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4497249423Sdim                                      DstPTL.getInnerLoc());
4498249423Sdim    DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4499249423Sdim    DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4500243830Sdim    return;
4501243830Sdim  }
4502249423Sdim  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4503249423Sdim  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4504249423Sdim  TypeLoc SrcElemTL = SrcATL.getElementLoc();
4505249423Sdim  TypeLoc DstElemTL = DstATL.getElementLoc();
4506243830Sdim  DstElemTL.initializeFullCopy(SrcElemTL);
4507249423Sdim  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4508249423Sdim  DstATL.setSizeExpr(SrcATL.getSizeExpr());
4509249423Sdim  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4510243830Sdim}
4511243830Sdim
4512243830Sdim/// Helper method to turn variable array types into constant array
4513243830Sdim/// types in certain situations which would otherwise be errors (for
4514243830Sdim/// GCC compatibility).
4515243830Sdimstatic TypeSourceInfo*
4516243830SdimTryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4517243830Sdim                                              ASTContext &Context,
4518243830Sdim                                              bool &SizeIsNegative,
4519243830Sdim                                              llvm::APSInt &Oversized) {
4520243830Sdim  QualType FixedTy
4521243830Sdim    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4522243830Sdim                                          SizeIsNegative, Oversized);
4523243830Sdim  if (FixedTy.isNull())
4524243830Sdim    return 0;
4525243830Sdim  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4526243830Sdim  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4527243830Sdim                                    FixedTInfo->getTypeLoc());
4528243830Sdim  return FixedTInfo;
4529243830Sdim}
4530243830Sdim
4531249423Sdim/// \brief Register the given locally-scoped extern "C" declaration so
4532263508Sdim/// that it can be found later for redeclarations. We include any extern "C"
4533263508Sdim/// declaration that is not visible in the translation unit here, not just
4534263508Sdim/// function-scope declarations.
4535198092Srdivackyvoid
4536263508SdimSema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4537263508Sdim  if (!getLangOpts().CPlusPlus &&
4538263508Sdim      ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4539263508Sdim    // Don't need to track declarations in the TU in C.
4540263508Sdim    return;
4541263508Sdim
4542193326Sed  // Note that we have a locally-scoped external with this name.
4543263508Sdim  // FIXME: There can be multiple such declarations if they are functions marked
4544263508Sdim  // __attribute__((overloadable)) declared in function scope in C.
4545249423Sdim  LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4546193326Sed}
4547193326Sed
4548263508SdimNamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4549226633Sdim  if (ExternalSource) {
4550226633Sdim    // Load locally-scoped external decls from the external source.
4551263508Sdim    // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4552226633Sdim    SmallVector<NamedDecl *, 4> Decls;
4553249423Sdim    ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4554226633Sdim    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4555226633Sdim      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4556249423Sdim        = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4557249423Sdim      if (Pos == LocallyScopedExternCDecls.end())
4558249423Sdim        LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4559226633Sdim    }
4560226633Sdim  }
4561263508Sdim
4562263508Sdim  NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4563263508Sdim  return D ? D->getMostRecentDecl() : 0;
4564226633Sdim}
4565226633Sdim
4566193326Sed/// \brief Diagnose function specifiers on a declaration of an identifier that
4567193326Sed/// does not identify a function.
4568249423Sdimvoid Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4569193326Sed  // FIXME: We should probably indicate the identifier in question to avoid
4570193326Sed  // confusion for constructs like "inline int a(), b;"
4571249423Sdim  if (DS.isInlineSpecified())
4572249423Sdim    Diag(DS.getInlineSpecLoc(),
4573193326Sed         diag::err_inline_non_function);
4574193326Sed
4575249423Sdim  if (DS.isVirtualSpecified())
4576249423Sdim    Diag(DS.getVirtualSpecLoc(),
4577193326Sed         diag::err_virtual_non_function);
4578193326Sed
4579249423Sdim  if (DS.isExplicitSpecified())
4580249423Sdim    Diag(DS.getExplicitSpecLoc(),
4581193326Sed         diag::err_explicit_non_function);
4582249423Sdim
4583249423Sdim  if (DS.isNoreturnSpecified())
4584249423Sdim    Diag(DS.getNoreturnSpecLoc(),
4585249423Sdim         diag::err_noreturn_non_function);
4586193326Sed}
4587193326Sed
4588193326SedNamedDecl*
4589193326SedSema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4590226633Sdim                             TypeSourceInfo *TInfo, LookupResult &Previous) {
4591193326Sed  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4592193326Sed  if (D.getCXXScopeSpec().isSet()) {
4593193326Sed    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4594193326Sed      << D.getCXXScopeSpec().getRange();
4595193326Sed    D.setInvalidType();
4596193326Sed    // Pretend we didn't see the scope specifier.
4597206084Srdivacky    DC = CurContext;
4598206084Srdivacky    Previous.clear();
4599193326Sed  }
4600193326Sed
4601249423Sdim  DiagnoseFunctionSpecifiers(D.getDeclSpec());
4602193326Sed
4603226633Sdim  if (D.getDeclSpec().isConstexprSpecified())
4604226633Sdim    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4605226633Sdim      << 1;
4606193326Sed
4607210299Sed  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4608210299Sed    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4609210299Sed      << D.getName().getSourceRange();
4610210299Sed    return 0;
4611210299Sed  }
4612210299Sed
4613226633Sdim  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4614193326Sed  if (!NewTD) return 0;
4615198092Srdivacky
4616193326Sed  // Handle attributes prior to checking for duplicates in MergeVarDecl
4617194613Sed  ProcessDeclAttributes(S, NewTD, D);
4618199512Srdivacky
4619223017Sdim  CheckTypedefForVariablyModifiedType(S, NewTD);
4620223017Sdim
4621226633Sdim  bool Redeclaration = D.isRedeclaration();
4622226633Sdim  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4623226633Sdim  D.setRedeclaration(Redeclaration);
4624226633Sdim  return ND;
4625221345Sdim}
4626221345Sdim
4627223017Sdimvoid
4628223017SdimSema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4629193326Sed  // C99 6.7.7p2: If a typedef name specifies a variably modified type
4630193326Sed  // then it shall have block scope.
4631212904Sdim  // Note that variably modified types must be fixed before merging the decl so
4632212904Sdim  // that redeclarations will match.
4633243830Sdim  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4634243830Sdim  QualType T = TInfo->getType();
4635193326Sed  if (T->isVariablyModifiedType()) {
4636212904Sdim    getCurFunction()->setHasBranchProtectedScope();
4637198092Srdivacky
4638193326Sed    if (S->getFnParent() == 0) {
4639193326Sed      bool SizeIsNegative;
4640212904Sdim      llvm::APSInt Oversized;
4641243830Sdim      TypeSourceInfo *FixedTInfo =
4642243830Sdim        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4643243830Sdim                                                      SizeIsNegative,
4644243830Sdim                                                      Oversized);
4645243830Sdim      if (FixedTInfo) {
4646221345Sdim        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4647243830Sdim        NewTD->setTypeSourceInfo(FixedTInfo);
4648193326Sed      } else {
4649193326Sed        if (SizeIsNegative)
4650221345Sdim          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4651193326Sed        else if (T->isVariableArrayType())
4652221345Sdim          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4653212904Sdim        else if (Oversized.getBoolValue())
4654234353Sdim          Diag(NewTD->getLocation(), diag::err_array_too_large)
4655234353Sdim            << Oversized.toString(10);
4656193326Sed        else
4657221345Sdim          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4658193326Sed        NewTD->setInvalidDecl();
4659193326Sed      }
4660193326Sed    }
4661193326Sed  }
4662223017Sdim}
4663198092Srdivacky
4664223017Sdim
4665223017Sdim/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4666223017Sdim/// declares a typedef-name, either using the 'typedef' type specifier or via
4667223017Sdim/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4668223017SdimNamedDecl*
4669223017SdimSema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4670223017Sdim                           LookupResult &Previous, bool &Redeclaration) {
4671212904Sdim  // Merge the decl with the existing one if appropriate. If the decl is
4672212904Sdim  // in an outer scope, it isn't the same thing.
4673223017Sdim  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4674221345Sdim                       /*ExplicitInstantiationOrSpecialization=*/false);
4675249423Sdim  filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4676212904Sdim  if (!Previous.empty()) {
4677212904Sdim    Redeclaration = true;
4678221345Sdim    MergeTypedefNameDecl(NewTD, Previous);
4679212904Sdim  }
4680212904Sdim
4681198092Srdivacky  // If this is the C FILE type, notify the AST context.
4682198092Srdivacky  if (IdentifierInfo *II = NewTD->getIdentifier())
4683198092Srdivacky    if (!NewTD->isInvalidDecl() &&
4684212904Sdim        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4685198092Srdivacky      if (II->isStr("FILE"))
4686198092Srdivacky        Context.setFILEDecl(NewTD);
4687198092Srdivacky      else if (II->isStr("jmp_buf"))
4688198092Srdivacky        Context.setjmp_bufDecl(NewTD);
4689198092Srdivacky      else if (II->isStr("sigjmp_buf"))
4690198092Srdivacky        Context.setsigjmp_bufDecl(NewTD);
4691227737Sdim      else if (II->isStr("ucontext_t"))
4692227737Sdim        Context.setucontext_tDecl(NewTD);
4693198092Srdivacky    }
4694198092Srdivacky
4695193326Sed  return NewTD;
4696193326Sed}
4697193326Sed
4698193326Sed/// \brief Determines whether the given declaration is an out-of-scope
4699193326Sed/// previous declaration.
4700193326Sed///
4701193326Sed/// This routine should be invoked when name lookup has found a
4702193326Sed/// previous declaration (PrevDecl) that is not in the scope where a
4703193326Sed/// new declaration by the same name is being introduced. If the new
4704193326Sed/// declaration occurs in a local scope, previous declarations with
4705193326Sed/// linkage may still be considered previous declarations (C99
4706193326Sed/// 6.2.2p4-5, C++ [basic.link]p6).
4707193326Sed///
4708193326Sed/// \param PrevDecl the previous declaration found by name
4709193326Sed/// lookup
4710198092Srdivacky///
4711193326Sed/// \param DC the context in which the new declaration is being
4712193326Sed/// declared.
4713193326Sed///
4714193326Sed/// \returns true if PrevDecl is an out-of-scope previous declaration
4715193326Sed/// for a new delcaration with the same name.
4716198092Srdivackystatic bool
4717193326SedisOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4718193326Sed                                ASTContext &Context) {
4719193326Sed  if (!PrevDecl)
4720212904Sdim    return false;
4721193326Sed
4722193326Sed  if (!PrevDecl->hasLinkage())
4723193326Sed    return false;
4724193326Sed
4725234353Sdim  if (Context.getLangOpts().CPlusPlus) {
4726193326Sed    // C++ [basic.link]p6:
4727193326Sed    //   If there is a visible declaration of an entity with linkage
4728193326Sed    //   having the same name and type, ignoring entities declared
4729193326Sed    //   outside the innermost enclosing namespace scope, the block
4730193326Sed    //   scope declaration declares that same entity and receives the
4731193326Sed    //   linkage of the previous declaration.
4732212904Sdim    DeclContext *OuterContext = DC->getRedeclContext();
4733193326Sed    if (!OuterContext->isFunctionOrMethod())
4734193326Sed      // This rule only applies to block-scope declarations.
4735193326Sed      return false;
4736212904Sdim
4737212904Sdim    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4738212904Sdim    if (PrevOuterContext->isRecord())
4739212904Sdim      // We found a member function: ignore it.
4740212904Sdim      return false;
4741212904Sdim
4742212904Sdim    // Find the innermost enclosing namespace for the new and
4743212904Sdim    // previous declarations.
4744212904Sdim    OuterContext = OuterContext->getEnclosingNamespaceContext();
4745212904Sdim    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4746198092Srdivacky
4747212904Sdim    // The previous declaration is in a different namespace, so it
4748212904Sdim    // isn't the same function.
4749212904Sdim    if (!OuterContext->Equals(PrevOuterContext))
4750212904Sdim      return false;
4751193326Sed  }
4752193326Sed
4753193326Sed  return true;
4754193326Sed}
4755193326Sed
4756205219Srdivackystatic void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4757205219Srdivacky  CXXScopeSpec &SS = D.getCXXScopeSpec();
4758205219Srdivacky  if (!SS.isSet()) return;
4759219077Sdim  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4760205219Srdivacky}
4761205219Srdivacky
4762224145Sdimbool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4763224145Sdim  QualType type = decl->getType();
4764224145Sdim  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4765224145Sdim  if (lifetime == Qualifiers::OCL_Autoreleasing) {
4766224145Sdim    // Various kinds of declaration aren't allowed to be __autoreleasing.
4767224145Sdim    unsigned kind = -1U;
4768224145Sdim    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4769224145Sdim      if (var->hasAttr<BlocksAttr>())
4770224145Sdim        kind = 0; // __block
4771224145Sdim      else if (!var->hasLocalStorage())
4772224145Sdim        kind = 1; // global
4773224145Sdim    } else if (isa<ObjCIvarDecl>(decl)) {
4774224145Sdim      kind = 3; // ivar
4775224145Sdim    } else if (isa<FieldDecl>(decl)) {
4776224145Sdim      kind = 2; // field
4777224145Sdim    }
4778224145Sdim
4779224145Sdim    if (kind != -1U) {
4780224145Sdim      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4781224145Sdim        << kind;
4782224145Sdim    }
4783224145Sdim  } else if (lifetime == Qualifiers::OCL_None) {
4784224145Sdim    // Try to infer lifetime.
4785224145Sdim    if (!type->isObjCLifetimeType())
4786224145Sdim      return false;
4787224145Sdim
4788224145Sdim    lifetime = type->getObjCARCImplicitLifetime();
4789224145Sdim    type = Context.getLifetimeQualifiedType(type, lifetime);
4790224145Sdim    decl->setType(type);
4791224145Sdim  }
4792224145Sdim
4793224145Sdim  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4794224145Sdim    // Thread-local variables cannot have lifetime.
4795224145Sdim    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4796251662Sdim        var->getTLSKind()) {
4797224145Sdim      Diag(var->getLocation(), diag::err_arc_thread_ownership)
4798224145Sdim        << var->getType();
4799224145Sdim      return true;
4800224145Sdim    }
4801224145Sdim  }
4802224145Sdim
4803224145Sdim  return false;
4804224145Sdim}
4805224145Sdim
4806249423Sdimstatic void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4807249423Sdim  // 'weak' only applies to declarations with external linkage.
4808249423Sdim  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4809263508Sdim    if (!ND.isExternallyVisible()) {
4810249423Sdim      S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4811249423Sdim      ND.dropAttr<WeakAttr>();
4812249423Sdim    }
4813249423Sdim  }
4814249423Sdim  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4815263508Sdim    if (ND.isExternallyVisible()) {
4816249423Sdim      S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4817249423Sdim      ND.dropAttr<WeakRefAttr>();
4818249423Sdim    }
4819249423Sdim  }
4820263508Sdim
4821263508Sdim  // 'selectany' only applies to externally visible varable declarations.
4822263508Sdim  // It does not apply to functions.
4823263508Sdim  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4824263508Sdim    if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4825263508Sdim      S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4826263508Sdim      ND.dropAttr<SelectAnyAttr>();
4827263508Sdim    }
4828263508Sdim  }
4829249423Sdim}
4830249423Sdim
4831249423Sdim/// Given that we are within the definition of the given function,
4832249423Sdim/// will that definition behave like C99's 'inline', where the
4833249423Sdim/// definition is discarded except for optimization purposes?
4834249423Sdimstatic bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4835249423Sdim  // Try to avoid calling GetGVALinkageForFunction.
4836249423Sdim
4837249423Sdim  // All cases of this require the 'inline' keyword.
4838249423Sdim  if (!FD->isInlined()) return false;
4839249423Sdim
4840249423Sdim  // This is only possible in C++ with the gnu_inline attribute.
4841249423Sdim  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4842249423Sdim    return false;
4843249423Sdim
4844249423Sdim  // Okay, go ahead and call the relatively-more-expensive function.
4845249423Sdim
4846249423Sdim#ifndef NDEBUG
4847249423Sdim  // AST quite reasonably asserts that it's working on a function
4848249423Sdim  // definition.  We don't really have a way to tell it that we're
4849249423Sdim  // currently defining the function, so just lie to it in +Asserts
4850249423Sdim  // builds.  This is an awful hack.
4851249423Sdim  FD->setLazyBody(1);
4852249423Sdim#endif
4853249423Sdim
4854249423Sdim  bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4855249423Sdim
4856249423Sdim#ifndef NDEBUG
4857249423Sdim  FD->setLazyBody(0);
4858249423Sdim#endif
4859249423Sdim
4860249423Sdim  return isC99Inline;
4861249423Sdim}
4862249423Sdim
4863263508Sdim/// Determine whether a variable is extern "C" prior to attaching
4864263508Sdim/// an initializer. We can't just call isExternC() here, because that
4865263508Sdim/// will also compute and cache whether the declaration is externally
4866263508Sdim/// visible, which might change when we attach the initializer.
4867263508Sdim///
4868263508Sdim/// This can only be used if the declaration is known to not be a
4869263508Sdim/// redeclaration of an internal linkage declaration.
4870263508Sdim///
4871263508Sdim/// For instance:
4872263508Sdim///
4873263508Sdim///   auto x = []{};
4874263508Sdim///
4875263508Sdim/// Attaching the initializer here makes this declaration not externally
4876263508Sdim/// visible, because its type has internal linkage.
4877263508Sdim///
4878263508Sdim/// FIXME: This is a hack.
4879263508Sdimtemplate<typename T>
4880263508Sdimstatic bool isIncompleteDeclExternC(Sema &S, const T *D) {
4881263508Sdim  if (S.getLangOpts().CPlusPlus) {
4882263508Sdim    // In C++, the overloadable attribute negates the effects of extern "C".
4883263508Sdim    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4884263508Sdim      return false;
4885263508Sdim  }
4886263508Sdim  return D->isExternC();
4887263508Sdim}
4888263508Sdim
4889249423Sdimstatic bool shouldConsiderLinkage(const VarDecl *VD) {
4890249423Sdim  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4891249423Sdim  if (DC->isFunctionOrMethod())
4892249423Sdim    return VD->hasExternalStorage();
4893249423Sdim  if (DC->isFileContext())
4894249423Sdim    return true;
4895249423Sdim  if (DC->isRecord())
4896249423Sdim    return false;
4897249423Sdim  llvm_unreachable("Unexpected context");
4898249423Sdim}
4899249423Sdim
4900249423Sdimstatic bool shouldConsiderLinkage(const FunctionDecl *FD) {
4901249423Sdim  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4902249423Sdim  if (DC->isFileContext() || DC->isFunctionOrMethod())
4903249423Sdim    return true;
4904249423Sdim  if (DC->isRecord())
4905249423Sdim    return false;
4906249423Sdim  llvm_unreachable("Unexpected context");
4907249423Sdim}
4908249423Sdim
4909263508Sdim/// Adjust the \c DeclContext for a function or variable that might be a
4910263508Sdim/// function-local external declaration.
4911263508Sdimbool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4912263508Sdim  if (!DC->isFunctionOrMethod())
4913263508Sdim    return false;
4914263508Sdim
4915263508Sdim  // If this is a local extern function or variable declared within a function
4916263508Sdim  // template, don't add it into the enclosing namespace scope until it is
4917263508Sdim  // instantiated; it might have a dependent type right now.
4918263508Sdim  if (DC->isDependentContext())
4919263508Sdim    return true;
4920263508Sdim
4921263508Sdim  // C++11 [basic.link]p7:
4922263508Sdim  //   When a block scope declaration of an entity with linkage is not found to
4923263508Sdim  //   refer to some other declaration, then that entity is a member of the
4924263508Sdim  //   innermost enclosing namespace.
4925263508Sdim  //
4926263508Sdim  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4927263508Sdim  // semantically-enclosing namespace, not a lexically-enclosing one.
4928263508Sdim  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4929263508Sdim    DC = DC->getParent();
4930263508Sdim  return true;
4931263508Sdim}
4932263508Sdim
4933263508SdimNamedDecl *
4934218893SdimSema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4935226633Sdim                              TypeSourceInfo *TInfo, LookupResult &Previous,
4936263508Sdim                              MultiTemplateParamsArg TemplateParamLists,
4937263508Sdim                              bool &AddToScope) {
4938226633Sdim  QualType R = TInfo->getType();
4939212904Sdim  DeclarationName Name = GetNameForDeclarator(D).getName();
4940193326Sed
4941207619Srdivacky  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4942251662Sdim  VarDecl::StorageClass SC =
4943251662Sdim    StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4944249423Sdim
4945263508Sdim  DeclContext *OriginalDC = DC;
4946263508Sdim  bool IsLocalExternDecl = SC == SC_Extern &&
4947263508Sdim                           adjustContextForLocalExternDecl(DC);
4948263508Sdim
4949251662Sdim  if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
4950249423Sdim    // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4951249423Sdim    // half array type (unless the cl_khr_fp16 extension is enabled).
4952249423Sdim    if (Context.getBaseElementType(R)->isHalfType()) {
4953249423Sdim      Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4954249423Sdim      D.setInvalidType();
4955249423Sdim    }
4956249423Sdim  }
4957249423Sdim
4958207619Srdivacky  if (SCSpec == DeclSpec::SCS_mutable) {
4959193326Sed    // mutable can only appear on non-static class members, so it's always
4960193326Sed    // an error here
4961193326Sed    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4962193326Sed    D.setInvalidType();
4963212904Sdim    SC = SC_None;
4964193326Sed  }
4965193326Sed
4966263508Sdim  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4967263508Sdim      !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4968263508Sdim                              D.getDeclSpec().getStorageClassSpecLoc())) {
4969263508Sdim    // In C++11, the 'register' storage class specifier is deprecated.
4970263508Sdim    // Suppress the warning in system macros, it's used in macros in some
4971263508Sdim    // popular C system headers, such as in glibc's htonl() macro.
4972263508Sdim    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4973263508Sdim         diag::warn_deprecated_register)
4974263508Sdim      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4975263508Sdim  }
4976251662Sdim
4977193326Sed  IdentifierInfo *II = Name.getAsIdentifierInfo();
4978193326Sed  if (!II) {
4979193326Sed    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4980226633Sdim      << Name;
4981193326Sed    return 0;
4982193326Sed  }
4983193326Sed
4984249423Sdim  DiagnoseFunctionSpecifiers(D.getDeclSpec());
4985193326Sed
4986193326Sed  if (!DC->isRecord() && S->getFnParent() == 0) {
4987193326Sed    // C99 6.9p2: The storage-class specifiers auto and register shall not
4988193326Sed    // appear in the declaration specifiers in an external declaration.
4989212904Sdim    if (SC == SC_Auto || SC == SC_Register) {
4990193326Sed      // If this is a register variable with an asm label specified, then this
4991193326Sed      // is a GNU extension.
4992212904Sdim      if (SC == SC_Register && D.getAsmLabel())
4993193326Sed        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4994193326Sed      else
4995193326Sed        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4996193326Sed      D.setInvalidType();
4997193326Sed    }
4998193326Sed  }
4999263508Sdim
5000234353Sdim  if (getLangOpts().OpenCL) {
5001226633Sdim    // Set up the special work-group-local storage class for variables in the
5002226633Sdim    // OpenCL __local address space.
5003249423Sdim    if (R.getAddressSpace() == LangAS::opencl_local) {
5004226633Sdim      SC = SC_OpenCLWorkGroupLocal;
5005249423Sdim    }
5006249423Sdim
5007249423Sdim    // OpenCL v1.2 s6.9.b p4:
5008249423Sdim    // The sampler type cannot be used with the __local and __global address
5009249423Sdim    // space qualifiers.
5010249423Sdim    if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5011249423Sdim      R.getAddressSpace() == LangAS::opencl_global)) {
5012249423Sdim      Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5013249423Sdim    }
5014249423Sdim
5015249423Sdim    // OpenCL 1.2 spec, p6.9 r:
5016249423Sdim    // The event type cannot be used to declare a program scope variable.
5017249423Sdim    // The event type cannot be used with the __local, __constant and __global
5018249423Sdim    // address space qualifiers.
5019249423Sdim    if (R->isEventT()) {
5020249423Sdim      if (S->getParent() == 0) {
5021249423Sdim        Diag(D.getLocStart(), diag::err_event_t_global_var);
5022249423Sdim        D.setInvalidType();
5023249423Sdim      }
5024249423Sdim
5025249423Sdim      if (R.getAddressSpace()) {
5026249423Sdim        Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5027249423Sdim        D.setInvalidType();
5028249423Sdim      }
5029249423Sdim    }
5030226633Sdim  }
5031226633Sdim
5032263508Sdim  bool IsExplicitSpecialization = false;
5033263508Sdim  bool IsVariableTemplateSpecialization = false;
5034263508Sdim  bool IsPartialSpecialization = false;
5035263508Sdim  bool IsVariableTemplate = false;
5036263508Sdim  VarTemplateDecl *PrevVarTemplate = 0;
5037263508Sdim  VarDecl *NewVD = 0;
5038263508Sdim  VarTemplateDecl *NewTemplate = 0;
5039234353Sdim  if (!getLangOpts().CPlusPlus) {
5040234353Sdim    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5041221345Sdim                            D.getIdentifierLoc(), II,
5042249423Sdim                            R, TInfo, SC);
5043218893Sdim
5044218893Sdim    if (D.isInvalidType())
5045218893Sdim      NewVD->setInvalidDecl();
5046218893Sdim  } else {
5047263508Sdim    bool Invalid = false;
5048263508Sdim
5049218893Sdim    if (DC->isRecord() && !CurContext->isRecord()) {
5050218893Sdim      // This is an out-of-line definition of a static data member.
5051263508Sdim      switch (SC) {
5052263508Sdim      case SC_None:
5053263508Sdim        break;
5054263508Sdim      case SC_Static:
5055218893Sdim        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5056218893Sdim             diag::err_static_out_of_line)
5057218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5058263508Sdim        break;
5059263508Sdim      case SC_Auto:
5060263508Sdim      case SC_Register:
5061263508Sdim      case SC_Extern:
5062263508Sdim        // [dcl.stc] p2: The auto or register specifiers shall be applied only
5063263508Sdim        // to names of variables declared in a block or to function parameters.
5064263508Sdim        // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5065263508Sdim        // of class members
5066263508Sdim
5067263508Sdim        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5068263508Sdim             diag::err_storage_class_for_static_member)
5069263508Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5070263508Sdim        break;
5071263508Sdim      case SC_PrivateExtern:
5072263508Sdim        llvm_unreachable("C storage class in c++!");
5073263508Sdim      case SC_OpenCLWorkGroupLocal:
5074263508Sdim        llvm_unreachable("OpenCL storage class in c++!");
5075249423Sdim      }
5076263508Sdim    }
5077263508Sdim
5078234353Sdim    if (SC == SC_Static && CurContext->isRecord()) {
5079218893Sdim      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5080218893Sdim        if (RD->isLocalClass())
5081218893Sdim          Diag(D.getIdentifierLoc(),
5082218893Sdim               diag::err_static_data_member_not_allowed_in_local_class)
5083218893Sdim            << Name << RD->getDeclName();
5084218893Sdim
5085234353Sdim        // C++98 [class.union]p1: If a union contains a static data member,
5086234353Sdim        // the program is ill-formed. C++11 drops this restriction.
5087234353Sdim        if (RD->isUnion())
5088218893Sdim          Diag(D.getIdentifierLoc(),
5089249423Sdim               getLangOpts().CPlusPlus11
5090234353Sdim                 ? diag::warn_cxx98_compat_static_data_member_in_union
5091234353Sdim                 : diag::ext_static_data_member_in_union) << Name;
5092234353Sdim        // We conservatively disallow static data members in anonymous structs.
5093234353Sdim        else if (!RD->getDeclName())
5094234353Sdim          Diag(D.getIdentifierLoc(),
5095234353Sdim               diag::err_static_data_member_not_allowed_in_anon_struct)
5096218893Sdim            << Name << RD->isUnion();
5097218893Sdim      }
5098195099Sed    }
5099193326Sed
5100263508Sdim    NamedDecl *PrevDecl = 0;
5101263508Sdim    if (Previous.begin() != Previous.end())
5102263508Sdim      PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5103263508Sdim    PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5104263508Sdim
5105218893Sdim    // Match up the template parameter lists with the scope specifier, then
5106218893Sdim    // determine whether we have a template or a template specialization.
5107263508Sdim    TemplateParameterList *TemplateParams =
5108263508Sdim        MatchTemplateParametersToScopeSpecifier(
5109263508Sdim            D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5110263508Sdim            D.getCXXScopeSpec(), TemplateParamLists,
5111263508Sdim            /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5112263508Sdim    if (TemplateParams) {
5113263508Sdim      if (!TemplateParams->size() &&
5114263508Sdim          D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5115218893Sdim        // There is an extraneous 'template<>' for this variable. Complain
5116218893Sdim        // about it, but allow the declaration of the variable.
5117218893Sdim        Diag(TemplateParams->getTemplateLoc(),
5118218893Sdim             diag::err_template_variable_noparams)
5119218893Sdim          << II
5120218893Sdim          << SourceRange(TemplateParams->getTemplateLoc(),
5121218893Sdim                         TemplateParams->getRAngleLoc());
5122263508Sdim      } else {
5123263508Sdim        // Only C++1y supports variable templates (N3651).
5124263508Sdim        Diag(D.getIdentifierLoc(),
5125263508Sdim             getLangOpts().CPlusPlus1y
5126263508Sdim                 ? diag::warn_cxx11_compat_variable_template
5127263508Sdim                 : diag::ext_variable_template);
5128263508Sdim
5129263508Sdim        if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5130263508Sdim          // This is an explicit specialization or a partial specialization.
5131263508Sdim          // Check that we can declare a specialization here
5132263508Sdim
5133263508Sdim          IsVariableTemplateSpecialization = true;
5134263508Sdim          IsPartialSpecialization = TemplateParams->size() > 0;
5135263508Sdim
5136263508Sdim        } else { // if (TemplateParams->size() > 0)
5137263508Sdim          // This is a template declaration.
5138263508Sdim          IsVariableTemplate = true;
5139263508Sdim
5140263508Sdim          // Check that we can declare a template here.
5141263508Sdim          if (CheckTemplateDeclScope(S, TemplateParams))
5142263508Sdim            return 0;
5143263508Sdim
5144263508Sdim          // If there is a previous declaration with the same name, check
5145263508Sdim          // whether this is a valid redeclaration.
5146263508Sdim          if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5147263508Sdim            PrevDecl = PrevVarTemplate = 0;
5148263508Sdim
5149263508Sdim          if (PrevVarTemplate) {
5150263508Sdim            // Ensure that the template parameter lists are compatible.
5151263508Sdim            if (!TemplateParameterListsAreEqual(
5152263508Sdim                    TemplateParams, PrevVarTemplate->getTemplateParameters(),
5153263508Sdim                    /*Complain=*/true, TPL_TemplateMatch))
5154263508Sdim              return 0;
5155263508Sdim          } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5156263508Sdim            // Maybe we will complain about the shadowed template parameter.
5157263508Sdim            DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5158263508Sdim
5159263508Sdim            // Just pretend that we didn't see the previous declaration.
5160263508Sdim            PrevDecl = 0;
5161263508Sdim          } else if (PrevDecl) {
5162263508Sdim            // C++ [temp]p5:
5163263508Sdim            // ... a template name declared in namespace scope or in class
5164263508Sdim            // scope shall be unique in that scope.
5165263508Sdim            Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5166263508Sdim                << Name;
5167263508Sdim            Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5168263508Sdim            return 0;
5169263508Sdim          }
5170263508Sdim
5171263508Sdim          // Check the template parameter list of this declaration, possibly
5172263508Sdim          // merging in the template parameter list from the previous variable
5173263508Sdim          // template declaration.
5174263508Sdim          if (CheckTemplateParameterList(
5175263508Sdim                  TemplateParams,
5176263508Sdim                  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5177263508Sdim                                  : 0,
5178263508Sdim                  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5179263508Sdim                   DC->isDependentContext())
5180263508Sdim                      ? TPC_ClassTemplateMember
5181263508Sdim                      : TPC_VarTemplate))
5182263508Sdim            Invalid = true;
5183263508Sdim
5184263508Sdim          if (D.getCXXScopeSpec().isSet()) {
5185263508Sdim            // If the name of the template was qualified, we must be defining
5186263508Sdim            // the template out-of-line.
5187263508Sdim            if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5188263508Sdim                !PrevVarTemplate) {
5189263508Sdim              Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5190263508Sdim                  << Name << DC << /*IsDefinition*/true
5191263508Sdim                  << D.getCXXScopeSpec().getRange();
5192263508Sdim              Invalid = true;
5193263508Sdim            }
5194263508Sdim          }
5195263508Sdim        }
5196218893Sdim      }
5197263508Sdim    } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5198263508Sdim      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5199263508Sdim
5200263508Sdim      // We have encountered something that the user meant to be a
5201263508Sdim      // specialization (because it has explicitly-specified template
5202263508Sdim      // arguments) but that was not introduced with a "template<>" (or had
5203263508Sdim      // too few of them).
5204263508Sdim      // FIXME: Differentiate between attempts for explicit instantiations
5205263508Sdim      // (starting with "template") and the rest.
5206263508Sdim      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5207263508Sdim          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5208263508Sdim          << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5209263508Sdim                                        "template<> ");
5210263508Sdim      IsVariableTemplateSpecialization = true;
5211198092Srdivacky    }
5212198092Srdivacky
5213263508Sdim    if (IsVariableTemplateSpecialization) {
5214263508Sdim      if (!PrevVarTemplate) {
5215263508Sdim        Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5216263508Sdim            << IsPartialSpecialization;
5217263508Sdim        return 0;
5218263508Sdim      }
5219198092Srdivacky
5220263508Sdim      SourceLocation TemplateKWLoc =
5221263508Sdim          TemplateParamLists.size() > 0
5222263508Sdim              ? TemplateParamLists[0]->getTemplateLoc()
5223263508Sdim              : SourceLocation();
5224263508Sdim      DeclResult Res = ActOnVarTemplateSpecialization(
5225263508Sdim          S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5226263508Sdim          IsPartialSpecialization);
5227263508Sdim      if (Res.isInvalid())
5228263508Sdim        return 0;
5229263508Sdim      NewVD = cast<VarDecl>(Res.get());
5230263508Sdim      AddToScope = false;
5231263508Sdim    } else
5232263508Sdim      NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5233263508Sdim                              D.getIdentifierLoc(), II, R, TInfo, SC);
5234263508Sdim
5235263508Sdim    // If this is supposed to be a variable template, create it as such.
5236263508Sdim    if (IsVariableTemplate) {
5237263508Sdim      NewTemplate =
5238263508Sdim          VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5239263508Sdim                                  TemplateParams, NewVD, PrevVarTemplate);
5240263508Sdim      NewVD->setDescribedVarTemplate(NewTemplate);
5241263508Sdim    }
5242263508Sdim
5243219077Sdim    // If this decl has an auto type in need of deduction, make a note of the
5244219077Sdim    // Decl so we can diagnose uses of it in its own initializer.
5245251662Sdim    if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5246219077Sdim      ParsingInitForAutoVars.insert(NewVD);
5247198092Srdivacky
5248263508Sdim    if (D.isInvalidType() || Invalid) {
5249218893Sdim      NewVD->setInvalidDecl();
5250263508Sdim      if (NewTemplate)
5251263508Sdim        NewTemplate->setInvalidDecl();
5252263508Sdim    }
5253205219Srdivacky
5254218893Sdim    SetNestedNameSpecifier(NewVD, D);
5255218893Sdim
5256263508Sdim    // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5257263508Sdim    if (TemplateParams && TemplateParamLists.size() > 1 &&
5258263508Sdim        (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5259263508Sdim      NewVD->setTemplateParameterListsInfo(
5260263508Sdim          Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5261263508Sdim    } else if (IsVariableTemplateSpecialization ||
5262263508Sdim               (!TemplateParams && TemplateParamLists.size() > 0 &&
5263263508Sdim                (D.getCXXScopeSpec().isSet()))) {
5264218893Sdim      NewVD->setTemplateParameterListsInfo(Context,
5265221345Sdim                                           TemplateParamLists.size(),
5266243830Sdim                                           TemplateParamLists.data());
5267218893Sdim    }
5268226633Sdim
5269234353Sdim    if (D.getDeclSpec().isConstexprSpecified())
5270234353Sdim      NewVD->setConstexpr(true);
5271210299Sed  }
5272210299Sed
5273226633Sdim  // Set the lexical context. If the declarator has a C++ scope specifier, the
5274226633Sdim  // lexical context will be different from the semantic context.
5275226633Sdim  NewVD->setLexicalDeclContext(CurContext);
5276263508Sdim  if (NewTemplate)
5277263508Sdim    NewTemplate->setLexicalDeclContext(CurContext);
5278226633Sdim
5279263508Sdim  if (IsLocalExternDecl)
5280263508Sdim    NewVD->setLocalExternDecl();
5281263508Sdim
5282251662Sdim  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5283263508Sdim    if (NewVD->hasLocalStorage()) {
5284263508Sdim      // C++11 [dcl.stc]p4:
5285263508Sdim      //   When thread_local is applied to a variable of block scope the
5286263508Sdim      //   storage-class-specifier static is implied if it does not appear
5287263508Sdim      //   explicitly.
5288263508Sdim      // Core issue: 'static' is not implied if the variable is declared
5289263508Sdim      //   'extern'.
5290263508Sdim      if (SCSpec == DeclSpec::SCS_unspecified &&
5291263508Sdim          TSCS == DeclSpec::TSCS_thread_local &&
5292263508Sdim          DC->isFunctionOrMethod())
5293263508Sdim        NewVD->setTSCSpec(TSCS);
5294263508Sdim      else
5295263508Sdim        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5296263508Sdim             diag::err_thread_non_global)
5297263508Sdim          << DeclSpec::getSpecifierName(TSCS);
5298263508Sdim    } else if (!Context.getTargetInfo().isTLSSupported())
5299251662Sdim      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5300251662Sdim           diag::err_thread_unsupported);
5301193326Sed    else
5302251662Sdim      NewVD->setTSCSpec(TSCS);
5303193326Sed  }
5304193326Sed
5305249423Sdim  // C99 6.7.4p3
5306249423Sdim  //   An inline definition of a function with external linkage shall
5307249423Sdim  //   not contain a definition of a modifiable object with static or
5308249423Sdim  //   thread storage duration...
5309249423Sdim  // We only apply this when the function is required to be defined
5310249423Sdim  // elsewhere, i.e. when the function is not 'extern inline'.  Note
5311249423Sdim  // that a local variable with thread storage duration still has to
5312249423Sdim  // be marked 'static'.  Also note that it's possible to get these
5313249423Sdim  // semantics in C++ using __attribute__((gnu_inline)).
5314249423Sdim  if (SC == SC_Static && S->getFnParent() != 0 &&
5315249423Sdim      !NewVD->getType().isConstQualified()) {
5316249423Sdim    FunctionDecl *CurFD = getCurFunctionDecl();
5317249423Sdim    if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5318249423Sdim      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5319249423Sdim           diag::warn_static_local_in_extern_inline);
5320249423Sdim      MaybeSuggestAddingStaticToDecl(CurFD);
5321249423Sdim    }
5322249423Sdim  }
5323249423Sdim
5324226633Sdim  if (D.getDeclSpec().isModulePrivateSpecified()) {
5325263508Sdim    if (IsVariableTemplateSpecialization)
5326226633Sdim      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5327263508Sdim          << (IsPartialSpecialization ? 1 : 0)
5328263508Sdim          << FixItHint::CreateRemoval(
5329263508Sdim                 D.getDeclSpec().getModulePrivateSpecLoc());
5330263508Sdim    else if (IsExplicitSpecialization)
5331263508Sdim      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5332226633Sdim        << 2
5333226633Sdim        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5334226633Sdim    else if (NewVD->hasLocalStorage())
5335226633Sdim      Diag(NewVD->getLocation(), diag::err_module_private_local)
5336226633Sdim        << 0 << NewVD->getDeclName()
5337226633Sdim        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5338226633Sdim        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5339263508Sdim    else {
5340226633Sdim      NewVD->setModulePrivate();
5341263508Sdim      if (NewTemplate)
5342263508Sdim        NewTemplate->setModulePrivate();
5343263508Sdim    }
5344226633Sdim  }
5345193326Sed
5346193326Sed  // Handle attributes prior to checking for duplicates in MergeVarDecl
5347194613Sed  ProcessDeclAttributes(S, NewVD, D);
5348193326Sed
5349249423Sdim  if (NewVD->hasAttrs())
5350249423Sdim    CheckAlignasUnderalignment(NewVD);
5351249423Sdim
5352243830Sdim  if (getLangOpts().CUDA) {
5353243830Sdim    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5354243830Sdim    // storage [duration]."
5355243830Sdim    if (SC == SC_None && S->getFnParent() != 0 &&
5356249423Sdim        (NewVD->hasAttr<CUDASharedAttr>() ||
5357249423Sdim         NewVD->hasAttr<CUDAConstantAttr>())) {
5358243830Sdim      NewVD->setStorageClass(SC_Static);
5359249423Sdim    }
5360243830Sdim  }
5361243830Sdim
5362224145Sdim  // In auto-retain/release, infer strong retension for variables of
5363224145Sdim  // retainable type.
5364234353Sdim  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5365224145Sdim    NewVD->setInvalidDecl();
5366224145Sdim
5367193326Sed  // Handle GNU asm-label extension (encoded as an attribute).
5368218893Sdim  if (Expr *E = (Expr*)D.getAsmLabel()) {
5369193326Sed    // The parser guarantees this is a string.
5370198092Srdivacky    StringLiteral *SE = cast<StringLiteral>(E);
5371226633Sdim    StringRef Label = SE->getString();
5372218893Sdim    if (S->getFnParent() != 0) {
5373218893Sdim      switch (SC) {
5374218893Sdim      case SC_None:
5375218893Sdim      case SC_Auto:
5376218893Sdim        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5377218893Sdim        break;
5378218893Sdim      case SC_Register:
5379226633Sdim        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5380218893Sdim          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5381218893Sdim        break;
5382218893Sdim      case SC_Static:
5383218893Sdim      case SC_Extern:
5384218893Sdim      case SC_PrivateExtern:
5385226633Sdim      case SC_OpenCLWorkGroupLocal:
5386218893Sdim        break;
5387218893Sdim      }
5388218893Sdim    }
5389218893Sdim
5390218893Sdim    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5391218893Sdim                                                Context, Label));
5392234353Sdim  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5393234353Sdim    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5394234353Sdim      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5395234353Sdim    if (I != ExtnameUndeclaredIdentifiers.end()) {
5396234353Sdim      NewVD->addAttr(I->second);
5397234353Sdim      ExtnameUndeclaredIdentifiers.erase(I);
5398234353Sdim    }
5399193326Sed  }
5400193326Sed
5401205408Srdivacky  // Diagnose shadowed variables before filtering for scope.
5402205408Srdivacky  if (!D.getCXXScopeSpec().isSet())
5403206084Srdivacky    CheckShadow(S, NewVD, Previous);
5404205408Srdivacky
5405199512Srdivacky  // Don't consider existing declarations that are in a different
5406199512Srdivacky  // scope and are out-of-semantic-context declarations (if the new
5407199512Srdivacky  // declaration has linkage).
5408263508Sdim  FilterLookupForScope(
5409263508Sdim      Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5410263508Sdim      IsExplicitSpecialization || IsVariableTemplateSpecialization);
5411263508Sdim
5412263508Sdim  // Check whether the previous declaration is in the same block scope. This
5413263508Sdim  // affects whether we merge types with it, per C++11 [dcl.array]p3.
5414263508Sdim  if (getLangOpts().CPlusPlus &&
5415263508Sdim      NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5416263508Sdim    NewVD->setPreviousDeclInSameBlockScope(
5417263508Sdim        Previous.isSingleResult() && !Previous.isShadowed() &&
5418263508Sdim        isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5419263508Sdim
5420234353Sdim  if (!getLangOpts().CPlusPlus) {
5421226633Sdim    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5422226633Sdim  } else {
5423218893Sdim    // Merge the decl with the existing one if appropriate.
5424218893Sdim    if (!Previous.empty()) {
5425218893Sdim      if (Previous.isSingleResult() &&
5426218893Sdim          isa<FieldDecl>(Previous.getFoundDecl()) &&
5427218893Sdim          D.getCXXScopeSpec().isSet()) {
5428218893Sdim        // The user tried to define a non-static data member
5429218893Sdim        // out-of-line (C++ [dcl.meaning]p1).
5430218893Sdim        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5431218893Sdim          << D.getCXXScopeSpec().getRange();
5432218893Sdim        Previous.clear();
5433218893Sdim        NewVD->setInvalidDecl();
5434218893Sdim      }
5435218893Sdim    } else if (D.getCXXScopeSpec().isSet()) {
5436218893Sdim      // No previous declaration in the qualifying scope.
5437218893Sdim      Diag(D.getIdentifierLoc(), diag::err_no_member)
5438218893Sdim        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5439193326Sed        << D.getCXXScopeSpec().getRange();
5440193326Sed      NewVD->setInvalidDecl();
5441193326Sed    }
5442193326Sed
5443263508Sdim    if (!IsVariableTemplateSpecialization) {
5444263508Sdim      if (PrevVarTemplate) {
5445263508Sdim        LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5446263508Sdim                              LookupOrdinaryName, ForRedeclaration);
5447263508Sdim        PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
5448263508Sdim        D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
5449263508Sdim      } else
5450263508Sdim        D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5451263508Sdim    }
5452193326Sed
5453218893Sdim    // This is an explicit specialization of a static data member. Check it.
5454263508Sdim    if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5455218893Sdim        CheckMemberSpecialization(NewVD, Previous))
5456218893Sdim      NewVD->setInvalidDecl();
5457218893Sdim  }
5458198092Srdivacky
5459249423Sdim  ProcessPragmaWeak(S, NewVD);
5460249423Sdim  checkAttributesAfterMerging(*this, *NewVD);
5461249423Sdim
5462263508Sdim  // If this is the first declaration of an extern C variable, update
5463263508Sdim  // the map of such variables.
5464263508Sdim  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5465263508Sdim      isIncompleteDeclExternC(*this, NewVD))
5466263508Sdim    RegisterLocallyScopedExternCDecl(NewVD, S);
5467193326Sed
5468263508Sdim  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5469263508Sdim    Decl *ManglingContextDecl;
5470263508Sdim    if (MangleNumberingContext *MCtx =
5471263508Sdim            getCurrentMangleNumberContext(NewVD->getDeclContext(),
5472263508Sdim                                          ManglingContextDecl)) {
5473263508Sdim      Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5474263508Sdim    }
5475263508Sdim  }
5476263508Sdim
5477263508Sdim  // If we are providing an explicit specialization of a static variable
5478263508Sdim  // template, make a note of that.
5479263508Sdim  if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
5480263508Sdim    PrevVarTemplate->setMemberSpecialization();
5481263508Sdim
5482263508Sdim  if (NewTemplate) {
5483263508Sdim    ActOnDocumentableDecl(NewTemplate);
5484263508Sdim    return NewTemplate;
5485263508Sdim  }
5486263508Sdim
5487193326Sed  return NewVD;
5488193326Sed}
5489193326Sed
5490206084Srdivacky/// \brief Diagnose variable or built-in function shadowing.  Implements
5491206084Srdivacky/// -Wshadow.
5492205408Srdivacky///
5493206084Srdivacky/// This method is called whenever a VarDecl is added to a "useful"
5494206084Srdivacky/// scope.
5495205408Srdivacky///
5496205408Srdivacky/// \param S the scope in which the shadowing name is being declared
5497205408Srdivacky/// \param R the lookup of the name
5498205408Srdivacky///
5499206084Srdivackyvoid Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5500205408Srdivacky  // Return if warning is ignored.
5501218893Sdim  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5502226633Sdim        DiagnosticsEngine::Ignored)
5503205408Srdivacky    return;
5504205408Srdivacky
5505218893Sdim  // Don't diagnose declarations at file scope.
5506221345Sdim  if (D->hasGlobalStorage())
5507221345Sdim    return;
5508221345Sdim
5509218893Sdim  DeclContext *NewDC = D->getDeclContext();
5510221345Sdim
5511205408Srdivacky  // Only diagnose if we're shadowing an unambiguous field or variable.
5512205408Srdivacky  if (R.getResultKind() != LookupResult::Found)
5513205408Srdivacky    return;
5514205408Srdivacky
5515205408Srdivacky  NamedDecl* ShadowedDecl = R.getFoundDecl();
5516205408Srdivacky  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5517205408Srdivacky    return;
5518205408Srdivacky
5519218893Sdim  // Fields are not shadowed by variables in C++ static methods.
5520218893Sdim  if (isa<FieldDecl>(ShadowedDecl))
5521218893Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5522218893Sdim      if (MD->isStatic())
5523218893Sdim        return;
5524218893Sdim
5525218893Sdim  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5526218893Sdim    if (shadowedVar->isExternC()) {
5527218893Sdim      // For shadowing external vars, make sure that we point to the global
5528218893Sdim      // declaration, not a locally scoped extern declaration.
5529218893Sdim      for (VarDecl::redecl_iterator
5530218893Sdim             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5531218893Sdim           I != E; ++I)
5532218893Sdim        if (I->isFileVarDecl()) {
5533218893Sdim          ShadowedDecl = *I;
5534218893Sdim          break;
5535218893Sdim        }
5536218893Sdim    }
5537218893Sdim
5538205408Srdivacky  DeclContext *OldDC = ShadowedDecl->getDeclContext();
5539205408Srdivacky
5540205408Srdivacky  // Only warn about certain kinds of shadowing for class members.
5541205408Srdivacky  if (NewDC && NewDC->isRecord()) {
5542205408Srdivacky    // In particular, don't warn about shadowing non-class members.
5543205408Srdivacky    if (!OldDC->isRecord())
5544205408Srdivacky      return;
5545205408Srdivacky
5546205408Srdivacky    // TODO: should we warn about static data members shadowing
5547205408Srdivacky    // static data members from base classes?
5548205408Srdivacky
5549205408Srdivacky    // TODO: don't diagnose for inaccessible shadowed members.
5550205408Srdivacky    // This is hard to do perfectly because we might friend the
5551205408Srdivacky    // shadowing context, but that's just a false negative.
5552205408Srdivacky  }
5553205408Srdivacky
5554205408Srdivacky  // Determine what kind of declaration we're shadowing.
5555205408Srdivacky  unsigned Kind;
5556205408Srdivacky  if (isa<RecordDecl>(OldDC)) {
5557205408Srdivacky    if (isa<FieldDecl>(ShadowedDecl))
5558205408Srdivacky      Kind = 3; // field
5559205408Srdivacky    else
5560205408Srdivacky      Kind = 2; // static data member
5561205408Srdivacky  } else if (OldDC->isFileContext())
5562205408Srdivacky    Kind = 1; // global
5563205408Srdivacky  else
5564205408Srdivacky    Kind = 0; // local
5565205408Srdivacky
5566205408Srdivacky  DeclarationName Name = R.getLookupName();
5567205408Srdivacky
5568205408Srdivacky  // Emit warning and note.
5569205408Srdivacky  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5570205408Srdivacky  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5571205408Srdivacky}
5572205408Srdivacky
5573206084Srdivacky/// \brief Check -Wshadow without the advantage of a previous lookup.
5574206084Srdivackyvoid Sema::CheckShadow(Scope *S, VarDecl *D) {
5575218893Sdim  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5576226633Sdim        DiagnosticsEngine::Ignored)
5577218893Sdim    return;
5578218893Sdim
5579206084Srdivacky  LookupResult R(*this, D->getDeclName(), D->getLocation(),
5580206084Srdivacky                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5581206084Srdivacky  LookupName(R, S);
5582206084Srdivacky  CheckShadow(S, D, R);
5583206084Srdivacky}
5584206084Srdivacky
5585263508Sdim/// Check for conflict between this global or extern "C" declaration and
5586263508Sdim/// previous global or extern "C" declarations. This is only used in C++.
5587249423Sdimtemplate<typename T>
5588263508Sdimstatic bool checkGlobalOrExternCConflict(
5589263508Sdim    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5590263508Sdim  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5591263508Sdim  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5592249423Sdim
5593263508Sdim  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5594263508Sdim    // The common case: this global doesn't conflict with any extern "C"
5595263508Sdim    // declaration.
5596263508Sdim    return false;
5597263508Sdim  }
5598263508Sdim
5599263508Sdim  if (Prev) {
5600263508Sdim    if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5601263508Sdim      // Both the old and new declarations have C language linkage. This is a
5602263508Sdim      // redeclaration.
5603263508Sdim      Previous.clear();
5604263508Sdim      Previous.addDecl(Prev);
5605263508Sdim      return true;
5606263508Sdim    }
5607263508Sdim
5608263508Sdim    // This is a global, non-extern "C" declaration, and there is a previous
5609263508Sdim    // non-global extern "C" declaration. Diagnose if this is a variable
5610263508Sdim    // declaration.
5611263508Sdim    if (!isa<VarDecl>(ND))
5612249423Sdim      return false;
5613263508Sdim  } else {
5614263508Sdim    // The declaration is extern "C". Check for any declaration in the
5615263508Sdim    // translation unit which might conflict.
5616263508Sdim    if (IsGlobal) {
5617263508Sdim      // We have already performed the lookup into the translation unit.
5618263508Sdim      IsGlobal = false;
5619263508Sdim      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5620263508Sdim           I != E; ++I) {
5621263508Sdim        if (isa<VarDecl>(*I)) {
5622263508Sdim          Prev = *I;
5623263508Sdim          break;
5624263508Sdim        }
5625263508Sdim      }
5626263508Sdim    } else {
5627263508Sdim      DeclContext::lookup_result R =
5628263508Sdim          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5629263508Sdim      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5630263508Sdim           I != E; ++I) {
5631263508Sdim        if (isa<VarDecl>(*I)) {
5632263508Sdim          Prev = *I;
5633263508Sdim          break;
5634263508Sdim        }
5635263508Sdim        // FIXME: If we have any other entity with this name in global scope,
5636263508Sdim        // the declaration is ill-formed, but that is a defect: it breaks the
5637263508Sdim        // 'stat' hack, for instance. Only variables can have mangled name
5638263508Sdim        // clashes with extern "C" declarations, so only they deserve a
5639263508Sdim        // diagnostic.
5640263508Sdim      }
5641263508Sdim    }
5642263508Sdim
5643263508Sdim    if (!Prev)
5644263508Sdim      return false;
5645249423Sdim  }
5646249423Sdim
5647263508Sdim  // Use the first declaration's location to ensure we point at something which
5648263508Sdim  // is lexically inside an extern "C" linkage-spec.
5649263508Sdim  assert(Prev && "should have found a previous declaration to diagnose");
5650263508Sdim  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5651263508Sdim    Prev = FD->getFirstDecl();
5652263508Sdim  else
5653263508Sdim    Prev = cast<VarDecl>(Prev)->getFirstDecl();
5654263508Sdim
5655263508Sdim  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5656263508Sdim    << IsGlobal << ND;
5657263508Sdim  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5658263508Sdim    << IsGlobal;
5659263508Sdim  return false;
5660249423Sdim}
5661249423Sdim
5662263508Sdim/// Apply special rules for handling extern "C" declarations. Returns \c true
5663263508Sdim/// if we have found that this is a redeclaration of some prior entity.
5664263508Sdim///
5665263508Sdim/// Per C++ [dcl.link]p6:
5666263508Sdim///   Two declarations [for a function or variable] with C language linkage
5667263508Sdim///   with the same name that appear in different scopes refer to the same
5668263508Sdim///   [entity]. An entity with C language linkage shall not be declared with
5669263508Sdim///   the same name as an entity in global scope.
5670263508Sdimtemplate<typename T>
5671263508Sdimstatic bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5672263508Sdim                                                  LookupResult &Previous) {
5673263508Sdim  if (!S.getLangOpts().CPlusPlus) {
5674263508Sdim    // In C, when declaring a global variable, look for a corresponding 'extern'
5675263508Sdim    // variable declared in function scope. We don't need this in C++, because
5676263508Sdim    // we find local extern decls in the surrounding file-scope DeclContext.
5677263508Sdim    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5678263508Sdim      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5679263508Sdim        Previous.clear();
5680263508Sdim        Previous.addDecl(Prev);
5681263508Sdim        return true;
5682263508Sdim      }
5683263508Sdim    }
5684263508Sdim    return false;
5685263508Sdim  }
5686263508Sdim
5687263508Sdim  // A declaration in the translation unit can conflict with an extern "C"
5688263508Sdim  // declaration.
5689263508Sdim  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5690263508Sdim    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5691263508Sdim
5692263508Sdim  // An extern "C" declaration can conflict with a declaration in the
5693263508Sdim  // translation unit or can be a redeclaration of an extern "C" declaration
5694263508Sdim  // in another scope.
5695263508Sdim  if (isIncompleteDeclExternC(S,ND))
5696263508Sdim    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5697263508Sdim
5698263508Sdim  // Neither global nor extern "C": nothing to do.
5699263508Sdim  return false;
5700263508Sdim}
5701263508Sdim
5702251662Sdimvoid Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5703193326Sed  // If the decl is already known invalid, don't check it.
5704193326Sed  if (NewVD->isInvalidDecl())
5705251662Sdim    return;
5706198092Srdivacky
5707243830Sdim  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5708243830Sdim  QualType T = TInfo->getType();
5709193326Sed
5710251662Sdim  // Defer checking an 'auto' type until its initializer is attached.
5711251662Sdim  if (T->isUndeducedType())
5712251662Sdim    return;
5713251662Sdim
5714208600Srdivacky  if (T->isObjCObjectType()) {
5715226633Sdim    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5716226633Sdim      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5717226633Sdim    T = Context.getObjCObjectPointerType(T);
5718226633Sdim    NewVD->setType(T);
5719193326Sed  }
5720198092Srdivacky
5721193326Sed  // Emit an error if an address space was applied to decl with local storage.
5722193326Sed  // This includes arrays of objects with address space qualifiers, but not
5723193326Sed  // automatic variables that point to other address spaces.
5724193326Sed  // ISO/IEC TR 18037 S5.1.2
5725218893Sdim  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5726193326Sed    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5727226633Sdim    NewVD->setInvalidDecl();
5728251662Sdim    return;
5729193326Sed  }
5730193326Sed
5731251662Sdim  // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5732251662Sdim  // __constant address space.
5733251662Sdim  if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5734251662Sdim      && T.getAddressSpace() != LangAS::opencl_constant
5735251662Sdim      && !T->isSamplerT()){
5736251662Sdim    Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5737251662Sdim    NewVD->setInvalidDecl();
5738251662Sdim    return;
5739251662Sdim  }
5740251662Sdim
5741239462Sdim  // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5742239462Sdim  // scope.
5743239462Sdim  if ((getLangOpts().OpenCLVersion >= 120)
5744239462Sdim      && NewVD->isStaticLocal()) {
5745239462Sdim    Diag(NewVD->getLocation(), diag::err_static_function_scope);
5746239462Sdim    NewVD->setInvalidDecl();
5747251662Sdim    return;
5748239462Sdim  }
5749239462Sdim
5750193326Sed  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5751223017Sdim      && !NewVD->hasAttr<BlocksAttr>()) {
5752234353Sdim    if (getLangOpts().getGC() != LangOptions::NonGC)
5753223017Sdim      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5754243830Sdim    else {
5755243830Sdim      assert(!getLangOpts().ObjCAutoRefCount);
5756223017Sdim      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5757243830Sdim    }
5758223017Sdim  }
5759218893Sdim
5760193326Sed  bool isVM = T->isVariablyModifiedType();
5761198092Srdivacky  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5762212904Sdim      NewVD->hasAttr<BlocksAttr>())
5763212904Sdim    getCurFunction()->setHasBranchProtectedScope();
5764198092Srdivacky
5765193326Sed  if ((isVM && NewVD->hasLinkage()) ||
5766193326Sed      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5767193326Sed    bool SizeIsNegative;
5768212904Sdim    llvm::APSInt Oversized;
5769243830Sdim    TypeSourceInfo *FixedTInfo =
5770243830Sdim      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5771243830Sdim                                                    SizeIsNegative, Oversized);
5772243830Sdim    if (FixedTInfo == 0 && T->isVariableArrayType()) {
5773193326Sed      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5774198092Srdivacky      // FIXME: This won't give the correct result for
5775198092Srdivacky      // int a[10][n];
5776193326Sed      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5777198092Srdivacky
5778193326Sed      if (NewVD->isFileVarDecl())
5779193326Sed        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5780193326Sed        << SizeRange;
5781263508Sdim      else if (NewVD->isStaticLocal())
5782193326Sed        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5783193326Sed        << SizeRange;
5784193326Sed      else
5785193326Sed        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5786193326Sed        << SizeRange;
5787226633Sdim      NewVD->setInvalidDecl();
5788251662Sdim      return;
5789198092Srdivacky    }
5790198092Srdivacky
5791243830Sdim    if (FixedTInfo == 0) {
5792193326Sed      if (NewVD->isFileVarDecl())
5793193326Sed        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5794193326Sed      else
5795193326Sed        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5796226633Sdim      NewVD->setInvalidDecl();
5797251662Sdim      return;
5798193326Sed    }
5799198092Srdivacky
5800193326Sed    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5801243830Sdim    NewVD->setType(FixedTInfo->getType());
5802243830Sdim    NewVD->setTypeSourceInfo(FixedTInfo);
5803193326Sed  }
5804193326Sed
5805263508Sdim  if (T->isVoidType()) {
5806263508Sdim    // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5807263508Sdim    //                    of objects and functions.
5808263508Sdim    if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5809263508Sdim      Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5810263508Sdim        << T;
5811263508Sdim      NewVD->setInvalidDecl();
5812263508Sdim      return;
5813263508Sdim    }
5814251662Sdim  }
5815251662Sdim
5816251662Sdim  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5817251662Sdim    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5818251662Sdim    NewVD->setInvalidDecl();
5819251662Sdim    return;
5820251662Sdim  }
5821251662Sdim
5822251662Sdim  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5823251662Sdim    Diag(NewVD->getLocation(), diag::err_block_on_vm);
5824251662Sdim    NewVD->setInvalidDecl();
5825251662Sdim    return;
5826251662Sdim  }
5827251662Sdim
5828251662Sdim  if (NewVD->isConstexpr() && !T->isDependentType() &&
5829251662Sdim      RequireLiteralType(NewVD->getLocation(), T,
5830251662Sdim                         diag::err_constexpr_var_non_literal)) {
5831251662Sdim    // Can't perform this check until the type is deduced.
5832251662Sdim    NewVD->setInvalidDecl();
5833251662Sdim    return;
5834251662Sdim  }
5835251662Sdim}
5836251662Sdim
5837251662Sdim/// \brief Perform semantic checking on a newly-created variable
5838251662Sdim/// declaration.
5839251662Sdim///
5840251662Sdim/// This routine performs all of the type-checking required for a
5841251662Sdim/// variable declaration once it has been built. It is used both to
5842251662Sdim/// check variables after they have been parsed and their declarators
5843251662Sdim/// have been translated into a declaration, and to check variables
5844251662Sdim/// that have been instantiated from a template.
5845251662Sdim///
5846251662Sdim/// Sets NewVD->isInvalidDecl() if an error was encountered.
5847251662Sdim///
5848251662Sdim/// Returns true if the variable declaration is a redeclaration.
5849263508Sdimbool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5850251662Sdim  CheckVariableDeclarationType(NewVD);
5851251662Sdim
5852251662Sdim  // If the decl is already known invalid, don't check it.
5853251662Sdim  if (NewVD->isInvalidDecl())
5854251662Sdim    return false;
5855251662Sdim
5856249423Sdim  // If we did not find anything by this name, look for a non-visible
5857249423Sdim  // extern "C" declaration with the same name.
5858263508Sdim  if (Previous.empty() &&
5859263508Sdim      checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5860263508Sdim    Previous.setShadowed();
5861193326Sed
5862249423Sdim  // Filter out any non-conflicting previous declarations.
5863249423Sdim  filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5864249423Sdim
5865199512Srdivacky  if (!Previous.empty()) {
5866263508Sdim    MergeVarDecl(NewVD, Previous);
5867226633Sdim    return true;
5868193326Sed  }
5869226633Sdim  return false;
5870193326Sed}
5871193326Sed
5872198092Srdivacky/// \brief Data used with FindOverriddenMethod
5873198092Srdivackystruct FindOverriddenMethodData {
5874198092Srdivacky  Sema *S;
5875198092Srdivacky  CXXMethodDecl *Method;
5876198092Srdivacky};
5877198092Srdivacky
5878198092Srdivacky/// \brief Member lookup function that determines whether a given C++
5879198092Srdivacky/// method overrides a method in a base class, to be used with
5880198092Srdivacky/// CXXRecordDecl::lookupInBases().
5881199482Srdivackystatic bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5882198092Srdivacky                                 CXXBasePath &Path,
5883198092Srdivacky                                 void *UserData) {
5884198092Srdivacky  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5885199990Srdivacky
5886198092Srdivacky  FindOverriddenMethodData *Data
5887198092Srdivacky    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5888199990Srdivacky
5889199990Srdivacky  DeclarationName Name = Data->Method->getDeclName();
5890199990Srdivacky
5891199990Srdivacky  // FIXME: Do we care about other names here too?
5892199990Srdivacky  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5893210299Sed    // We really want to find the base class destructor here.
5894199990Srdivacky    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5895199990Srdivacky    CanQualType CT = Data->S->Context.getCanonicalType(T);
5896199990Srdivacky
5897199990Srdivacky    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5898199990Srdivacky  }
5899199990Srdivacky
5900199990Srdivacky  for (Path.Decls = BaseRecord->lookup(Name);
5901249423Sdim       !Path.Decls.empty();
5902249423Sdim       Path.Decls = Path.Decls.slice(1)) {
5903249423Sdim    NamedDecl *D = Path.Decls.front();
5904210299Sed    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5905210299Sed      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5906198092Srdivacky        return true;
5907198092Srdivacky    }
5908198092Srdivacky  }
5909198092Srdivacky
5910198092Srdivacky  return false;
5911198092Srdivacky}
5912198092Srdivacky
5913243830Sdimnamespace {
5914243830Sdim  enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5915243830Sdim}
5916243830Sdim/// \brief Report an error regarding overriding, along with any relevant
5917243830Sdim/// overriden methods.
5918243830Sdim///
5919243830Sdim/// \param DiagID the primary error to report.
5920243830Sdim/// \param MD the overriding method.
5921243830Sdim/// \param OEK which overrides to include as notes.
5922243830Sdimstatic void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5923243830Sdim                            OverrideErrorKind OEK = OEK_All) {
5924243830Sdim  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5925243830Sdim  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5926243830Sdim                                      E = MD->end_overridden_methods();
5927243830Sdim       I != E; ++I) {
5928243830Sdim    // This check (& the OEK parameter) could be replaced by a predicate, but
5929243830Sdim    // without lambdas that would be overkill. This is still nicer than writing
5930243830Sdim    // out the diag loop 3 times.
5931243830Sdim    if ((OEK == OEK_All) ||
5932243830Sdim        (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5933243830Sdim        (OEK == OEK_Deleted && (*I)->isDeleted()))
5934243830Sdim      S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5935243830Sdim  }
5936243830Sdim}
5937243830Sdim
5938199512Srdivacky/// AddOverriddenMethods - See if a method overrides any in the base classes,
5939199512Srdivacky/// and if so, check that it's a valid override and remember it.
5940218893Sdimbool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5941199512Srdivacky  // Look for virtual methods in base classes that this method might override.
5942199512Srdivacky  CXXBasePaths Paths;
5943199512Srdivacky  FindOverriddenMethodData Data;
5944199512Srdivacky  Data.Method = MD;
5945199512Srdivacky  Data.S = this;
5946243830Sdim  bool hasDeletedOverridenMethods = false;
5947243830Sdim  bool hasNonDeletedOverridenMethods = false;
5948218893Sdim  bool AddedAny = false;
5949199512Srdivacky  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5950199512Srdivacky    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5951199512Srdivacky         E = Paths.found_decls_end(); I != E; ++I) {
5952199512Srdivacky      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5953224145Sdim        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5954199512Srdivacky        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5955249423Sdim            !CheckOverridingFunctionAttributes(MD, OldMD) &&
5956239462Sdim            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5957218893Sdim            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5958243830Sdim          hasDeletedOverridenMethods |= OldMD->isDeleted();
5959243830Sdim          hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5960218893Sdim          AddedAny = true;
5961218893Sdim        }
5962199512Srdivacky      }
5963199512Srdivacky    }
5964199512Srdivacky  }
5965243830Sdim
5966243830Sdim  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5967243830Sdim    ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5968243830Sdim  }
5969243830Sdim  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5970243830Sdim    ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5971243830Sdim  }
5972243830Sdim
5973218893Sdim  return AddedAny;
5974199512Srdivacky}
5975199512Srdivacky
5976226633Sdimnamespace {
5977226633Sdim  // Struct for holding all of the extra arguments needed by
5978226633Sdim  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5979226633Sdim  struct ActOnFDArgs {
5980226633Sdim    Scope *S;
5981226633Sdim    Declarator &D;
5982226633Sdim    MultiTemplateParamsArg TemplateParamLists;
5983226633Sdim    bool AddToScope;
5984226633Sdim  };
5985226633Sdim}
5986226633Sdim
5987234353Sdimnamespace {
5988234353Sdim
5989234353Sdim// Callback to only accept typo corrections that have a non-zero edit distance.
5990234353Sdim// Also only accept corrections that have the same parent decl.
5991234353Sdimclass DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5992234353Sdim public:
5993239462Sdim  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5994239462Sdim                            CXXRecordDecl *Parent)
5995239462Sdim      : Context(Context), OriginalFD(TypoFD),
5996239462Sdim        ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5997234353Sdim
5998234353Sdim  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5999234353Sdim    if (candidate.getEditDistance() == 0)
6000234353Sdim      return false;
6001234353Sdim
6002249423Sdim    SmallVector<unsigned, 1> MismatchedParams;
6003239462Sdim    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6004239462Sdim                                          CDeclEnd = candidate.end();
6005239462Sdim         CDecl != CDeclEnd; ++CDecl) {
6006239462Sdim      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6007239462Sdim
6008239462Sdim      if (FD && !FD->hasBody() &&
6009239462Sdim          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6010239462Sdim        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6011239462Sdim          CXXRecordDecl *Parent = MD->getParent();
6012239462Sdim          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6013239462Sdim            return true;
6014239462Sdim        } else if (!ExpectedParent) {
6015239462Sdim          return true;
6016239462Sdim        }
6017239462Sdim      }
6018234353Sdim    }
6019234353Sdim
6020239462Sdim    return false;
6021234353Sdim  }
6022234353Sdim
6023234353Sdim private:
6024239462Sdim  ASTContext &Context;
6025239462Sdim  FunctionDecl *OriginalFD;
6026234353Sdim  CXXRecordDecl *ExpectedParent;
6027234353Sdim};
6028234353Sdim
6029234353Sdim}
6030234353Sdim
6031226633Sdim/// \brief Generate diagnostics for an invalid function redeclaration.
6032226633Sdim///
6033226633Sdim/// This routine handles generating the diagnostic messages for an invalid
6034226633Sdim/// function redeclaration, including finding possible similar declarations
6035226633Sdim/// or performing typo correction if there are no previous declarations with
6036226633Sdim/// the same name.
6037226633Sdim///
6038226633Sdim/// Returns a NamedDecl iff typo correction was performed and substituting in
6039226633Sdim/// the new declaration name does not cause new errors.
6040263508Sdimstatic NamedDecl *DiagnoseInvalidRedeclaration(
6041226633Sdim    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6042263508Sdim    ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6043226633Sdim  DeclarationName Name = NewFD->getDeclName();
6044226633Sdim  DeclContext *NewDC = NewFD->getDeclContext();
6045249423Sdim  SmallVector<unsigned, 1> MismatchedParams;
6046249423Sdim  SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6047226633Sdim  TypoCorrection Correction;
6048263508Sdim  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6049263508Sdim  unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6050263508Sdim                                   : diag::err_member_decl_does_not_match;
6051263508Sdim  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6052263508Sdim                    IsLocalFriend ? Sema::LookupLocalFriendName
6053263508Sdim                                  : Sema::LookupOrdinaryName,
6054263508Sdim                    Sema::ForRedeclaration);
6055226633Sdim
6056226633Sdim  NewFD->setInvalidDecl();
6057263508Sdim  if (IsLocalFriend)
6058263508Sdim    SemaRef.LookupName(Prev, S);
6059263508Sdim  else
6060263508Sdim    SemaRef.LookupQualifiedName(Prev, NewDC);
6061218893Sdim  assert(!Prev.isAmbiguous() &&
6062218893Sdim         "Cannot have an ambiguity in previous-declaration lookup");
6063234353Sdim  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6064239462Sdim  DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6065239462Sdim                                      MD ? MD->getParent() : 0);
6066226633Sdim  if (!Prev.empty()) {
6067226633Sdim    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6068226633Sdim         Func != FuncEnd; ++Func) {
6069226633Sdim      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6070226633Sdim      if (FD &&
6071226633Sdim          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6072226633Sdim        // Add 1 to the index so that 0 can mean the mismatch didn't
6073226633Sdim        // involve a parameter
6074226633Sdim        unsigned ParamNum =
6075226633Sdim            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6076226633Sdim        NearMatches.push_back(std::make_pair(FD, ParamNum));
6077226633Sdim      }
6078226633Sdim    }
6079226633Sdim  // If the qualified name lookup yielded nothing, try typo correction
6080263508Sdim  } else if ((Correction = SemaRef.CorrectTypo(
6081263508Sdim                 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6082263508Sdim                 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6083263508Sdim                 IsLocalFriend ? 0 : NewDC))) {
6084226633Sdim    // Set up everything for the call to ActOnFunctionDeclarator
6085226633Sdim    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6086226633Sdim                              ExtraArgs.D.getIdentifierLoc());
6087226633Sdim    Previous.clear();
6088226633Sdim    Previous.setLookupName(Correction.getCorrection());
6089226633Sdim    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6090226633Sdim                                    CDeclEnd = Correction.end();
6091226633Sdim         CDecl != CDeclEnd; ++CDecl) {
6092226633Sdim      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6093239462Sdim      if (FD && !FD->hasBody() &&
6094239462Sdim          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6095226633Sdim        Previous.addDecl(FD);
6096226633Sdim      }
6097226633Sdim    }
6098226633Sdim    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6099263508Sdim
6100263508Sdim    NamedDecl *Result;
6101263508Sdim    // Retry building the function declaration with the new previous
6102263508Sdim    // declarations, and with errors suppressed.
6103263508Sdim    {
6104263508Sdim      // Trap errors.
6105263508Sdim      Sema::SFINAETrap Trap(SemaRef);
6106263508Sdim
6107263508Sdim      // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6108263508Sdim      // pieces need to verify the typo-corrected C++ declaration and hopefully
6109263508Sdim      // eliminate the need for the parameter pack ExtraArgs.
6110263508Sdim      Result = SemaRef.ActOnFunctionDeclarator(
6111263508Sdim          ExtraArgs.S, ExtraArgs.D,
6112263508Sdim          Correction.getCorrectionDecl()->getDeclContext(),
6113263508Sdim          NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6114263508Sdim          ExtraArgs.AddToScope);
6115263508Sdim
6116263508Sdim      if (Trap.hasErrorOccurred())
6117263508Sdim        Result = 0;
6118226633Sdim    }
6119263508Sdim
6120263508Sdim    if (Result) {
6121263508Sdim      // Determine which correction we picked.
6122263508Sdim      Decl *Canonical = Result->getCanonicalDecl();
6123263508Sdim      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6124263508Sdim           I != E; ++I)
6125263508Sdim        if ((*I)->getCanonicalDecl() == Canonical)
6126263508Sdim          Correction.setCorrectionDecl(*I);
6127263508Sdim
6128263508Sdim      SemaRef.diagnoseTypo(
6129263508Sdim          Correction,
6130263508Sdim          SemaRef.PDiag(IsLocalFriend
6131263508Sdim                          ? diag::err_no_matching_local_friend_suggest
6132263508Sdim                          : diag::err_member_decl_does_not_match_suggest)
6133263508Sdim            << Name << NewDC << IsDefinition);
6134263508Sdim      return Result;
6135226633Sdim    }
6136226633Sdim
6137263508Sdim    // Pretend the typo correction never occurred
6138263508Sdim    ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6139263508Sdim                              ExtraArgs.D.getIdentifierLoc());
6140263508Sdim    ExtraArgs.D.setRedeclaration(wasRedeclaration);
6141263508Sdim    Previous.clear();
6142263508Sdim    Previous.setLookupName(Name);
6143239462Sdim  }
6144226633Sdim
6145263508Sdim  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6146263508Sdim      << Name << NewDC << IsDefinition << NewFD->getLocation();
6147263508Sdim
6148226633Sdim  bool NewFDisConst = false;
6149226633Sdim  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6150239462Sdim    NewFDisConst = NewMD->isConst();
6151226633Sdim
6152263508Sdim  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6153226633Sdim       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6154226633Sdim       NearMatch != NearMatchEnd; ++NearMatch) {
6155226633Sdim    FunctionDecl *FD = NearMatch->first;
6156263508Sdim    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6157263508Sdim    bool FDisConst = MD && MD->isConst();
6158263508Sdim    bool IsMember = MD || !IsLocalFriend;
6159226633Sdim
6160263508Sdim    // FIXME: These notes are poorly worded for the local friend case.
6161226633Sdim    if (unsigned Idx = NearMatch->second) {
6162226633Sdim      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6163234353Sdim      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6164234353Sdim      if (Loc.isInvalid()) Loc = FD->getLocation();
6165263508Sdim      SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6166263508Sdim                                 : diag::note_local_decl_close_param_match)
6167263508Sdim        << Idx << FDParam->getType()
6168263508Sdim        << NewFD->getParamDecl(Idx - 1)->getType();
6169226633Sdim    } else if (FDisConst != NewFDisConst) {
6170226633Sdim      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6171226633Sdim          << NewFDisConst << FD->getSourceRange().getEnd();
6172226633Sdim    } else
6173263508Sdim      SemaRef.Diag(FD->getLocation(),
6174263508Sdim                   IsMember ? diag::note_member_def_close_match
6175263508Sdim                            : diag::note_local_decl_close_match);
6176226633Sdim  }
6177263508Sdim  return 0;
6178218893Sdim}
6179218893Sdim
6180234353Sdimstatic FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6181234353Sdim                                                          Declarator &D) {
6182193326Sed  switch (D.getDeclSpec().getStorageClassSpec()) {
6183226633Sdim  default: llvm_unreachable("Unknown storage class!");
6184193326Sed  case DeclSpec::SCS_auto:
6185193326Sed  case DeclSpec::SCS_register:
6186193326Sed  case DeclSpec::SCS_mutable:
6187226633Sdim    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6188226633Sdim                 diag::err_typecheck_sclass_func);
6189193326Sed    D.setInvalidType();
6190193326Sed    break;
6191226633Sdim  case DeclSpec::SCS_unspecified: break;
6192251662Sdim  case DeclSpec::SCS_extern:
6193251662Sdim    if (D.getDeclSpec().isExternInLinkageSpec())
6194251662Sdim      return SC_None;
6195251662Sdim    return SC_Extern;
6196193326Sed  case DeclSpec::SCS_static: {
6197226633Sdim    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6198193326Sed      // C99 6.7.1p5:
6199193326Sed      //   The declaration of an identifier for a function that has
6200193326Sed      //   block scope shall have no explicit storage-class specifier
6201193326Sed      //   other than extern
6202193326Sed      // See also (C++ [dcl.stc]p4).
6203226633Sdim      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6204226633Sdim                   diag::err_static_block_func);
6205226633Sdim      break;
6206193326Sed    } else
6207226633Sdim      return SC_Static;
6208193326Sed  }
6209226633Sdim  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6210193326Sed  }
6211193326Sed
6212226633Sdim  // No explicit storage class has already been returned
6213226633Sdim  return SC_None;
6214226633Sdim}
6215193326Sed
6216226633Sdimstatic FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6217226633Sdim                                           DeclContext *DC, QualType &R,
6218226633Sdim                                           TypeSourceInfo *TInfo,
6219226633Sdim                                           FunctionDecl::StorageClass SC,
6220226633Sdim                                           bool &IsVirtualOkay) {
6221226633Sdim  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6222226633Sdim  DeclarationName Name = NameInfo.getName();
6223226633Sdim
6224226633Sdim  FunctionDecl *NewFD = 0;
6225193326Sed  bool isInline = D.getDeclSpec().isInlineSpecified();
6226221345Sdim
6227234353Sdim  if (!SemaRef.getLangOpts().CPlusPlus) {
6228218893Sdim    // Determine whether the function was written with a
6229218893Sdim    // prototype. This true when:
6230218893Sdim    //   - there is a prototype in the declarator, or
6231218893Sdim    //   - the type R of the function is some kind of typedef or other reference
6232218893Sdim    //     to a type name (which eventually refers to a function type).
6233218893Sdim    bool HasPrototype =
6234226633Sdim      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6235226633Sdim      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6236226633Sdim
6237234353Sdim    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6238234353Sdim                                 D.getLocStart(), NameInfo, R,
6239249423Sdim                                 TInfo, SC, isInline,
6240249423Sdim                                 HasPrototype, false);
6241218893Sdim    if (D.isInvalidType())
6242218893Sdim      NewFD->setInvalidDecl();
6243226633Sdim
6244218893Sdim    // Set the lexical context.
6245226633Sdim    NewFD->setLexicalDeclContext(SemaRef.CurContext);
6246207619Srdivacky
6247226633Sdim    return NewFD;
6248226633Sdim  }
6249226633Sdim
6250226633Sdim  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6251226633Sdim  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6252226633Sdim
6253226633Sdim  // Check that the return type is not an abstract class type.
6254226633Sdim  // For record types, this is done by the AbstractClassUsageDiagnoser once
6255226633Sdim  // the class has been completely parsed.
6256226633Sdim  if (!DC->isRecord() &&
6257226633Sdim      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6258226633Sdim                                     R->getAs<FunctionType>()->getResultType(),
6259226633Sdim                                     diag::err_abstract_type_in_decl,
6260226633Sdim                                     SemaRef.AbstractReturnType))
6261226633Sdim    D.setInvalidType();
6262226633Sdim
6263226633Sdim  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6264226633Sdim    // This is a C++ constructor declaration.
6265226633Sdim    assert(DC->isRecord() &&
6266226633Sdim           "Constructors can only be declared in a member context");
6267226633Sdim
6268226633Sdim    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6269226633Sdim    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6270234353Sdim                                      D.getLocStart(), NameInfo,
6271226633Sdim                                      R, TInfo, isExplicit, isInline,
6272226633Sdim                                      /*isImplicitlyDeclared=*/false,
6273226633Sdim                                      isConstexpr);
6274226633Sdim
6275226633Sdim  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6276226633Sdim    // This is a C++ destructor declaration.
6277226633Sdim    if (DC->isRecord()) {
6278226633Sdim      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6279226633Sdim      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6280226633Sdim      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6281226633Sdim                                        SemaRef.Context, Record,
6282234353Sdim                                        D.getLocStart(),
6283226633Sdim                                        NameInfo, R, TInfo, isInline,
6284226633Sdim                                        /*isImplicitlyDeclared=*/false);
6285226633Sdim
6286226633Sdim      // If the class is complete, then we now create the implicit exception
6287226633Sdim      // specification. If the class is incomplete or dependent, we can't do
6288226633Sdim      // it yet.
6289249423Sdim      if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6290226633Sdim          Record->getDefinition() && !Record->isBeingDefined() &&
6291226633Sdim          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6292226633Sdim        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6293226633Sdim      }
6294226633Sdim
6295263508Sdim      // The Microsoft ABI requires that we perform the destructor body
6296263508Sdim      // checks (i.e. operator delete() lookup) at every declaration, as
6297263508Sdim      // any translation unit may need to emit a deleting destructor.
6298263508Sdim      if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6299263508Sdim          !Record->isDependentType() && Record->getDefinition() &&
6300263508Sdim          !Record->isBeingDefined()) {
6301263508Sdim        SemaRef.CheckDestructor(NewDD);
6302263508Sdim      }
6303263508Sdim
6304226633Sdim      IsVirtualOkay = true;
6305226633Sdim      return NewDD;
6306226633Sdim
6307226633Sdim    } else {
6308226633Sdim      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6309218893Sdim      D.setInvalidType();
6310198092Srdivacky
6311226633Sdim      // Create a FunctionDecl to satisfy the function definition parsing
6312226633Sdim      // code path.
6313226633Sdim      return FunctionDecl::Create(SemaRef.Context, DC,
6314234353Sdim                                  D.getLocStart(),
6315226633Sdim                                  D.getIdentifierLoc(), Name, R, TInfo,
6316249423Sdim                                  SC, isInline,
6317226633Sdim                                  /*hasPrototype=*/true, isConstexpr);
6318226633Sdim    }
6319198092Srdivacky
6320226633Sdim  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6321226633Sdim    if (!DC->isRecord()) {
6322226633Sdim      SemaRef.Diag(D.getIdentifierLoc(),
6323226633Sdim           diag::err_conv_function_not_member);
6324226633Sdim      return 0;
6325226633Sdim    }
6326193326Sed
6327226633Sdim    SemaRef.CheckConversionDeclarator(D, R, SC);
6328226633Sdim    IsVirtualOkay = true;
6329226633Sdim    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6330234353Sdim                                     D.getLocStart(), NameInfo,
6331226633Sdim                                     R, TInfo, isInline, isExplicit,
6332226633Sdim                                     isConstexpr, SourceLocation());
6333223017Sdim
6334226633Sdim  } else if (DC->isRecord()) {
6335226633Sdim    // If the name of the function is the same as the name of the record,
6336226633Sdim    // then this must be an invalid constructor that has a return type.
6337226633Sdim    // (The parser checks for a return type and makes the declarator a
6338226633Sdim    // constructor if it has no return type).
6339226633Sdim    if (Name.getAsIdentifierInfo() &&
6340226633Sdim        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6341226633Sdim      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6342226633Sdim        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6343226633Sdim        << SourceRange(D.getIdentifierLoc());
6344226633Sdim      return 0;
6345226633Sdim    }
6346193326Sed
6347226633Sdim    // This is a C++ method declaration.
6348249423Sdim    CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6349249423Sdim                                               cast<CXXRecordDecl>(DC),
6350249423Sdim                                               D.getLocStart(), NameInfo, R,
6351249423Sdim                                               TInfo, SC, isInline,
6352249423Sdim                                               isConstexpr, SourceLocation());
6353249423Sdim    IsVirtualOkay = !Ret->isStatic();
6354249423Sdim    return Ret;
6355226633Sdim  } else {
6356226633Sdim    // Determine whether the function was written with a
6357226633Sdim    // prototype. This true when:
6358226633Sdim    //   - we're in C++ (where every function has a prototype),
6359226633Sdim    return FunctionDecl::Create(SemaRef.Context, DC,
6360234353Sdim                                D.getLocStart(),
6361249423Sdim                                NameInfo, R, TInfo, SC, isInline,
6362226633Sdim                                true/*HasPrototype*/, isConstexpr);
6363226633Sdim  }
6364226633Sdim}
6365193326Sed
6366243830Sdimvoid Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6367243830Sdim  // In C++, the empty parameter-type-list must be spelled "void"; a
6368243830Sdim  // typedef of void is not permitted.
6369243830Sdim  if (getLangOpts().CPlusPlus &&
6370243830Sdim      Param->getType().getUnqualifiedType() != Context.VoidTy) {
6371243830Sdim    bool IsTypeAlias = false;
6372243830Sdim    if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6373243830Sdim      IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6374243830Sdim    else if (const TemplateSpecializationType *TST =
6375243830Sdim               Param->getType()->getAs<TemplateSpecializationType>())
6376243830Sdim      IsTypeAlias = TST->isTypeAlias();
6377243830Sdim    Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6378243830Sdim      << IsTypeAlias;
6379243830Sdim  }
6380243830Sdim}
6381243830Sdim
6382263508Sdimenum OpenCLParamType {
6383263508Sdim  ValidKernelParam,
6384263508Sdim  PtrPtrKernelParam,
6385263508Sdim  PtrKernelParam,
6386263508Sdim  InvalidKernelParam,
6387263508Sdim  RecordKernelParam
6388263508Sdim};
6389263508Sdim
6390263508Sdimstatic OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6391263508Sdim  if (PT->isPointerType()) {
6392263508Sdim    QualType PointeeType = PT->getPointeeType();
6393263508Sdim    return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6394263508Sdim  }
6395263508Sdim
6396263508Sdim  // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6397263508Sdim  // be used as builtin types.
6398263508Sdim
6399263508Sdim  if (PT->isImageType())
6400263508Sdim    return PtrKernelParam;
6401263508Sdim
6402263508Sdim  if (PT->isBooleanType())
6403263508Sdim    return InvalidKernelParam;
6404263508Sdim
6405263508Sdim  if (PT->isEventT())
6406263508Sdim    return InvalidKernelParam;
6407263508Sdim
6408263508Sdim  if (PT->isHalfType())
6409263508Sdim    return InvalidKernelParam;
6410263508Sdim
6411263508Sdim  if (PT->isRecordType())
6412263508Sdim    return RecordKernelParam;
6413263508Sdim
6414263508Sdim  return ValidKernelParam;
6415263508Sdim}
6416263508Sdim
6417263508Sdimstatic void checkIsValidOpenCLKernelParameter(
6418263508Sdim  Sema &S,
6419263508Sdim  Declarator &D,
6420263508Sdim  ParmVarDecl *Param,
6421263508Sdim  llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6422263508Sdim  QualType PT = Param->getType();
6423263508Sdim
6424263508Sdim  // Cache the valid types we encounter to avoid rechecking structs that are
6425263508Sdim  // used again
6426263508Sdim  if (ValidTypes.count(PT.getTypePtr()))
6427263508Sdim    return;
6428263508Sdim
6429263508Sdim  switch (getOpenCLKernelParameterType(PT)) {
6430263508Sdim  case PtrPtrKernelParam:
6431263508Sdim    // OpenCL v1.2 s6.9.a:
6432263508Sdim    // A kernel function argument cannot be declared as a
6433263508Sdim    // pointer to a pointer type.
6434263508Sdim    S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6435263508Sdim    D.setInvalidType();
6436263508Sdim    return;
6437263508Sdim
6438263508Sdim    // OpenCL v1.2 s6.9.k:
6439263508Sdim    // Arguments to kernel functions in a program cannot be declared with the
6440263508Sdim    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6441263508Sdim    // uintptr_t or a struct and/or union that contain fields declared to be
6442263508Sdim    // one of these built-in scalar types.
6443263508Sdim
6444263508Sdim  case InvalidKernelParam:
6445263508Sdim    // OpenCL v1.2 s6.8 n:
6446263508Sdim    // A kernel function argument cannot be declared
6447263508Sdim    // of event_t type.
6448263508Sdim    S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6449263508Sdim    D.setInvalidType();
6450263508Sdim    return;
6451263508Sdim
6452263508Sdim  case PtrKernelParam:
6453263508Sdim  case ValidKernelParam:
6454263508Sdim    ValidTypes.insert(PT.getTypePtr());
6455263508Sdim    return;
6456263508Sdim
6457263508Sdim  case RecordKernelParam:
6458263508Sdim    break;
6459263508Sdim  }
6460263508Sdim
6461263508Sdim  // Track nested structs we will inspect
6462263508Sdim  SmallVector<const Decl *, 4> VisitStack;
6463263508Sdim
6464263508Sdim  // Track where we are in the nested structs. Items will migrate from
6465263508Sdim  // VisitStack to HistoryStack as we do the DFS for bad field.
6466263508Sdim  SmallVector<const FieldDecl *, 4> HistoryStack;
6467263508Sdim  HistoryStack.push_back((const FieldDecl *) 0);
6468263508Sdim
6469263508Sdim  const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6470263508Sdim  VisitStack.push_back(PD);
6471263508Sdim
6472263508Sdim  assert(VisitStack.back() && "First decl null?");
6473263508Sdim
6474263508Sdim  do {
6475263508Sdim    const Decl *Next = VisitStack.pop_back_val();
6476263508Sdim    if (!Next) {
6477263508Sdim      assert(!HistoryStack.empty());
6478263508Sdim      // Found a marker, we have gone up a level
6479263508Sdim      if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6480263508Sdim        ValidTypes.insert(Hist->getType().getTypePtr());
6481263508Sdim
6482263508Sdim      continue;
6483263508Sdim    }
6484263508Sdim
6485263508Sdim    // Adds everything except the original parameter declaration (which is not a
6486263508Sdim    // field itself) to the history stack.
6487263508Sdim    const RecordDecl *RD;
6488263508Sdim    if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6489263508Sdim      HistoryStack.push_back(Field);
6490263508Sdim      RD = Field->getType()->castAs<RecordType>()->getDecl();
6491263508Sdim    } else {
6492263508Sdim      RD = cast<RecordDecl>(Next);
6493263508Sdim    }
6494263508Sdim
6495263508Sdim    // Add a null marker so we know when we've gone back up a level
6496263508Sdim    VisitStack.push_back((const Decl *) 0);
6497263508Sdim
6498263508Sdim    for (RecordDecl::field_iterator I = RD->field_begin(),
6499263508Sdim           E = RD->field_end(); I != E; ++I) {
6500263508Sdim      const FieldDecl *FD = *I;
6501263508Sdim      QualType QT = FD->getType();
6502263508Sdim
6503263508Sdim      if (ValidTypes.count(QT.getTypePtr()))
6504263508Sdim        continue;
6505263508Sdim
6506263508Sdim      OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6507263508Sdim      if (ParamType == ValidKernelParam)
6508263508Sdim        continue;
6509263508Sdim
6510263508Sdim      if (ParamType == RecordKernelParam) {
6511263508Sdim        VisitStack.push_back(FD);
6512263508Sdim        continue;
6513263508Sdim      }
6514263508Sdim
6515263508Sdim      // OpenCL v1.2 s6.9.p:
6516263508Sdim      // Arguments to kernel functions that are declared to be a struct or union
6517263508Sdim      // do not allow OpenCL objects to be passed as elements of the struct or
6518263508Sdim      // union.
6519263508Sdim      if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6520263508Sdim        S.Diag(Param->getLocation(),
6521263508Sdim               diag::err_record_with_pointers_kernel_param)
6522263508Sdim          << PT->isUnionType()
6523263508Sdim          << PT;
6524263508Sdim      } else {
6525263508Sdim        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6526263508Sdim      }
6527263508Sdim
6528263508Sdim      S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6529263508Sdim        << PD->getDeclName();
6530263508Sdim
6531263508Sdim      // We have an error, now let's go back up through history and show where
6532263508Sdim      // the offending field came from
6533263508Sdim      for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6534263508Sdim             E = HistoryStack.end(); I != E; ++I) {
6535263508Sdim        const FieldDecl *OuterField = *I;
6536263508Sdim        S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6537263508Sdim          << OuterField->getType();
6538263508Sdim      }
6539263508Sdim
6540263508Sdim      S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6541263508Sdim        << QT->isPointerType()
6542263508Sdim        << QT;
6543263508Sdim      D.setInvalidType();
6544263508Sdim      return;
6545263508Sdim    }
6546263508Sdim  } while (!VisitStack.empty());
6547263508Sdim}
6548263508Sdim
6549226633SdimNamedDecl*
6550226633SdimSema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6551226633Sdim                              TypeSourceInfo *TInfo, LookupResult &Previous,
6552226633Sdim                              MultiTemplateParamsArg TemplateParamLists,
6553226633Sdim                              bool &AddToScope) {
6554226633Sdim  QualType R = TInfo->getType();
6555221345Sdim
6556226633Sdim  assert(R.getTypePtr()->isFunctionType());
6557198092Srdivacky
6558226633Sdim  // TODO: consider using NameInfo for diagnostic.
6559226633Sdim  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6560226633Sdim  DeclarationName Name = NameInfo.getName();
6561226633Sdim  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6562221345Sdim
6563251662Sdim  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6564251662Sdim    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6565251662Sdim         diag::err_invalid_thread)
6566251662Sdim      << DeclSpec::getSpecifierName(TSCS);
6567198092Srdivacky
6568263508Sdim  if (D.isFirstDeclarationOfMember())
6569263508Sdim    adjustMemberFunctionCC(R, D.isStaticMember());
6570226633Sdim
6571226633Sdim  bool isFriend = false;
6572226633Sdim  FunctionTemplateDecl *FunctionTemplate = 0;
6573226633Sdim  bool isExplicitSpecialization = false;
6574226633Sdim  bool isFunctionTemplateSpecialization = false;
6575239462Sdim
6576226633Sdim  bool isDependentClassScopeExplicitSpecialization = false;
6577239462Sdim  bool HasExplicitTemplateArgs = false;
6578239462Sdim  TemplateArgumentListInfo TemplateArgs;
6579239462Sdim
6580226633Sdim  bool isVirtualOkay = false;
6581226633Sdim
6582263508Sdim  DeclContext *OriginalDC = DC;
6583263508Sdim  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6584263508Sdim
6585226633Sdim  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6586226633Sdim                                              isVirtualOkay);
6587226633Sdim  if (!NewFD) return 0;
6588226633Sdim
6589234353Sdim  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6590234353Sdim    NewFD->setTopLevelDeclInObjCContainer();
6591234353Sdim
6592263508Sdim  // Set the lexical context. If this is a function-scope declaration, or has a
6593263508Sdim  // C++ scope specifier, or is the object of a friend declaration, the lexical
6594263508Sdim  // context will be different from the semantic context.
6595263508Sdim  NewFD->setLexicalDeclContext(CurContext);
6596263508Sdim
6597263508Sdim  if (IsLocalExternDecl)
6598263508Sdim    NewFD->setLocalExternDecl();
6599263508Sdim
6600234353Sdim  if (getLangOpts().CPlusPlus) {
6601226633Sdim    bool isInline = D.getDeclSpec().isInlineSpecified();
6602226633Sdim    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6603226633Sdim    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6604226633Sdim    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6605226633Sdim    isFriend = D.getDeclSpec().isFriendSpecified();
6606226633Sdim    if (isFriend && !isInline && D.isFunctionDefinition()) {
6607221345Sdim      // C++ [class.friend]p5
6608221345Sdim      //   A function can be defined in a friend declaration of a
6609221345Sdim      //   class . . . . Such a function is implicitly inline.
6610221345Sdim      NewFD->setImplicitlyInline();
6611221345Sdim    }
6612221345Sdim
6613243830Sdim    // If this is a method defined in an __interface, and is not a constructor
6614243830Sdim    // or an overloaded operator, then set the pure flag (isVirtual will already
6615243830Sdim    // return true).
6616243830Sdim    if (const CXXRecordDecl *Parent =
6617243830Sdim          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6618243830Sdim      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6619243830Sdim        NewFD->setPure(true);
6620243830Sdim    }
6621243830Sdim
6622218893Sdim    SetNestedNameSpecifier(NewFD, D);
6623218893Sdim    isExplicitSpecialization = false;
6624218893Sdim    isFunctionTemplateSpecialization = false;
6625218893Sdim    if (D.isInvalidType())
6626218893Sdim      NewFD->setInvalidDecl();
6627263508Sdim
6628218893Sdim    // Match up the template parameter lists with the scope specifier, then
6629218893Sdim    // determine whether we have a template or a template specialization.
6630218893Sdim    bool Invalid = false;
6631263508Sdim    if (TemplateParameterList *TemplateParams =
6632263508Sdim            MatchTemplateParametersToScopeSpecifier(
6633263508Sdim                D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6634263508Sdim                D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6635263508Sdim                isExplicitSpecialization, Invalid)) {
6636221345Sdim      if (TemplateParams->size() > 0) {
6637221345Sdim        // This is a function template
6638210299Sed
6639221345Sdim        // Check that we can declare a template here.
6640221345Sdim        if (CheckTemplateDeclScope(S, TemplateParams))
6641221345Sdim          return 0;
6642198092Srdivacky
6643221345Sdim        // A destructor cannot be a template.
6644221345Sdim        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6645221345Sdim          Diag(NewFD->getLocation(), diag::err_destructor_template);
6646221345Sdim          return 0;
6647221345Sdim        }
6648226633Sdim
6649226633Sdim        // If we're adding a template to a dependent context, we may need to
6650234353Sdim        // rebuilding some of the types used within the template parameter list,
6651226633Sdim        // now that we know what the current instantiation is.
6652226633Sdim        if (DC->isDependentContext()) {
6653226633Sdim          ContextRAII SavedContext(*this, DC);
6654226633Sdim          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6655226633Sdim            Invalid = true;
6656226633Sdim        }
6657226633Sdim
6658198092Srdivacky
6659221345Sdim        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6660221345Sdim                                                        NewFD->getLocation(),
6661221345Sdim                                                        Name, TemplateParams,
6662221345Sdim                                                        NewFD);
6663221345Sdim        FunctionTemplate->setLexicalDeclContext(CurContext);
6664221345Sdim        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6665206084Srdivacky
6666221345Sdim        // For source fidelity, store the other template param lists.
6667221345Sdim        if (TemplateParamLists.size() > 1) {
6668221345Sdim          NewFD->setTemplateParameterListsInfo(Context,
6669221345Sdim                                               TemplateParamLists.size() - 1,
6670243830Sdim                                               TemplateParamLists.data());
6671221345Sdim        }
6672221345Sdim      } else {
6673221345Sdim        // This is a function template specialization.
6674221345Sdim        isFunctionTemplateSpecialization = true;
6675221345Sdim        // For source fidelity, store all the template param lists.
6676221345Sdim        NewFD->setTemplateParameterListsInfo(Context,
6677221345Sdim                                             TemplateParamLists.size(),
6678243830Sdim                                             TemplateParamLists.data());
6679206084Srdivacky
6680221345Sdim        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6681221345Sdim        if (isFriend) {
6682221345Sdim          // We want to remove the "template<>", found here.
6683221345Sdim          SourceRange RemoveRange = TemplateParams->getSourceRange();
6684218893Sdim
6685221345Sdim          // If we remove the template<> and the name is not a
6686221345Sdim          // template-id, we're actually silently creating a problem:
6687221345Sdim          // the friend declaration will refer to an untemplated decl,
6688221345Sdim          // and clearly the user wants a template specialization.  So
6689221345Sdim          // we need to insert '<>' after the name.
6690221345Sdim          SourceLocation InsertLoc;
6691221345Sdim          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6692221345Sdim            InsertLoc = D.getName().getSourceRange().getEnd();
6693221345Sdim            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6694218893Sdim          }
6695221345Sdim
6696221345Sdim          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6697221345Sdim            << Name << RemoveRange
6698221345Sdim            << FixItHint::CreateRemoval(RemoveRange)
6699221345Sdim            << FixItHint::CreateInsertion(InsertLoc, "<>");
6700206084Srdivacky        }
6701221345Sdim      }
6702195099Sed    }
6703221345Sdim    else {
6704221345Sdim      // All template param lists were matched against the scope specifier:
6705221345Sdim      // this is NOT (an explicit specialization of) a template.
6706221345Sdim      if (TemplateParamLists.size() > 0)
6707221345Sdim        // For source fidelity, store all the template param lists.
6708221345Sdim        NewFD->setTemplateParameterListsInfo(Context,
6709221345Sdim                                             TemplateParamLists.size(),
6710243830Sdim                                             TemplateParamLists.data());
6711221345Sdim    }
6712198092Srdivacky
6713218893Sdim    if (Invalid) {
6714218893Sdim      NewFD->setInvalidDecl();
6715218893Sdim      if (FunctionTemplate)
6716218893Sdim        FunctionTemplate->setInvalidDecl();
6717218893Sdim    }
6718226633Sdim
6719218893Sdim    // C++ [dcl.fct.spec]p5:
6720218893Sdim    //   The virtual specifier shall only be used in declarations of
6721218893Sdim    //   nonstatic class member functions that appear within a
6722218893Sdim    //   member-specification of a class declaration; see 10.3.
6723218893Sdim    //
6724218893Sdim    if (isVirtual && !NewFD->isInvalidDecl()) {
6725218893Sdim      if (!isVirtualOkay) {
6726218893Sdim        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6727218893Sdim             diag::err_virtual_non_function);
6728218893Sdim      } else if (!CurContext->isRecord()) {
6729218893Sdim        // 'virtual' was specified outside of the class.
6730218893Sdim        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6731218893Sdim             diag::err_virtual_out_of_class)
6732218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6733218893Sdim      } else if (NewFD->getDescribedFunctionTemplate()) {
6734218893Sdim        // C++ [temp.mem]p3:
6735218893Sdim        //  A member function template shall not be virtual.
6736218893Sdim        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6737218893Sdim             diag::err_virtual_member_function_template)
6738218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6739218893Sdim      } else {
6740218893Sdim        // Okay: Add virtual to the method.
6741218893Sdim        NewFD->setVirtualAsWritten(true);
6742218893Sdim      }
6743251662Sdim
6744251662Sdim      if (getLangOpts().CPlusPlus1y &&
6745251662Sdim          NewFD->getResultType()->isUndeducedType())
6746251662Sdim        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6747193326Sed    }
6748193326Sed
6749263508Sdim    if (getLangOpts().CPlusPlus1y &&
6750263508Sdim        (NewFD->isDependentContext() ||
6751263508Sdim         (isFriend && CurContext->isDependentContext())) &&
6752263508Sdim        NewFD->getResultType()->isUndeducedType()) {
6753263508Sdim      // If the function template is referenced directly (for instance, as a
6754263508Sdim      // member of the current instantiation), pretend it has a dependent type.
6755263508Sdim      // This is not really justified by the standard, but is the only sane
6756263508Sdim      // thing to do.
6757263508Sdim      // FIXME: For a friend function, we have not marked the function as being
6758263508Sdim      // a friend yet, so 'isDependentContext' on the FD doesn't work.
6759263508Sdim      const FunctionProtoType *FPT =
6760263508Sdim          NewFD->getType()->castAs<FunctionProtoType>();
6761263508Sdim      QualType Result = SubstAutoType(FPT->getResultType(),
6762263508Sdim                                       Context.DependentTy);
6763263508Sdim      NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6764263508Sdim                                             FPT->getExtProtoInfo()));
6765263508Sdim    }
6766263508Sdim
6767218893Sdim    // C++ [dcl.fct.spec]p3:
6768234353Sdim    //  The inline specifier shall not appear on a block scope function
6769234353Sdim    //  declaration.
6770218893Sdim    if (isInline && !NewFD->isInvalidDecl()) {
6771218893Sdim      if (CurContext->isFunctionOrMethod()) {
6772218893Sdim        // 'inline' is not allowed on block scope function declaration.
6773218893Sdim        Diag(D.getDeclSpec().getInlineSpecLoc(),
6774218893Sdim             diag::err_inline_declaration_block_scope) << Name
6775218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6776218893Sdim      }
6777212904Sdim    }
6778226633Sdim
6779218893Sdim    // C++ [dcl.fct.spec]p6:
6780218893Sdim    //  The explicit specifier shall be used only in the declaration of a
6781234353Sdim    //  constructor or conversion function within its class definition;
6782234353Sdim    //  see 12.3.1 and 12.3.2.
6783218893Sdim    if (isExplicit && !NewFD->isInvalidDecl()) {
6784218893Sdim      if (!CurContext->isRecord()) {
6785218893Sdim        // 'explicit' was specified outside of the class.
6786218893Sdim        Diag(D.getDeclSpec().getExplicitSpecLoc(),
6787218893Sdim             diag::err_explicit_out_of_class)
6788218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6789218893Sdim      } else if (!isa<CXXConstructorDecl>(NewFD) &&
6790218893Sdim                 !isa<CXXConversionDecl>(NewFD)) {
6791218893Sdim        // 'explicit' was specified on a function that wasn't a constructor
6792218893Sdim        // or conversion function.
6793218893Sdim        Diag(D.getDeclSpec().getExplicitSpecLoc(),
6794218893Sdim             diag::err_explicit_non_ctor_or_conv_function)
6795218893Sdim          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6796218893Sdim      }
6797218893Sdim    }
6798203955Srdivacky
6799226633Sdim    if (isConstexpr) {
6800249423Sdim      // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6801226633Sdim      // are implicitly inline.
6802226633Sdim      NewFD->setImplicitlyInline();
6803199512Srdivacky
6804249423Sdim      // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6805226633Sdim      // be either constructors or to return a literal type. Therefore,
6806226633Sdim      // destructors cannot be declared constexpr.
6807226633Sdim      if (isa<CXXDestructorDecl>(NewFD))
6808226633Sdim        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6809226633Sdim    }
6810226633Sdim
6811226633Sdim    // If __module_private__ was specified, mark the function accordingly.
6812226633Sdim    if (D.getDeclSpec().isModulePrivateSpecified()) {
6813226633Sdim      if (isFunctionTemplateSpecialization) {
6814226633Sdim        SourceLocation ModulePrivateLoc
6815226633Sdim          = D.getDeclSpec().getModulePrivateSpecLoc();
6816226633Sdim        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6817226633Sdim          << 0
6818226633Sdim          << FixItHint::CreateRemoval(ModulePrivateLoc);
6819226633Sdim      } else {
6820226633Sdim        NewFD->setModulePrivate();
6821226633Sdim        if (FunctionTemplate)
6822226633Sdim          FunctionTemplate->setModulePrivate();
6823226633Sdim      }
6824226633Sdim    }
6825226633Sdim
6826218893Sdim    if (isFriend) {
6827218893Sdim      if (FunctionTemplate) {
6828263508Sdim        FunctionTemplate->setObjectOfFriendDecl();
6829218893Sdim        FunctionTemplate->setAccess(AS_public);
6830218893Sdim      }
6831263508Sdim      NewFD->setObjectOfFriendDecl();
6832218893Sdim      NewFD->setAccess(AS_public);
6833218893Sdim    }
6834199512Srdivacky
6835234353Sdim    // If a function is defined as defaulted or deleted, mark it as such now.
6836234353Sdim    switch (D.getFunctionDefinitionKind()) {
6837234353Sdim      case FDK_Declaration:
6838234353Sdim      case FDK_Definition:
6839234353Sdim        break;
6840234353Sdim
6841234353Sdim      case FDK_Defaulted:
6842234353Sdim        NewFD->setDefaulted();
6843234353Sdim        break;
6844234353Sdim
6845234353Sdim      case FDK_Deleted:
6846234353Sdim        NewFD->setDeletedAsWritten();
6847234353Sdim        break;
6848234353Sdim    }
6849234353Sdim
6850226633Sdim    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6851226633Sdim        D.isFunctionDefinition()) {
6852234353Sdim      // C++ [class.mfct]p2:
6853234353Sdim      //   A member function may be defined (8.4) in its class definition, in
6854234353Sdim      //   which case it is an inline member function (7.1.2)
6855218893Sdim      NewFD->setImplicitlyInline();
6856198092Srdivacky    }
6857198092Srdivacky
6858218893Sdim    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6859218893Sdim        !CurContext->isRecord()) {
6860218893Sdim      // C++ [class.static]p1:
6861218893Sdim      //   A data or function member of a class may be declared static
6862218893Sdim      //   in a class definition, in which case it is a static member of
6863218893Sdim      //   the class.
6864193326Sed
6865218893Sdim      // Complain about the 'static' specifier if it's on an out-of-line
6866218893Sdim      // member function definition.
6867218893Sdim      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6868218893Sdim           diag::err_static_out_of_line)
6869218893Sdim        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6870218893Sdim    }
6871243830Sdim
6872243830Sdim    // C++11 [except.spec]p15:
6873243830Sdim    //   A deallocation function with no exception-specification is treated
6874243830Sdim    //   as if it were specified with noexcept(true).
6875243830Sdim    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6876243830Sdim    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6877243830Sdim         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6878249423Sdim        getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6879243830Sdim      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6880243830Sdim      EPI.ExceptionSpecType = EST_BasicNoexcept;
6881243830Sdim      NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6882263508Sdim                                             FPT->getArgTypes(), EPI));
6883243830Sdim    }
6884193326Sed  }
6885226633Sdim
6886226633Sdim  // Filter out previous declarations that don't match the scope.
6887263508Sdim  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6888226633Sdim                       isExplicitSpecialization ||
6889226633Sdim                       isFunctionTemplateSpecialization);
6890263508Sdim
6891193326Sed  // Handle GNU asm-label extension (encoded as an attribute).
6892193326Sed  if (Expr *E = (Expr*) D.getAsmLabel()) {
6893193326Sed    // The parser guarantees this is a string.
6894198092Srdivacky    StringLiteral *SE = cast<StringLiteral>(E);
6895212904Sdim    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6896212904Sdim                                                SE->getString()));
6897234353Sdim  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6898234353Sdim    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6899234353Sdim      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6900234353Sdim    if (I != ExtnameUndeclaredIdentifiers.end()) {
6901234353Sdim      NewFD->addAttr(I->second);
6902234353Sdim      ExtnameUndeclaredIdentifiers.erase(I);
6903234353Sdim    }
6904193326Sed  }
6905193326Sed
6906193326Sed  // Copy the parameter declarations from the declarator D to the function
6907193326Sed  // declaration NewFD, if they are available.  First scavenge them into Params.
6908226633Sdim  SmallVector<ParmVarDecl*, 16> Params;
6909218893Sdim  if (D.isFunctionDeclarator()) {
6910218893Sdim    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6911193326Sed
6912193326Sed    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6913193326Sed    // function that takes no arguments, not a function that takes a
6914193326Sed    // single void argument.
6915193326Sed    // We let through "const void" here because Sema::GetTypeForDeclarator
6916193326Sed    // already checks for that case.
6917193326Sed    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6918193326Sed        FTI.ArgInfo[0].Param &&
6919212904Sdim        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6920193326Sed      // Empty arg list, don't push any params.
6921243830Sdim      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6922193326Sed    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6923198092Srdivacky      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6924212904Sdim        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6925198092Srdivacky        assert(Param->getDeclContext() != NewFD && "Was set before ?");
6926198092Srdivacky        Param->setDeclContext(NewFD);
6927198092Srdivacky        Params.push_back(Param);
6928207619Srdivacky
6929207619Srdivacky        if (Param->isInvalidDecl())
6930207619Srdivacky          NewFD->setInvalidDecl();
6931198092Srdivacky      }
6932193326Sed    }
6933198092Srdivacky
6934198092Srdivacky  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6935193326Sed    // When we're declaring a function with a typedef, typeof, etc as in the
6936193326Sed    // following example, we'll need to synthesize (unnamed)
6937193326Sed    // parameters for use in the declaration.
6938193326Sed    //
6939193326Sed    // @code
6940193326Sed    // typedef void fn(int);
6941193326Sed    // fn f;
6942193326Sed    // @endcode
6943198092Srdivacky
6944193326Sed    // Synthesize a parameter for each argument type.
6945193326Sed    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6946193326Sed         AE = FT->arg_type_end(); AI != AE; ++AI) {
6947210299Sed      ParmVarDecl *Param =
6948210299Sed        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6949221345Sdim      Param->setScopeInfo(0, Params.size());
6950193326Sed      Params.push_back(Param);
6951193326Sed    }
6952193326Sed  } else {
6953193326Sed    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6954193326Sed           "Should not need args for typedef of non-prototype fn");
6955193326Sed  }
6956226633Sdim
6957193326Sed  // Finally, we know we have the right number of parameters, install them.
6958226633Sdim  NewFD->setParams(Params);
6959198092Srdivacky
6960234353Sdim  // Find all anonymous symbols defined during the declaration of this function
6961234353Sdim  // and add to NewFD. This lets us track decls such 'enum Y' in:
6962234353Sdim  //
6963234353Sdim  //   void f(enum Y {AA} x) {}
6964234353Sdim  //
6965234353Sdim  // which would otherwise incorrectly end up in the translation unit scope.
6966234353Sdim  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6967234353Sdim  DeclsInPrototypeScope.clear();
6968234353Sdim
6969249423Sdim  if (D.getDeclSpec().isNoreturnSpecified())
6970249423Sdim    NewFD->addAttr(
6971249423Sdim        ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6972249423Sdim                                       Context));
6973249423Sdim
6974234353Sdim  // Functions returning a variably modified type violate C99 6.7.5.2p2
6975234353Sdim  // because all functions have linkage.
6976234353Sdim  if (!NewFD->isInvalidDecl() &&
6977234353Sdim      NewFD->getResultType()->isVariablyModifiedType()) {
6978234353Sdim    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6979234353Sdim    NewFD->setInvalidDecl();
6980234353Sdim  }
6981234353Sdim
6982239462Sdim  // Handle attributes.
6983263508Sdim  ProcessDeclAttributes(S, NewFD, D);
6984239462Sdim
6985249423Sdim  QualType RetType = NewFD->getResultType();
6986249423Sdim  const CXXRecordDecl *Ret = RetType->isRecordType() ?
6987249423Sdim      RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6988249423Sdim  if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6989249423Sdim      Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6990249423Sdim    const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6991263508Sdim    // Attach the attribute to the new decl. Don't apply the attribute if it
6992263508Sdim    // returns an instance of the class (e.g. assignment operators).
6993263508Sdim    if (!MD || MD->getParent() != Ret) {
6994249423Sdim      NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6995249423Sdim                                                        Context));
6996249423Sdim    }
6997249423Sdim  }
6998249423Sdim
6999234353Sdim  if (!getLangOpts().CPlusPlus) {
7000218893Sdim    // Perform semantic checking on the function declaration.
7001223017Sdim    bool isExplicitSpecialization=false;
7002263508Sdim    if (!NewFD->isInvalidDecl() && NewFD->isMain())
7003263508Sdim      CheckMain(NewFD, D.getDeclSpec());
7004263508Sdim
7005263508Sdim    if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7006263508Sdim      CheckMSVCRTEntryPoint(NewFD);
7007263508Sdim
7008263508Sdim    if (!NewFD->isInvalidDecl())
7009234353Sdim      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7010234353Sdim                                                  isExplicitSpecialization));
7011243830Sdim    else if (!Previous.empty())
7012263508Sdim      // Make graceful recovery from an invalid redeclaration.
7013263508Sdim      D.setRedeclaration(true);
7014226633Sdim    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7015218893Sdim            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7016218893Sdim           "previous declaration set still overloaded");
7017218893Sdim  } else {
7018263508Sdim    // C++11 [replacement.functions]p3:
7019263508Sdim    //  The program's definitions shall not be specified as inline.
7020263508Sdim    //
7021263508Sdim    // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7022263508Sdim    //
7023263508Sdim    // Suppress the diagnostic if the function is __attribute__((used)), since
7024263508Sdim    // that forces an external definition to be emitted.
7025263508Sdim    if (D.getDeclSpec().isInlineSpecified() &&
7026263508Sdim        NewFD->isReplaceableGlobalAllocationFunction() &&
7027263508Sdim        !NewFD->hasAttr<UsedAttr>())
7028263508Sdim      Diag(D.getDeclSpec().getInlineSpecLoc(),
7029263508Sdim           diag::ext_operator_new_delete_declared_inline)
7030263508Sdim        << NewFD->getDeclName();
7031263508Sdim
7032218893Sdim    // If the declarator is a template-id, translate the parser's template
7033218893Sdim    // argument list into our AST format.
7034218893Sdim    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7035218893Sdim      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7036218893Sdim      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7037218893Sdim      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7038243830Sdim      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7039218893Sdim                                         TemplateId->NumArgs);
7040218893Sdim      translateTemplateArguments(TemplateArgsPtr,
7041218893Sdim                                 TemplateArgs);
7042198092Srdivacky
7043218893Sdim      HasExplicitTemplateArgs = true;
7044198092Srdivacky
7045223017Sdim      if (NewFD->isInvalidDecl()) {
7046223017Sdim        HasExplicitTemplateArgs = false;
7047223017Sdim      } else if (FunctionTemplate) {
7048218893Sdim        // Function template with explicit template arguments.
7049218893Sdim        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7050218893Sdim          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7051218893Sdim
7052218893Sdim        HasExplicitTemplateArgs = false;
7053218893Sdim      } else if (!isFunctionTemplateSpecialization &&
7054218893Sdim                 !D.getDeclSpec().isFriendSpecified()) {
7055218893Sdim        // We have encountered something that the user meant to be a
7056218893Sdim        // specialization (because it has explicitly-specified template
7057218893Sdim        // arguments) but that was not introduced with a "template<>" (or had
7058218893Sdim        // too few of them).
7059263508Sdim        // FIXME: Differentiate between attempts for explicit instantiations
7060263508Sdim        // (starting with "template") and the rest.
7061218893Sdim        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7062218893Sdim          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7063218893Sdim          << FixItHint::CreateInsertion(
7064234353Sdim                                    D.getDeclSpec().getLocStart(),
7065234353Sdim                                        "template<> ");
7066218893Sdim        isFunctionTemplateSpecialization = true;
7067218893Sdim      } else {
7068218893Sdim        // "friend void foo<>(int);" is an implicit specialization decl.
7069218893Sdim        isFunctionTemplateSpecialization = true;
7070218893Sdim      }
7071218893Sdim    } else if (isFriend && isFunctionTemplateSpecialization) {
7072218893Sdim      // This combination is only possible in a recovery case;  the user
7073218893Sdim      // wrote something like:
7074218893Sdim      //   template <> friend void foo(int);
7075218893Sdim      // which we're recovering from as if the user had written:
7076218893Sdim      //   friend void foo<>(int);
7077218893Sdim      // Go ahead and fake up a template id.
7078218893Sdim      HasExplicitTemplateArgs = true;
7079218893Sdim        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7080218893Sdim      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7081198092Srdivacky    }
7082199512Srdivacky
7083218893Sdim    // If it's a friend (and only if it's a friend), it's possible
7084218893Sdim    // that either the specialized function type or the specialized
7085218893Sdim    // template is dependent, and therefore matching will fail.  In
7086218893Sdim    // this case, don't check the specialization yet.
7087226633Sdim    bool InstantiationDependent = false;
7088218893Sdim    if (isFunctionTemplateSpecialization && isFriend &&
7089226633Sdim        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7090226633Sdim         TemplateSpecializationType::anyDependentTemplateArguments(
7091226633Sdim            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7092226633Sdim            InstantiationDependent))) {
7093218893Sdim      assert(HasExplicitTemplateArgs &&
7094218893Sdim             "friend function specialization without template args");
7095218893Sdim      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7096218893Sdim                                                       Previous))
7097218893Sdim        NewFD->setInvalidDecl();
7098218893Sdim    } else if (isFunctionTemplateSpecialization) {
7099221345Sdim      if (CurContext->isDependentContext() && CurContext->isRecord()
7100221345Sdim          && !isFriend) {
7101226633Sdim        isDependentClassScopeExplicitSpecialization = true;
7102234353Sdim        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7103226633Sdim          diag::ext_function_specialization_in_class :
7104226633Sdim          diag::err_function_specialization_in_class)
7105221345Sdim          << NewFD->getDeclName();
7106221345Sdim      } else if (CheckFunctionTemplateSpecialization(NewFD,
7107221345Sdim                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7108221345Sdim                                                     Previous))
7109221345Sdim        NewFD->setInvalidDecl();
7110223017Sdim
7111223017Sdim      // C++ [dcl.stc]p1:
7112223017Sdim      //   A storage-class-specifier shall not be specified in an explicit
7113223017Sdim      //   specialization (14.7.3)
7114263508Sdim      FunctionTemplateSpecializationInfo *Info =
7115263508Sdim          NewFD->getTemplateSpecializationInfo();
7116263508Sdim      if (Info && SC != SC_None) {
7117263508Sdim        if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7118224145Sdim          Diag(NewFD->getLocation(),
7119224145Sdim               diag::err_explicit_specialization_inconsistent_storage_class)
7120224145Sdim            << SC
7121224145Sdim            << FixItHint::CreateRemoval(
7122224145Sdim                                      D.getDeclSpec().getStorageClassSpecLoc());
7123224145Sdim
7124224145Sdim        else
7125224145Sdim          Diag(NewFD->getLocation(),
7126224145Sdim               diag::ext_explicit_specialization_storage_class)
7127224145Sdim            << FixItHint::CreateRemoval(
7128224145Sdim                                      D.getDeclSpec().getStorageClassSpecLoc());
7129223017Sdim      }
7130223017Sdim
7131218893Sdim    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7132218893Sdim      if (CheckMemberSpecialization(NewFD, Previous))
7133218893Sdim          NewFD->setInvalidDecl();
7134218893Sdim    }
7135207619Srdivacky
7136218893Sdim    // Perform semantic checking on the function declaration.
7137226633Sdim    if (!isDependentClassScopeExplicitSpecialization) {
7138263508Sdim      if (!NewFD->isInvalidDecl() && NewFD->isMain())
7139263508Sdim        CheckMain(NewFD, D.getDeclSpec());
7140263508Sdim
7141263508Sdim      if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7142263508Sdim        CheckMSVCRTEntryPoint(NewFD);
7143263508Sdim
7144226633Sdim      if (NewFD->isInvalidDecl()) {
7145226633Sdim        // If this is a class member, mark the class invalid immediately.
7146226633Sdim        // This avoids some consistency errors later.
7147226633Sdim        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7148226633Sdim          methodDecl->getParent()->setInvalidDecl();
7149263508Sdim      } else
7150226633Sdim        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7151226633Sdim                                                    isExplicitSpecialization));
7152226633Sdim    }
7153193326Sed
7154226633Sdim    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7155218893Sdim            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7156218893Sdim           "previous declaration set still overloaded");
7157199512Srdivacky
7158218893Sdim    NamedDecl *PrincipalDecl = (FunctionTemplate
7159218893Sdim                                ? cast<NamedDecl>(FunctionTemplate)
7160218893Sdim                                : NewFD);
7161207619Srdivacky
7162226633Sdim    if (isFriend && D.isRedeclaration()) {
7163218893Sdim      AccessSpecifier Access = AS_public;
7164218893Sdim      if (!NewFD->isInvalidDecl())
7165234353Sdim        Access = NewFD->getPreviousDecl()->getAccess();
7166207619Srdivacky
7167218893Sdim      NewFD->setAccess(Access);
7168218893Sdim      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7169218893Sdim    }
7170206084Srdivacky
7171218893Sdim    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7172218893Sdim        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7173218893Sdim      PrincipalDecl->setNonMemberOperator();
7174207619Srdivacky
7175218893Sdim    // If we have a function template, check the template parameter
7176218893Sdim    // list. This will check and merge default template arguments.
7177218893Sdim    if (FunctionTemplate) {
7178234353Sdim      FunctionTemplateDecl *PrevTemplate =
7179234353Sdim                                     FunctionTemplate->getPreviousDecl();
7180218893Sdim      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7181234353Sdim                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7182218893Sdim                            D.getDeclSpec().isFriendSpecified()
7183226633Sdim                              ? (D.isFunctionDefinition()
7184218893Sdim                                   ? TPC_FriendFunctionTemplateDefinition
7185218893Sdim                                   : TPC_FriendFunctionTemplate)
7186218893Sdim                              : (D.getCXXScopeSpec().isSet() &&
7187218893Sdim                                 DC && DC->isRecord() &&
7188218893Sdim                                 DC->isDependentContext())
7189218893Sdim                                  ? TPC_ClassTemplateMember
7190218893Sdim                                  : TPC_FunctionTemplate);
7191218893Sdim    }
7192199990Srdivacky
7193218893Sdim    if (NewFD->isInvalidDecl()) {
7194218893Sdim      // Ignore all the rest of this.
7195226633Sdim    } else if (!D.isRedeclaration()) {
7196226633Sdim      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7197226633Sdim                                       AddToScope };
7198218893Sdim      // Fake up an access specifier if it's supposed to be a class member.
7199218893Sdim      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7200218893Sdim        NewFD->setAccess(AS_public);
7201202879Srdivacky
7202218893Sdim      // Qualified decls generally require a previous declaration.
7203218893Sdim      if (D.getCXXScopeSpec().isSet()) {
7204218893Sdim        // ...with the major exception of templated-scope or
7205218893Sdim        // dependent-scope friend declarations.
7206218893Sdim
7207218893Sdim        // TODO: we currently also suppress this check in dependent
7208218893Sdim        // contexts because (1) the parameter depth will be off when
7209218893Sdim        // matching friend templates and (2) we might actually be
7210218893Sdim        // selecting a friend based on a dependent factor.  But there
7211218893Sdim        // are situations where these conditions don't apply and we
7212218893Sdim        // can actually do this check immediately.
7213218893Sdim        if (isFriend &&
7214221345Sdim            (TemplateParamLists.size() ||
7215218893Sdim             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7216218893Sdim             CurContext->isDependentContext())) {
7217226633Sdim          // ignore these
7218226633Sdim        } else {
7219226633Sdim          // The user tried to provide an out-of-line definition for a
7220226633Sdim          // function that is a member of a class or namespace, but there
7221226633Sdim          // was no such member function declared (C++ [class.mfct]p2,
7222226633Sdim          // C++ [namespace.memdef]p2). For example:
7223226633Sdim          //
7224226633Sdim          // class X {
7225226633Sdim          //   void f() const;
7226226633Sdim          // };
7227226633Sdim          //
7228226633Sdim          // void X::f() { } // ill-formed
7229226633Sdim          //
7230226633Sdim          // Complain about this problem, and attempt to suggest close
7231226633Sdim          // matches (e.g., those that differ only in cv-qualifiers and
7232226633Sdim          // whether the parameter types are references).
7233218893Sdim
7234263508Sdim          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7235263508Sdim                  *this, Previous, NewFD, ExtraArgs, false, 0)) {
7236226633Sdim            AddToScope = ExtraArgs.AddToScope;
7237226633Sdim            return Result;
7238226633Sdim          }
7239226633Sdim        }
7240218893Sdim
7241218893Sdim        // Unqualified local friend declarations are required to resolve
7242218893Sdim        // to something.
7243226633Sdim      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7244263508Sdim        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7245263508Sdim                *this, Previous, NewFD, ExtraArgs, true, S)) {
7246226633Sdim          AddToScope = ExtraArgs.AddToScope;
7247226633Sdim          return Result;
7248218893Sdim        }
7249226633Sdim      }
7250218893Sdim
7251226633Sdim    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
7252218893Sdim               !isFriend && !isFunctionTemplateSpecialization &&
7253218893Sdim               !isExplicitSpecialization) {
7254218893Sdim      // An out-of-line member function declaration must also be a
7255218893Sdim      // definition (C++ [dcl.meaning]p1).
7256218893Sdim      // Note that this is not the case for explicit specializations of
7257218893Sdim      // function templates or member functions of class templates, per
7258234353Sdim      // C++ [temp.expl.spec]p2. We also allow these declarations as an
7259234353Sdim      // extension for compatibility with old SWIG code which likes to
7260234353Sdim      // generate them.
7261212904Sdim      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7262193326Sed        << D.getCXXScopeSpec().getRange();
7263212904Sdim    }
7264193326Sed  }
7265198092Srdivacky
7266249423Sdim  ProcessPragmaWeak(S, NewFD);
7267249423Sdim  checkAttributesAfterMerging(*this, *NewFD);
7268249423Sdim
7269193326Sed  AddKnownFunctionAttributes(NewFD);
7270193326Sed
7271212904Sdim  if (NewFD->hasAttr<OverloadableAttr>() &&
7272212904Sdim      !NewFD->getType()->getAs<FunctionProtoType>()) {
7273212904Sdim    Diag(NewFD->getLocation(),
7274212904Sdim         diag::err_attribute_overloadable_no_prototype)
7275212904Sdim      << NewFD;
7276212904Sdim
7277212904Sdim    // Turn this into a variadic function with no parameters.
7278212904Sdim    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7279263508Sdim    FunctionProtoType::ExtProtoInfo EPI(
7280263508Sdim        Context.getDefaultCallingConvention(true, false));
7281218893Sdim    EPI.Variadic = true;
7282218893Sdim    EPI.ExtInfo = FT->getExtInfo();
7283218893Sdim
7284251662Sdim    QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
7285212904Sdim    NewFD->setType(R);
7286212904Sdim  }
7287212904Sdim
7288212904Sdim  // If there's a #pragma GCC visibility in scope, and this isn't a class
7289212904Sdim  // member, set the visibility of this function.
7290263508Sdim  if (!DC->isRecord() && NewFD->isExternallyVisible())
7291212904Sdim    AddPushedVisibilityAttribute(NewFD);
7292212904Sdim
7293226633Sdim  // If there's a #pragma clang arc_cf_code_audited in scope, consider
7294226633Sdim  // marking the function.
7295226633Sdim  AddCFAuditedAttribute(NewFD);
7296226633Sdim
7297263508Sdim  // If this is the first declaration of an extern C variable, update
7298263508Sdim  // the map of such variables.
7299263508Sdim  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7300263508Sdim      isIncompleteDeclExternC(*this, NewFD))
7301263508Sdim    RegisterLocallyScopedExternCDecl(NewFD, S);
7302193326Sed
7303195099Sed  // Set this FunctionDecl's range up to the right paren.
7304221345Sdim  NewFD->setRangeEnd(D.getSourceRange().getEnd());
7305195099Sed
7306234353Sdim  if (getLangOpts().CPlusPlus) {
7307218893Sdim    if (FunctionTemplate) {
7308218893Sdim      if (NewFD->isInvalidDecl())
7309218893Sdim        FunctionTemplate->setInvalidDecl();
7310218893Sdim      return FunctionTemplate;
7311218893Sdim    }
7312218893Sdim  }
7313198092Srdivacky
7314249423Sdim  if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7315249423Sdim    // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7316249423Sdim    if ((getLangOpts().OpenCLVersion >= 120)
7317249423Sdim        && (SC == SC_Static)) {
7318249423Sdim      Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7319249423Sdim      D.setInvalidType();
7320249423Sdim    }
7321249423Sdim
7322249423Sdim    // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7323249423Sdim    if (!NewFD->getResultType()->isVoidType()) {
7324249423Sdim      Diag(D.getIdentifierLoc(),
7325249423Sdim           diag::err_expected_kernel_void_return_type);
7326249423Sdim      D.setInvalidType();
7327249423Sdim    }
7328263508Sdim
7329263508Sdim    llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7330249423Sdim    for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7331249423Sdim         PE = NewFD->param_end(); PI != PE; ++PI) {
7332249423Sdim      ParmVarDecl *Param = *PI;
7333263508Sdim      checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7334249423Sdim    }
7335239462Sdim  }
7336239462Sdim
7337212904Sdim  MarkUnusedFileScopedDecl(NewFD);
7338212904Sdim
7339234353Sdim  if (getLangOpts().CUDA)
7340218893Sdim    if (IdentifierInfo *II = NewFD->getIdentifier())
7341218893Sdim      if (!NewFD->isInvalidDecl() &&
7342218893Sdim          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7343218893Sdim        if (II->isStr("cudaConfigureCall")) {
7344218893Sdim          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7345218893Sdim            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7346218893Sdim
7347218893Sdim          Context.setcudaConfigureCallDecl(NewFD);
7348218893Sdim        }
7349218893Sdim      }
7350226633Sdim
7351226633Sdim  // Here we have an function template explicit specialization at class scope.
7352226633Sdim  // The actually specialization will be postponed to template instatiation
7353226633Sdim  // time via the ClassScopeFunctionSpecializationDecl node.
7354226633Sdim  if (isDependentClassScopeExplicitSpecialization) {
7355226633Sdim    ClassScopeFunctionSpecializationDecl *NewSpec =
7356226633Sdim                         ClassScopeFunctionSpecializationDecl::Create(
7357239462Sdim                                Context, CurContext, SourceLocation(),
7358239462Sdim                                cast<CXXMethodDecl>(NewFD),
7359239462Sdim                                HasExplicitTemplateArgs, TemplateArgs);
7360226633Sdim    CurContext->addDecl(NewSpec);
7361226633Sdim    AddToScope = false;
7362226633Sdim  }
7363218893Sdim
7364193326Sed  return NewFD;
7365193326Sed}
7366193326Sed
7367193326Sed/// \brief Perform semantic checking of a new function declaration.
7368193326Sed///
7369193326Sed/// Performs semantic analysis of the new function declaration
7370193326Sed/// NewFD. This routine performs all semantic checking that does not
7371193326Sed/// require the actual declarator involved in the declaration, and is
7372193326Sed/// used both for the declaration of functions as they are parsed
7373193326Sed/// (called via ActOnDeclarator) and for the declaration of functions
7374193326Sed/// that have been instantiated via C++ template instantiation (called
7375193326Sed/// via InstantiateDecl).
7376193326Sed///
7377239462Sdim/// \param IsExplicitSpecialization whether this new function declaration is
7378198092Srdivacky/// an explicit specialization of the previous declaration.
7379198092Srdivacky///
7380193326Sed/// This sets NewFD->isInvalidDecl() to true if there was an error.
7381226633Sdim///
7382239462Sdim/// \returns true if the function declaration is a redeclaration.
7383226633Sdimbool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7384199512Srdivacky                                    LookupResult &Previous,
7385226633Sdim                                    bool IsExplicitSpecialization) {
7386226633Sdim  assert(!NewFD->getResultType()->isVariablyModifiedType()
7387226633Sdim         && "Variably modified return types are not handled here");
7388212904Sdim
7389263508Sdim  // Determine whether the type of this function should be merged with
7390263508Sdim  // a previous visible declaration. This never happens for functions in C++,
7391263508Sdim  // and always happens in C if the previous declaration was visible.
7392263508Sdim  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7393263508Sdim                               !Previous.isShadowed();
7394193326Sed
7395249423Sdim  // Filter out any non-conflicting previous declarations.
7396249423Sdim  filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7397249423Sdim
7398226633Sdim  bool Redeclaration = false;
7399249423Sdim  NamedDecl *OldDecl = 0;
7400226633Sdim
7401193326Sed  // Merge or overload the declaration with an existing declaration of
7402193326Sed  // the same name, if appropriate.
7403199512Srdivacky  if (!Previous.empty()) {
7404193326Sed    // Determine whether NewFD is an overload of PrevDecl or
7405193326Sed    // a declaration that requires merging. If it's an overload,
7406193326Sed    // there's no more work to do here; we'll just add the new
7407193326Sed    // function to the scope.
7408200583Srdivacky    if (!AllowOverloadingOfFunction(Previous, Context)) {
7409251662Sdim      NamedDecl *Candidate = Previous.getFoundDecl();
7410251662Sdim      if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7411251662Sdim        Redeclaration = true;
7412251662Sdim        OldDecl = Candidate;
7413251662Sdim      }
7414200583Srdivacky    } else {
7415210299Sed      switch (CheckOverload(S, NewFD, Previous, OldDecl,
7416210299Sed                            /*NewIsUsingDecl*/ false)) {
7417200583Srdivacky      case Ovl_Match:
7418199512Srdivacky        Redeclaration = true;
7419200583Srdivacky        break;
7420200583Srdivacky
7421200583Srdivacky      case Ovl_NonFunction:
7422200583Srdivacky        Redeclaration = true;
7423200583Srdivacky        break;
7424200583Srdivacky
7425200583Srdivacky      case Ovl_Overload:
7426200583Srdivacky        Redeclaration = false;
7427200583Srdivacky        break;
7428199512Srdivacky      }
7429218893Sdim
7430234353Sdim      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7431218893Sdim        // If a function name is overloadable in C, then every function
7432218893Sdim        // with that name must be marked "overloadable".
7433218893Sdim        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7434218893Sdim          << Redeclaration << NewFD;
7435218893Sdim        NamedDecl *OverloadedDecl = 0;
7436218893Sdim        if (Redeclaration)
7437218893Sdim          OverloadedDecl = OldDecl;
7438218893Sdim        else if (!Previous.empty())
7439218893Sdim          OverloadedDecl = Previous.getRepresentativeDecl();
7440218893Sdim        if (OverloadedDecl)
7441218893Sdim          Diag(OverloadedDecl->getLocation(),
7442218893Sdim               diag::note_attribute_overloadable_prev_overload);
7443218893Sdim        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7444218893Sdim                                                        Context));
7445218893Sdim      }
7446199512Srdivacky    }
7447249423Sdim  }
7448193326Sed
7449263508Sdim  // Check for a previous extern "C" declaration with this name.
7450263508Sdim  if (!Redeclaration &&
7451263508Sdim      checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7452263508Sdim    filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7453263508Sdim    if (!Previous.empty()) {
7454263508Sdim      // This is an extern "C" declaration with the same name as a previous
7455263508Sdim      // declaration, and thus redeclares that entity...
7456263508Sdim      Redeclaration = true;
7457263508Sdim      OldDecl = Previous.getFoundDecl();
7458263508Sdim      MergeTypeWithPrevious = false;
7459263508Sdim
7460263508Sdim      // ... except in the presence of __attribute__((overloadable)).
7461263508Sdim      if (OldDecl->hasAttr<OverloadableAttr>()) {
7462263508Sdim        if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7463263508Sdim          Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7464263508Sdim            << Redeclaration << NewFD;
7465263508Sdim          Diag(Previous.getFoundDecl()->getLocation(),
7466263508Sdim               diag::note_attribute_overloadable_prev_overload);
7467263508Sdim          NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7468263508Sdim                                                          Context));
7469263508Sdim        }
7470263508Sdim        if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7471263508Sdim          Redeclaration = false;
7472263508Sdim          OldDecl = 0;
7473263508Sdim        }
7474263508Sdim      }
7475263508Sdim    }
7476263508Sdim  }
7477263508Sdim
7478249423Sdim  // C++11 [dcl.constexpr]p8:
7479249423Sdim  //   A constexpr specifier for a non-static member function that is not
7480249423Sdim  //   a constructor declares that member function to be const.
7481249423Sdim  //
7482249423Sdim  // This needs to be delayed until we know whether this is an out-of-line
7483249423Sdim  // definition of a static member function.
7484251662Sdim  //
7485251662Sdim  // This rule is not present in C++1y, so we produce a backwards
7486251662Sdim  // compatibility warning whenever it happens in C++11.
7487249423Sdim  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7488251662Sdim  if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7489251662Sdim      !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7490249423Sdim      (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7491249423Sdim    CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7492249423Sdim    if (FunctionTemplateDecl *OldTD =
7493249423Sdim          dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7494249423Sdim      OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7495249423Sdim    if (!OldMD || !OldMD->isStatic()) {
7496249423Sdim      const FunctionProtoType *FPT =
7497249423Sdim        MD->getType()->castAs<FunctionProtoType>();
7498249423Sdim      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7499249423Sdim      EPI.TypeQuals |= Qualifiers::Const;
7500249423Sdim      MD->setType(Context.getFunctionType(FPT->getResultType(),
7501263508Sdim                                          FPT->getArgTypes(), EPI));
7502251662Sdim
7503251662Sdim      // Warn that we did this, if we're not performing template instantiation.
7504251662Sdim      // In that case, we'll have warned already when the template was defined.
7505251662Sdim      if (ActiveTemplateInstantiations.empty()) {
7506251662Sdim        SourceLocation AddConstLoc;
7507251662Sdim        if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7508251662Sdim                .IgnoreParens().getAs<FunctionTypeLoc>())
7509251662Sdim          AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7510251662Sdim
7511251662Sdim        Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7512251662Sdim          << FixItHint::CreateInsertion(AddConstLoc, " const");
7513251662Sdim      }
7514249423Sdim    }
7515249423Sdim  }
7516249423Sdim
7517249423Sdim  if (Redeclaration) {
7518249423Sdim    // NewFD and OldDecl represent declarations that need to be
7519249423Sdim    // merged.
7520263508Sdim    if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7521249423Sdim      NewFD->setInvalidDecl();
7522249423Sdim      return Redeclaration;
7523249423Sdim    }
7524249423Sdim
7525249423Sdim    Previous.clear();
7526249423Sdim    Previous.addDecl(OldDecl);
7527249423Sdim
7528249423Sdim    if (FunctionTemplateDecl *OldTemplateDecl
7529249423Sdim                                  = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7530249423Sdim      NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7531249423Sdim      FunctionTemplateDecl *NewTemplateDecl
7532249423Sdim        = NewFD->getDescribedFunctionTemplate();
7533249423Sdim      assert(NewTemplateDecl && "Template/non-template mismatch");
7534249423Sdim      if (CXXMethodDecl *Method
7535249423Sdim            = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7536249423Sdim        Method->setAccess(OldTemplateDecl->getAccess());
7537249423Sdim        NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7538226633Sdim      }
7539249423Sdim
7540249423Sdim      // If this is an explicit specialization of a member that is a function
7541249423Sdim      // template, mark it as a member specialization.
7542249423Sdim      if (IsExplicitSpecialization &&
7543249423Sdim          NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7544249423Sdim        NewTemplateDecl->setMemberSpecialization();
7545249423Sdim        assert(OldTemplateDecl->isMemberSpecialization());
7546249423Sdim      }
7547249423Sdim
7548249423Sdim    } else {
7549249423Sdim      // This needs to happen first so that 'inline' propagates.
7550249423Sdim      NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7551193326Sed
7552249423Sdim      if (isa<CXXMethodDecl>(NewFD)) {
7553249423Sdim        // A valid redeclaration of a C++ method must be out-of-line,
7554249423Sdim        // but (unfortunately) it's not necessarily a definition
7555249423Sdim        // because of templates, which means that the previous
7556249423Sdim        // declaration is not necessarily from the class definition.
7557199512Srdivacky
7558249423Sdim        // For just setting the access, that doesn't matter.
7559249423Sdim        CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7560249423Sdim        NewFD->setAccess(oldMethod->getAccess());
7561249423Sdim
7562249423Sdim        // Update the key-function state if necessary for this ABI.
7563249423Sdim        if (NewFD->isInlined() &&
7564249423Sdim            !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7565249423Sdim          // setNonKeyFunction needs to work with the original
7566249423Sdim          // declaration from the class definition, and isVirtual() is
7567249423Sdim          // just faster in that case, so map back to that now.
7568263508Sdim          oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7569249423Sdim          if (oldMethod->isVirtual()) {
7570249423Sdim            Context.setNonKeyFunction(oldMethod);
7571249423Sdim          }
7572198092Srdivacky        }
7573198092Srdivacky      }
7574193326Sed    }
7575193326Sed  }
7576193326Sed
7577198092Srdivacky  // Semantic checking for this function declaration (in isolation).
7578234353Sdim  if (getLangOpts().CPlusPlus) {
7579198092Srdivacky    // C++-specific checks.
7580198092Srdivacky    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7581198092Srdivacky      CheckConstructor(Constructor);
7582199482Srdivacky    } else if (CXXDestructorDecl *Destructor =
7583199482Srdivacky                dyn_cast<CXXDestructorDecl>(NewFD)) {
7584199482Srdivacky      CXXRecordDecl *Record = Destructor->getParent();
7585198092Srdivacky      QualType ClassType = Context.getTypeDeclType(Record);
7586199482Srdivacky
7587210299Sed      // FIXME: Shouldn't we be able to perform this check even when the class
7588199482Srdivacky      // type is dependent? Both gcc and edg can handle that.
7589198092Srdivacky      if (!ClassType->isDependentType()) {
7590198092Srdivacky        DeclarationName Name
7591198092Srdivacky          = Context.DeclarationNames.getCXXDestructorName(
7592198092Srdivacky                                        Context.getCanonicalType(ClassType));
7593198092Srdivacky        if (NewFD->getDeclName() != Name) {
7594198092Srdivacky          Diag(NewFD->getLocation(), diag::err_destructor_name);
7595226633Sdim          NewFD->setInvalidDecl();
7596226633Sdim          return Redeclaration;
7597198092Srdivacky        }
7598198092Srdivacky      }
7599198092Srdivacky    } else if (CXXConversionDecl *Conversion
7600200583Srdivacky               = dyn_cast<CXXConversionDecl>(NewFD)) {
7601198092Srdivacky      ActOnConversionDeclarator(Conversion);
7602200583Srdivacky    }
7603198092Srdivacky
7604200583Srdivacky    // Find any virtual functions that this function overrides.
7605200583Srdivacky    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7606200583Srdivacky      if (!Method->isFunctionTemplateSpecialization() &&
7607243830Sdim          !Method->getDescribedFunctionTemplate() &&
7608243830Sdim          Method->isCanonicalDecl()) {
7609218893Sdim        if (AddOverriddenMethods(Method->getParent(), Method)) {
7610218893Sdim          // If the function was marked as "static", we have a problem.
7611218893Sdim          if (NewFD->getStorageClass() == SC_Static) {
7612243830Sdim            ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7613218893Sdim          }
7614218893Sdim        }
7615218893Sdim      }
7616234982Sdim
7617234982Sdim      if (Method->isStatic())
7618234982Sdim        checkThisInStaticMemberFunctionType(Method);
7619200583Srdivacky    }
7620200583Srdivacky
7621198092Srdivacky    // Extra checking for C++ overloaded operators (C++ [over.oper]).
7622198092Srdivacky    if (NewFD->isOverloadedOperator() &&
7623226633Sdim        CheckOverloadedOperatorDeclaration(NewFD)) {
7624226633Sdim      NewFD->setInvalidDecl();
7625226633Sdim      return Redeclaration;
7626226633Sdim    }
7627202379Srdivacky
7628202379Srdivacky    // Extra checking for C++0x literal operators (C++0x [over.literal]).
7629202379Srdivacky    if (NewFD->getLiteralIdentifier() &&
7630226633Sdim        CheckLiteralOperatorDeclaration(NewFD)) {
7631226633Sdim      NewFD->setInvalidDecl();
7632226633Sdim      return Redeclaration;
7633226633Sdim    }
7634202379Srdivacky
7635198092Srdivacky    // In C++, check default arguments now that we have merged decls. Unless
7636198092Srdivacky    // the lexical context is the class, because in this case this is done
7637198092Srdivacky    // during delayed parsing anyway.
7638198092Srdivacky    if (!CurContext->isRecord())
7639198092Srdivacky      CheckCXXDefaultArguments(NewFD);
7640263508Sdim
7641218893Sdim    // If this function declares a builtin function, check the type of this
7642218893Sdim    // declaration against the expected type for the builtin.
7643218893Sdim    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7644218893Sdim      ASTContext::GetBuiltinTypeError Error;
7645249423Sdim      LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7646218893Sdim      QualType T = Context.GetBuiltinType(BuiltinID, Error);
7647218893Sdim      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7648218893Sdim        // The type of this function differs from the type of the builtin,
7649218893Sdim        // so forget about the builtin entirely.
7650218893Sdim        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7651218893Sdim      }
7652218893Sdim    }
7653263508Sdim
7654234353Sdim    // If this function is declared as being extern "C", then check to see if
7655234353Sdim    // the function returns a UDT (class, struct, or union type) that is not C
7656234353Sdim    // compatible, and if it does, warn the user.
7657249423Sdim    // But, issue any diagnostic on the first declaration only.
7658249423Sdim    if (NewFD->isExternC() && Previous.empty()) {
7659234353Sdim      QualType R = NewFD->getResultType();
7660239462Sdim      if (R->isIncompleteType() && !R->isVoidType())
7661239462Sdim        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7662239462Sdim            << NewFD << R;
7663239462Sdim      else if (!R.isPODType(Context) && !R->isVoidType() &&
7664239462Sdim               !R->isObjCObjectPointerType())
7665239462Sdim        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7666234353Sdim    }
7667198092Srdivacky  }
7668226633Sdim  return Redeclaration;
7669193326Sed}
7670193326Sed
7671249423Sdimstatic SourceRange getResultSourceRange(const FunctionDecl *FD) {
7672249423Sdim  const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7673249423Sdim  if (!TSI)
7674249423Sdim    return SourceRange();
7675249423Sdim
7676249423Sdim  TypeLoc TL = TSI->getTypeLoc();
7677249423Sdim  FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7678249423Sdim  if (!FunctionTL)
7679249423Sdim    return SourceRange();
7680249423Sdim
7681249423Sdim  TypeLoc ResultTL = FunctionTL.getResultLoc();
7682249423Sdim  if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7683249423Sdim    return ResultTL.getSourceRange();
7684249423Sdim
7685249423Sdim  return SourceRange();
7686249423Sdim}
7687249423Sdim
7688226633Sdimvoid Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7689234353Sdim  // C++11 [basic.start.main]p3:  A program that declares main to be inline,
7690234353Sdim  //   static or constexpr is ill-formed.
7691249423Sdim  // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7692249423Sdim  //   appear in a declaration of main.
7693198092Srdivacky  // static main is not an error under C99, but we should warn about it.
7694249423Sdim  // We accept _Noreturn main as an extension.
7695226633Sdim  if (FD->getStorageClass() == SC_Static)
7696234353Sdim    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7697226633Sdim         ? diag::err_static_main : diag::warn_static_main)
7698226633Sdim      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7699226633Sdim  if (FD->isInlineSpecified())
7700226633Sdim    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7701226633Sdim      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7702249423Sdim  if (DS.isNoreturnSpecified()) {
7703249423Sdim    SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7704249423Sdim    SourceRange NoreturnRange(NoreturnLoc,
7705249423Sdim                              PP.getLocForEndOfToken(NoreturnLoc));
7706249423Sdim    Diag(NoreturnLoc, diag::ext_noreturn_main);
7707249423Sdim    Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7708249423Sdim      << FixItHint::CreateRemoval(NoreturnRange);
7709249423Sdim  }
7710234353Sdim  if (FD->isConstexpr()) {
7711234353Sdim    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7712234353Sdim      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7713234353Sdim    FD->setConstexpr(false);
7714234353Sdim  }
7715198092Srdivacky
7716263508Sdim  if (getLangOpts().OpenCL) {
7717263508Sdim    Diag(FD->getLocation(), diag::err_opencl_no_main)
7718263508Sdim        << FD->hasAttr<OpenCLKernelAttr>();
7719263508Sdim    FD->setInvalidDecl();
7720263508Sdim    return;
7721263508Sdim  }
7722263508Sdim
7723198092Srdivacky  QualType T = FD->getType();
7724198092Srdivacky  assert(T->isFunctionType() && "function decl is not of function type");
7725234353Sdim  const FunctionType* FT = T->castAs<FunctionType>();
7726198092Srdivacky
7727234353Sdim  // All the standards say that main() should should return 'int'.
7728234353Sdim  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7729234353Sdim    // In C and C++, main magically returns 0 if you fall off the end;
7730234353Sdim    // set the flag which tells us that.
7731234353Sdim    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7732234353Sdim    FD->setHasImplicitReturnZero(true);
7733234353Sdim
7734234353Sdim  // In C with GNU extensions we allow main() to have non-integer return
7735234353Sdim  // type, but we should warn about the extension, and we disable the
7736234353Sdim  // implicit-return-zero rule.
7737234353Sdim  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7738234353Sdim    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7739234353Sdim
7740249423Sdim    SourceRange ResultRange = getResultSourceRange(FD);
7741249423Sdim    if (ResultRange.isValid())
7742249423Sdim      Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7743249423Sdim          << FixItHint::CreateReplacement(ResultRange, "int");
7744249423Sdim
7745234353Sdim  // Otherwise, this is just a flat-out error.
7746234353Sdim  } else {
7747249423Sdim    SourceRange ResultRange = getResultSourceRange(FD);
7748249423Sdim    if (ResultRange.isValid())
7749249423Sdim      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7750249423Sdim          << FixItHint::CreateReplacement(ResultRange, "int");
7751249423Sdim    else
7752249423Sdim      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7753249423Sdim
7754198092Srdivacky    FD->setInvalidDecl(true);
7755198092Srdivacky  }
7756198092Srdivacky
7757198092Srdivacky  // Treat protoless main() as nullary.
7758198092Srdivacky  if (isa<FunctionNoProtoType>(FT)) return;
7759198092Srdivacky
7760198092Srdivacky  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7761198092Srdivacky  unsigned nparams = FTP->getNumArgs();
7762198092Srdivacky  assert(FD->getNumParams() == nparams);
7763198092Srdivacky
7764201361Srdivacky  bool HasExtraParameters = (nparams > 3);
7765201361Srdivacky
7766201361Srdivacky  // Darwin passes an undocumented fourth argument of type char**.  If
7767201361Srdivacky  // other platforms start sprouting these, the logic below will start
7768201361Srdivacky  // getting shifty.
7769226633Sdim  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7770201361Srdivacky    HasExtraParameters = false;
7771201361Srdivacky
7772201361Srdivacky  if (HasExtraParameters) {
7773198092Srdivacky    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7774198092Srdivacky    FD->setInvalidDecl(true);
7775198092Srdivacky    nparams = 3;
7776198092Srdivacky  }
7777198092Srdivacky
7778198092Srdivacky  // FIXME: a lot of the following diagnostics would be improved
7779198092Srdivacky  // if we had some location information about types.
7780198092Srdivacky
7781198092Srdivacky  QualType CharPP =
7782198092Srdivacky    Context.getPointerType(Context.getPointerType(Context.CharTy));
7783201361Srdivacky  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7784198092Srdivacky
7785198092Srdivacky  for (unsigned i = 0; i < nparams; ++i) {
7786198092Srdivacky    QualType AT = FTP->getArgType(i);
7787198092Srdivacky
7788198092Srdivacky    bool mismatch = true;
7789198092Srdivacky
7790198092Srdivacky    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7791198092Srdivacky      mismatch = false;
7792198092Srdivacky    else if (Expected[i] == CharPP) {
7793198092Srdivacky      // As an extension, the following forms are okay:
7794198092Srdivacky      //   char const **
7795198092Srdivacky      //   char const * const *
7796198092Srdivacky      //   char * const *
7797198092Srdivacky
7798198092Srdivacky      QualifierCollector qs;
7799198092Srdivacky      const PointerType* PT;
7800198092Srdivacky      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7801198092Srdivacky          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7802249423Sdim          Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7803249423Sdim                              Context.CharTy)) {
7804198092Srdivacky        qs.removeConst();
7805198092Srdivacky        mismatch = !qs.empty();
7806198092Srdivacky      }
7807198092Srdivacky    }
7808198092Srdivacky
7809198092Srdivacky    if (mismatch) {
7810198092Srdivacky      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7811198092Srdivacky      // TODO: suggest replacing given type with expected type
7812198092Srdivacky      FD->setInvalidDecl(true);
7813198092Srdivacky    }
7814198092Srdivacky  }
7815198092Srdivacky
7816198092Srdivacky  if (nparams == 1 && !FD->isInvalidDecl()) {
7817198092Srdivacky    Diag(FD->getLocation(), diag::warn_main_one_arg);
7818198092Srdivacky  }
7819218893Sdim
7820218893Sdim  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7821263508Sdim    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7822218893Sdim    FD->setInvalidDecl();
7823218893Sdim  }
7824198092Srdivacky}
7825198092Srdivacky
7826263508Sdimvoid Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7827263508Sdim  QualType T = FD->getType();
7828263508Sdim  assert(T->isFunctionType() && "function decl is not of function type");
7829263508Sdim  const FunctionType *FT = T->castAs<FunctionType>();
7830263508Sdim
7831263508Sdim  // Set an implicit return of 'zero' if the function can return some integral,
7832263508Sdim  // enumeration, pointer or nullptr type.
7833263508Sdim  if (FT->getResultType()->isIntegralOrEnumerationType() ||
7834263508Sdim      FT->getResultType()->isAnyPointerType() ||
7835263508Sdim      FT->getResultType()->isNullPtrType())
7836263508Sdim    // DllMain is exempt because a return value of zero means it failed.
7837263508Sdim    if (FD->getName() != "DllMain")
7838263508Sdim      FD->setHasImplicitReturnZero(true);
7839263508Sdim
7840263508Sdim  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7841263508Sdim    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7842263508Sdim    FD->setInvalidDecl();
7843263508Sdim  }
7844263508Sdim}
7845263508Sdim
7846193326Sedbool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7847193326Sed  // FIXME: Need strict checking.  In C89, we need to check for
7848193326Sed  // any assignment, increment, decrement, function-calls, or
7849193326Sed  // commas outside of a sizeof.  In C99, it's the same list,
7850193326Sed  // except that the aforementioned are allowed in unevaluated
7851193326Sed  // expressions.  Everything else falls under the
7852193326Sed  // "may accept other forms of constant expressions" exception.
7853193326Sed  // (We never end up here for C++, so the constant expression
7854193326Sed  // rules there don't matter.)
7855212904Sdim  if (Init->isConstantInitializer(Context, false))
7856193326Sed    return false;
7857193326Sed  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7858193326Sed    << Init->getSourceRange();
7859193326Sed  return true;
7860193326Sed}
7861193326Sed
7862221345Sdimnamespace {
7863221345Sdim  // Visits an initialization expression to see if OrigDecl is evaluated in
7864221345Sdim  // its own initialization and throws a warning if it does.
7865221345Sdim  class SelfReferenceChecker
7866221345Sdim      : public EvaluatedExprVisitor<SelfReferenceChecker> {
7867221345Sdim    Sema &S;
7868221345Sdim    Decl *OrigDecl;
7869226633Sdim    bool isRecordType;
7870226633Sdim    bool isPODType;
7871239462Sdim    bool isReferenceType;
7872221345Sdim
7873221345Sdim  public:
7874221345Sdim    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7875221345Sdim
7876221345Sdim    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7877226633Sdim                                                    S(S), OrigDecl(OrigDecl) {
7878226633Sdim      isPODType = false;
7879226633Sdim      isRecordType = false;
7880239462Sdim      isReferenceType = false;
7881226633Sdim      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7882226633Sdim        isPODType = VD->getType().isPODType(S.Context);
7883226633Sdim        isRecordType = VD->getType()->isRecordType();
7884239462Sdim        isReferenceType = VD->getType()->isReferenceType();
7885226633Sdim      }
7886226633Sdim    }
7887221345Sdim
7888239462Sdim    // For most expressions, the cast is directly above the DeclRefExpr.
7889239462Sdim    // For conditional operators, the cast can be outside the conditional
7890239462Sdim    // operator if both expressions are DeclRefExpr's.
7891239462Sdim    void HandleValue(Expr *E) {
7892243830Sdim      if (isReferenceType)
7893243830Sdim        return;
7894239462Sdim      E = E->IgnoreParenImpCasts();
7895239462Sdim      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7896239462Sdim        HandleDeclRefExpr(DRE);
7897239462Sdim        return;
7898239462Sdim      }
7899239462Sdim
7900239462Sdim      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7901239462Sdim        HandleValue(CO->getTrueExpr());
7902239462Sdim        HandleValue(CO->getFalseExpr());
7903243830Sdim        return;
7904239462Sdim      }
7905243830Sdim
7906243830Sdim      if (isa<MemberExpr>(E)) {
7907243830Sdim        Expr *Base = E->IgnoreParenImpCasts();
7908243830Sdim        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7909243830Sdim          // Check for static member variables and don't warn on them.
7910243830Sdim          if (!isa<FieldDecl>(ME->getMemberDecl()))
7911243830Sdim            return;
7912243830Sdim          Base = ME->getBase()->IgnoreParenImpCasts();
7913243830Sdim        }
7914243830Sdim        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7915243830Sdim          HandleDeclRefExpr(DRE);
7916243830Sdim        return;
7917243830Sdim      }
7918239462Sdim    }
7919239462Sdim
7920243830Sdim    // Reference types are handled here since all uses of references are
7921243830Sdim    // bad, not just r-value uses.
7922243830Sdim    void VisitDeclRefExpr(DeclRefExpr *E) {
7923243830Sdim      if (isReferenceType)
7924243830Sdim        HandleDeclRefExpr(E);
7925243830Sdim    }
7926243830Sdim
7927239462Sdim    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7928243830Sdim      if (E->getCastKind() == CK_LValueToRValue ||
7929239462Sdim          (isRecordType && E->getCastKind() == CK_NoOp))
7930239462Sdim        HandleValue(E->getSubExpr());
7931239462Sdim
7932239462Sdim      Inherited::VisitImplicitCastExpr(E);
7933239462Sdim    }
7934239462Sdim
7935226633Sdim    void VisitMemberExpr(MemberExpr *E) {
7936239462Sdim      // Don't warn on arrays since they can be treated as pointers.
7937226633Sdim      if (E->getType()->canDecayToPointerType()) return;
7938239462Sdim
7939243830Sdim      // Warn when a non-static method call is followed by non-static member
7940243830Sdim      // field accesses, which is followed by a DeclRefExpr.
7941243830Sdim      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7942243830Sdim      bool Warn = (MD && !MD->isStatic());
7943243830Sdim      Expr *Base = E->getBase()->IgnoreParenImpCasts();
7944243830Sdim      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7945243830Sdim        if (!isa<FieldDecl>(ME->getMemberDecl()))
7946243830Sdim          Warn = false;
7947243830Sdim        Base = ME->getBase()->IgnoreParenImpCasts();
7948243830Sdim      }
7949243830Sdim
7950243830Sdim      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7951243830Sdim        if (Warn)
7952226633Sdim          HandleDeclRefExpr(DRE);
7953243830Sdim        return;
7954243830Sdim      }
7955239462Sdim
7956243830Sdim      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7957243830Sdim      // Visit that expression.
7958243830Sdim      Visit(Base);
7959226633Sdim    }
7960226633Sdim
7961249423Sdim    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7962249423Sdim      if (E->getNumArgs() > 0)
7963249423Sdim        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7964249423Sdim          HandleDeclRefExpr(DRE);
7965249423Sdim
7966249423Sdim      Inherited::VisitCXXOperatorCallExpr(E);
7967249423Sdim    }
7968249423Sdim
7969226633Sdim    void VisitUnaryOperator(UnaryOperator *E) {
7970226633Sdim      // For POD record types, addresses of its own members are well-defined.
7971243830Sdim      if (E->getOpcode() == UO_AddrOf && isRecordType &&
7972243830Sdim          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7973243830Sdim        if (!isPODType)
7974243830Sdim          HandleValue(E->getSubExpr());
7975243830Sdim        return;
7976243830Sdim      }
7977226633Sdim      Inherited::VisitUnaryOperator(E);
7978251662Sdim    }
7979239462Sdim
7980239462Sdim    void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7981239462Sdim
7982226633Sdim    void HandleDeclRefExpr(DeclRefExpr *DRE) {
7983249423Sdim      Decl* ReferenceDecl = DRE->getDecl();
7984221345Sdim      if (OrigDecl != ReferenceDecl) return;
7985249423Sdim      unsigned diag;
7986249423Sdim      if (isReferenceType) {
7987249423Sdim        diag = diag::warn_uninit_self_reference_in_reference_init;
7988249423Sdim      } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7989249423Sdim        diag = diag::warn_static_self_reference_in_init;
7990249423Sdim      } else {
7991249423Sdim        diag = diag::warn_uninit_self_reference_in_init;
7992249423Sdim      }
7993249423Sdim
7994226633Sdim      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7995243830Sdim                            S.PDiag(diag)
7996243830Sdim                              << DRE->getNameInfo().getName()
7997223017Sdim                              << OrigDecl->getLocation()
7998226633Sdim                              << DRE->getSourceRange());
7999221345Sdim    }
8000221345Sdim  };
8001221345Sdim
8002243830Sdim  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8003243830Sdim  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8004243830Sdim                                 bool DirectInit) {
8005243830Sdim    // Parameters arguments are occassionially constructed with itself,
8006243830Sdim    // for instance, in recursive functions.  Skip them.
8007243830Sdim    if (isa<ParmVarDecl>(OrigDecl))
8008243830Sdim      return;
8009243830Sdim
8010243830Sdim    E = E->IgnoreParens();
8011243830Sdim
8012243830Sdim    // Skip checking T a = a where T is not a record or reference type.
8013243830Sdim    // Doing so is a way to silence uninitialized warnings.
8014243830Sdim    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8015243830Sdim      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8016243830Sdim        if (ICE->getCastKind() == CK_LValueToRValue)
8017243830Sdim          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8018243830Sdim            if (DRE->getDecl() == OrigDecl)
8019243830Sdim              return;
8020243830Sdim
8021243830Sdim    SelfReferenceChecker(S, OrigDecl).Visit(E);
8022243830Sdim  }
8023226633Sdim}
8024226633Sdim
8025193326Sed/// AddInitializerToDecl - Adds the initializer Init to the
8026193326Sed/// declaration dcl. If DirectInit is true, this is C++ direct
8027193326Sed/// initialization rather than copy initialization.
8028218893Sdimvoid Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8029218893Sdim                                bool DirectInit, bool TypeMayContainAuto) {
8030193326Sed  // If there is no declaration, there was an error parsing it.  Just ignore
8031193326Sed  // the initializer.
8032218893Sdim  if (RealDecl == 0 || RealDecl->isInvalidDecl())
8033193326Sed    return;
8034198092Srdivacky
8035193326Sed  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8036193326Sed    // With declarators parsed the way they are, the parser cannot
8037193326Sed    // distinguish between a normal initializer and a pure-specifier.
8038193326Sed    // Thus this grotesque test.
8039193326Sed    IntegerLiteral *IL;
8040193326Sed    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8041200583Srdivacky        Context.getCanonicalType(IL->getType()) == Context.IntTy)
8042200583Srdivacky      CheckPureMethod(Method, Init->getSourceRange());
8043200583Srdivacky    else {
8044193326Sed      Diag(Method->getLocation(), diag::err_member_function_initialization)
8045193326Sed        << Method->getDeclName() << Init->getSourceRange();
8046193326Sed      Method->setInvalidDecl();
8047193326Sed    }
8048193326Sed    return;
8049193326Sed  }
8050193326Sed
8051193326Sed  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8052193326Sed  if (!VDecl) {
8053224145Sdim    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8054224145Sdim    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8055193326Sed    RealDecl->setInvalidDecl();
8056193326Sed    return;
8057193326Sed  }
8058234353Sdim  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8059234353Sdim
8060234353Sdim  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8061251662Sdim  if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8062234353Sdim    Expr *DeduceInit = Init;
8063234353Sdim    // Initializer could be a C++ direct-initializer. Deduction only works if it
8064234353Sdim    // contains exactly one expression.
8065234353Sdim    if (CXXDirectInit) {
8066234353Sdim      if (CXXDirectInit->getNumExprs() == 0) {
8067234353Sdim        // It isn't possible to write this directly, but it is possible to
8068234353Sdim        // end up in this situation with "auto x(some_pack...);"
8069234353Sdim        Diag(CXXDirectInit->getLocStart(),
8070263508Sdim             VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8071263508Sdim                                    : diag::err_auto_var_init_no_expression)
8072234353Sdim          << VDecl->getDeclName() << VDecl->getType()
8073234353Sdim          << VDecl->getSourceRange();
8074234353Sdim        RealDecl->setInvalidDecl();
8075234353Sdim        return;
8076234353Sdim      } else if (CXXDirectInit->getNumExprs() > 1) {
8077234353Sdim        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8078263508Sdim             VDecl->isInitCapture()
8079263508Sdim                 ? diag::err_init_capture_multiple_expressions
8080263508Sdim                 : diag::err_auto_var_init_multiple_expressions)
8081234353Sdim          << VDecl->getDeclName() << VDecl->getType()
8082234353Sdim          << VDecl->getSourceRange();
8083234353Sdim        RealDecl->setInvalidDecl();
8084234353Sdim        return;
8085234353Sdim      } else {
8086234353Sdim        DeduceInit = CXXDirectInit->getExpr(0);
8087234353Sdim      }
8088234353Sdim    }
8089249423Sdim
8090249423Sdim    // Expressions default to 'id' when we're in a debugger.
8091249423Sdim    bool DefaultedToAuto = false;
8092249423Sdim    if (getLangOpts().DebuggerCastResultToId &&
8093249423Sdim        Init->getType() == Context.UnknownAnyTy) {
8094249423Sdim      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8095249423Sdim      if (Result.isInvalid()) {
8096249423Sdim        VDecl->setInvalidDecl();
8097249423Sdim        return;
8098249423Sdim      }
8099249423Sdim      Init = Result.take();
8100249423Sdim      DefaultedToAuto = true;
8101249423Sdim    }
8102251662Sdim
8103251662Sdim    QualType DeducedType;
8104234353Sdim    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8105234353Sdim            DAR_Failed)
8106234353Sdim      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8107251662Sdim    if (DeducedType.isNull()) {
8108218893Sdim      RealDecl->setInvalidDecl();
8109218893Sdim      return;
8110218893Sdim    }
8111251662Sdim    VDecl->setType(DeducedType);
8112249423Sdim    assert(VDecl->isLinkageValid());
8113249423Sdim
8114224145Sdim    // In ARC, infer lifetime.
8115234353Sdim    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8116224145Sdim      VDecl->setInvalidDecl();
8117224145Sdim
8118239462Sdim    // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8119239462Sdim    // 'id' instead of a specific object type prevents most of our usual checks.
8120239462Sdim    // We only want to warn outside of template instantiations, though:
8121239462Sdim    // inside a template, the 'id' could have come from a parameter.
8122249423Sdim    if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8123251662Sdim        DeducedType->isObjCIdType()) {
8124251662Sdim      SourceLocation Loc =
8125251662Sdim          VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8126239462Sdim      Diag(Loc, diag::warn_auto_var_is_id)
8127239462Sdim        << VDecl->getDeclName() << DeduceInit->getSourceRange();
8128239462Sdim    }
8129239462Sdim
8130218893Sdim    // If this is a redeclaration, check that the type we just deduced matches
8131218893Sdim    // the previously declared type.
8132263508Sdim    if (VarDecl *Old = VDecl->getPreviousDecl()) {
8133263508Sdim      // We never need to merge the type, because we cannot form an incomplete
8134263508Sdim      // array of auto, nor deduce such a type.
8135263508Sdim      MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8136263508Sdim    }
8137251662Sdim
8138251662Sdim    // Check the deduced type is valid for a variable declaration.
8139251662Sdim    CheckVariableDeclarationType(VDecl);
8140251662Sdim    if (VDecl->isInvalidDecl())
8141251662Sdim      return;
8142218893Sdim  }
8143212904Sdim
8144234353Sdim  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8145234353Sdim    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8146234353Sdim    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8147234353Sdim    VDecl->setInvalidDecl();
8148193326Sed    return;
8149193326Sed  }
8150193326Sed
8151234353Sdim  if (!VDecl->getType()->isDependentType()) {
8152234353Sdim    // A definition must end up with a complete type, which means it must be
8153234353Sdim    // complete with the restriction that an array type might be completed by
8154234353Sdim    // the initializer; note that later code assumes this restriction.
8155234353Sdim    QualType BaseDeclType = VDecl->getType();
8156234353Sdim    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8157234353Sdim      BaseDeclType = Array->getElementType();
8158234353Sdim    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8159234353Sdim                            diag::err_typecheck_decl_incomplete_type)) {
8160234353Sdim      RealDecl->setInvalidDecl();
8161234353Sdim      return;
8162234353Sdim    }
8163200583Srdivacky
8164234353Sdim    // The variable can not have an abstract class type.
8165234353Sdim    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8166234353Sdim                               diag::err_abstract_type_in_decl,
8167234353Sdim                               AbstractVariableType))
8168234353Sdim      VDecl->setInvalidDecl();
8169234353Sdim  }
8170234353Sdim
8171203955Srdivacky  const VarDecl *Def;
8172203955Srdivacky  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8173198092Srdivacky    Diag(VDecl->getLocation(), diag::err_redefinition)
8174193326Sed      << VDecl->getDeclName();
8175193326Sed    Diag(Def->getLocation(), diag::note_previous_definition);
8176193326Sed    VDecl->setInvalidDecl();
8177193326Sed    return;
8178193326Sed  }
8179212904Sdim
8180212904Sdim  const VarDecl* PrevInit = 0;
8181234353Sdim  if (getLangOpts().CPlusPlus) {
8182218893Sdim    // C++ [class.static.data]p4
8183218893Sdim    //   If a static data member is of const integral or const
8184218893Sdim    //   enumeration type, its declaration in the class definition can
8185218893Sdim    //   specify a constant-initializer which shall be an integral
8186218893Sdim    //   constant expression (5.19). In that case, the member can appear
8187218893Sdim    //   in integral constant expressions. The member shall still be
8188218893Sdim    //   defined in a namespace scope if it is used in the program and the
8189218893Sdim    //   namespace scope definition shall not contain an initializer.
8190218893Sdim    //
8191218893Sdim    // We already performed a redefinition check above, but for static
8192218893Sdim    // data members we also need to check whether there was an in-class
8193218893Sdim    // declaration with an initializer.
8194218893Sdim    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8195234353Sdim      Diag(VDecl->getLocation(), diag::err_redefinition)
8196234353Sdim        << VDecl->getDeclName();
8197218893Sdim      Diag(PrevInit->getLocation(), diag::note_previous_definition);
8198218893Sdim      return;
8199218893Sdim    }
8200193326Sed
8201218893Sdim    if (VDecl->hasLocalStorage())
8202218893Sdim      getCurFunction()->setHasBranchProtectedScope();
8203193326Sed
8204218893Sdim    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8205218893Sdim      VDecl->setInvalidDecl();
8206218893Sdim      return;
8207218893Sdim    }
8208218893Sdim  }
8209218893Sdim
8210226633Sdim  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8211226633Sdim  // a kernel function cannot be initialized."
8212226633Sdim  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8213226633Sdim    Diag(VDecl->getLocation(), diag::err_local_cant_init);
8214226633Sdim    VDecl->setInvalidDecl();
8215226633Sdim    return;
8216226633Sdim  }
8217226633Sdim
8218193326Sed  // Get the decls type and save a reference for later, since
8219193326Sed  // CheckInitializerTypes may change it.
8220193326Sed  QualType DclT = VDecl->getType(), SavT = DclT;
8221234353Sdim
8222249423Sdim  // Expressions default to 'id' when we're in a debugger
8223249423Sdim  // and we are assigning it to a variable of Objective-C pointer type.
8224249423Sdim  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8225249423Sdim      Init->getType() == Context.UnknownAnyTy) {
8226249423Sdim    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8227249423Sdim    if (Result.isInvalid()) {
8228249423Sdim      VDecl->setInvalidDecl();
8229249423Sdim      return;
8230234353Sdim    }
8231249423Sdim    Init = Result.take();
8232249423Sdim  }
8233200583Srdivacky
8234234353Sdim  // Perform the initialization.
8235234353Sdim  if (!VDecl->isInvalidDecl()) {
8236234353Sdim    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8237234353Sdim    InitializationKind Kind
8238234353Sdim      = DirectInit ?
8239234353Sdim          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8240234353Sdim                                                           Init->getLocStart(),
8241234353Sdim                                                           Init->getLocEnd())
8242234353Sdim                        : InitializationKind::CreateDirectList(
8243234353Sdim                                                          VDecl->getLocation())
8244234353Sdim                   : InitializationKind::CreateCopy(VDecl->getLocation(),
8245234353Sdim                                                    Init->getLocStart());
8246200583Srdivacky
8247251662Sdim    MultiExprArg Args = Init;
8248251662Sdim    if (CXXDirectInit)
8249251662Sdim      Args = MultiExprArg(CXXDirectInit->getExprs(),
8250251662Sdim                          CXXDirectInit->getNumExprs());
8251251662Sdim
8252251662Sdim    InitializationSequence InitSeq(*this, Entity, Kind, Args);
8253251662Sdim    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8254234353Sdim    if (Result.isInvalid()) {
8255234353Sdim      VDecl->setInvalidDecl();
8256234353Sdim      return;
8257234353Sdim    }
8258234353Sdim
8259234353Sdim    Init = Result.takeAs<Expr>();
8260234353Sdim  }
8261234353Sdim
8262243830Sdim  // Check for self-references within variable initializers.
8263243830Sdim  // Variables declared within a function/method body (except for references)
8264243830Sdim  // are handled by a dataflow analysis.
8265243830Sdim  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8266243830Sdim      VDecl->getType()->isReferenceType()) {
8267243830Sdim    CheckSelfReference(*this, RealDecl, Init, DirectInit);
8268243830Sdim  }
8269243830Sdim
8270234353Sdim  // If the type changed, it means we had an incomplete type that was
8271234353Sdim  // completed by the initializer. For example:
8272234353Sdim  //   int ary[] = { 1, 3, 5 };
8273234353Sdim  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8274234353Sdim  if (!VDecl->isInvalidDecl() && (DclT != SavT))
8275234353Sdim    VDecl->setType(DclT);
8276234353Sdim
8277243830Sdim  if (!VDecl->isInvalidDecl()) {
8278234353Sdim    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8279234353Sdim
8280243830Sdim    if (VDecl->hasAttr<BlocksAttr>())
8281243830Sdim      checkRetainCycles(VDecl, Init);
8282243830Sdim
8283243830Sdim    // It is safe to assign a weak reference into a strong variable.
8284243830Sdim    // Although this code can still have problems:
8285243830Sdim    //   id x = self.weakProp;
8286243830Sdim    //   id y = self.weakProp;
8287243830Sdim    // we do not warn to warn spuriously when 'x' and 'y' are on separate
8288243830Sdim    // paths through the function. This should be revisited if
8289243830Sdim    // -Wrepeated-use-of-weak is made flow-sensitive.
8290243830Sdim    if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8291243830Sdim      DiagnosticsEngine::Level Level =
8292243830Sdim        Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8293243830Sdim                                 Init->getLocStart());
8294243830Sdim      if (Level != DiagnosticsEngine::Ignored)
8295243830Sdim        getCurFunction()->markSafeWeakUse(Init);
8296243830Sdim    }
8297243830Sdim  }
8298243830Sdim
8299249423Sdim  // The initialization is usually a full-expression.
8300249423Sdim  //
8301249423Sdim  // FIXME: If this is a braced initialization of an aggregate, it is not
8302249423Sdim  // an expression, and each individual field initializer is a separate
8303249423Sdim  // full-expression. For instance, in:
8304249423Sdim  //
8305249423Sdim  //   struct Temp { ~Temp(); };
8306249423Sdim  //   struct S { S(Temp); };
8307249423Sdim  //   struct T { S a, b; } t = { Temp(), Temp() }
8308249423Sdim  //
8309249423Sdim  // we should destroy the first Temp before constructing the second.
8310249423Sdim  ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8311249423Sdim                                          false,
8312249423Sdim                                          VDecl->isConstexpr());
8313249423Sdim  if (Result.isInvalid()) {
8314249423Sdim    VDecl->setInvalidDecl();
8315249423Sdim    return;
8316249423Sdim  }
8317249423Sdim  Init = Result.take();
8318249423Sdim
8319234353Sdim  // Attach the initializer to the decl.
8320234353Sdim  VDecl->setInit(Init);
8321234353Sdim
8322234353Sdim  if (VDecl->isLocalVarDecl()) {
8323234353Sdim    // C99 6.7.8p4: All the expressions in an initializer for an object that has
8324234353Sdim    // static storage duration shall be constant expressions or string literals.
8325234353Sdim    // C++ does not have this restriction.
8326263508Sdim    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8327263508Sdim      if (VDecl->getStorageClass() == SC_Static)
8328263508Sdim        CheckForConstantInitializer(Init, DclT);
8329263508Sdim      // C89 is stricter than C99 for non-static aggregate types.
8330263508Sdim      // C89 6.5.7p3: All the expressions [...] in an initializer list
8331263508Sdim      // for an object that has aggregate or union type shall be
8332263508Sdim      // constant expressions.
8333263508Sdim      else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8334263508Sdim               isa<InitListExpr>(Init) &&
8335263508Sdim               !Init->isConstantInitializer(Context, false))
8336263508Sdim        Diag(Init->getExprLoc(),
8337263508Sdim             diag::ext_aggregate_init_not_constant)
8338263508Sdim          << Init->getSourceRange();
8339263508Sdim    }
8340198092Srdivacky  } else if (VDecl->isStaticDataMember() &&
8341193326Sed             VDecl->getLexicalDeclContext()->isRecord()) {
8342193326Sed    // This is an in-class initialization for a static data member, e.g.,
8343193326Sed    //
8344193326Sed    // struct S {
8345193326Sed    //   static const int value = 17;
8346193326Sed    // };
8347193326Sed
8348193326Sed    // C++ [class.mem]p4:
8349193326Sed    //   A member-declarator can contain a constant-initializer only
8350193326Sed    //   if it declares a static member (9.4) of const integral or
8351193326Sed    //   const enumeration type, see 9.4.2.
8352226633Sdim    //
8353234353Sdim    // C++11 [class.static.data]p3:
8354226633Sdim    //   If a non-volatile const static data member is of integral or
8355226633Sdim    //   enumeration type, its declaration in the class definition can
8356226633Sdim    //   specify a brace-or-equal-initializer in which every initalizer-clause
8357226633Sdim    //   that is an assignment-expression is a constant expression. A static
8358226633Sdim    //   data member of literal type can be declared in the class definition
8359226633Sdim    //   with the constexpr specifier; if so, its declaration shall specify a
8360226633Sdim    //   brace-or-equal-initializer in which every initializer-clause that is
8361226633Sdim    //   an assignment-expression is a constant expression.
8362218893Sdim
8363218893Sdim    // Do nothing on dependent types.
8364234353Sdim    if (DclT->isDependentType()) {
8365218893Sdim
8366226633Sdim    // Allow any 'static constexpr' members, whether or not they are of literal
8367234353Sdim    // type. We separately check that every constexpr variable is of literal
8368234353Sdim    // type.
8369226633Sdim    } else if (VDecl->isConstexpr()) {
8370226633Sdim
8371218893Sdim    // Require constness.
8372234353Sdim    } else if (!DclT.isConstQualified()) {
8373218893Sdim      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8374218893Sdim        << Init->getSourceRange();
8375193326Sed      VDecl->setInvalidDecl();
8376218893Sdim
8377218893Sdim    // We allow integer constant expressions in all cases.
8378234353Sdim    } else if (DclT->isIntegralOrEnumerationType()) {
8379224145Sdim      // Check whether the expression is a constant expression.
8380224145Sdim      SourceLocation Loc;
8381249423Sdim      if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8382234353Sdim        // In C++11, a non-constexpr const static data member with an
8383226633Sdim        // in-class initializer cannot be volatile.
8384226633Sdim        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8385226633Sdim      else if (Init->isValueDependent())
8386224145Sdim        ; // Nothing to check.
8387224145Sdim      else if (Init->isIntegerConstantExpr(Context, &Loc))
8388224145Sdim        ; // Ok, it's an ICE!
8389224145Sdim      else if (Init->isEvaluatable(Context)) {
8390224145Sdim        // If we can constant fold the initializer through heroics, accept it,
8391224145Sdim        // but report this as a use of an extension for -pedantic.
8392224145Sdim        Diag(Loc, diag::ext_in_class_initializer_non_constant)
8393224145Sdim          << Init->getSourceRange();
8394224145Sdim      } else {
8395224145Sdim        // Otherwise, this is some crazy unknown case.  Report the issue at the
8396224145Sdim        // location provided by the isIntegerConstantExpr failed check.
8397224145Sdim        Diag(Loc, diag::err_in_class_initializer_non_constant)
8398224145Sdim          << Init->getSourceRange();
8399224145Sdim        VDecl->setInvalidDecl();
8400193326Sed      }
8401218893Sdim
8402234353Sdim    // We allow foldable floating-point constants as an extension.
8403234353Sdim    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8404249423Sdim      // In C++98, this is a GNU extension. In C++11, it is not, but we support
8405249423Sdim      // it anyway and provide a fixit to add the 'constexpr'.
8406249423Sdim      if (getLangOpts().CPlusPlus11) {
8407226633Sdim        Diag(VDecl->getLocation(),
8408249423Sdim             diag::ext_in_class_initializer_float_type_cxx11)
8409249423Sdim            << DclT << Init->getSourceRange();
8410249423Sdim        Diag(VDecl->getLocStart(),
8411249423Sdim             diag::note_in_class_initializer_float_type_cxx11)
8412249423Sdim            << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8413249423Sdim      } else {
8414249423Sdim        Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8415249423Sdim          << DclT << Init->getSourceRange();
8416218893Sdim
8417249423Sdim        if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8418249423Sdim          Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8419249423Sdim            << Init->getSourceRange();
8420249423Sdim          VDecl->setInvalidDecl();
8421249423Sdim        }
8422218893Sdim      }
8423226633Sdim
8424234353Sdim    // Suggest adding 'constexpr' in C++11 for literal types.
8425251662Sdim    } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8426226633Sdim      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8427234353Sdim        << DclT << Init->getSourceRange()
8428226633Sdim        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8429226633Sdim      VDecl->setConstexpr(true);
8430226633Sdim
8431226633Sdim    } else {
8432226633Sdim      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8433234353Sdim        << DclT << Init->getSourceRange();
8434226633Sdim      VDecl->setInvalidDecl();
8435193326Sed    }
8436193326Sed  } else if (VDecl->isFileVarDecl()) {
8437249423Sdim    if (VDecl->getStorageClass() == SC_Extern &&
8438234353Sdim        (!getLangOpts().CPlusPlus ||
8439249423Sdim         !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8440263508Sdim           VDecl->isExternC())) &&
8441263508Sdim        !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8442193326Sed      Diag(VDecl->getLocation(), diag::warn_extern_init);
8443198092Srdivacky
8444234353Sdim    // C99 6.7.8p4. All file scoped initializers need to be constant.
8445234353Sdim    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8446193326Sed      CheckForConstantInitializer(Init, DclT);
8447251662Sdim    else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8448251662Sdim             !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8449251662Sdim             !Init->isValueDependent() && !VDecl->isConstexpr() &&
8450251662Sdim             !Init->isConstantInitializer(
8451251662Sdim                 Context, VDecl->getType()->isReferenceType())) {
8452251662Sdim      // GNU C++98 edits for __thread, [basic.start.init]p4:
8453251662Sdim      //   An object of thread storage duration shall not require dynamic
8454251662Sdim      //   initialization.
8455251662Sdim      // FIXME: Need strict checking here.
8456251662Sdim      Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8457251662Sdim      if (getLangOpts().CPlusPlus11)
8458251662Sdim        Diag(VDecl->getLocation(), diag::note_use_thread_local);
8459251662Sdim    }
8460193326Sed  }
8461226633Sdim
8462234353Sdim  // We will represent direct-initialization similarly to copy-initialization:
8463234353Sdim  //    int x(1);  -as-> int x = 1;
8464234353Sdim  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8465234353Sdim  //
8466234353Sdim  // Clients that want to distinguish between the two forms, can check for
8467234353Sdim  // direct initializer using VarDecl::getInitStyle().
8468234353Sdim  // A major benefit is that clients that don't particularly care about which
8469234353Sdim  // exactly form was it (like the CodeGen) can handle both cases without
8470234353Sdim  // special case code.
8471234353Sdim
8472234353Sdim  // C++ 8.5p11:
8473234353Sdim  // The form of initialization (using parentheses or '=') is generally
8474234353Sdim  // insignificant, but does matter when the entity being initialized has a
8475234353Sdim  // class type.
8476234353Sdim  if (CXXDirectInit) {
8477234353Sdim    assert(DirectInit && "Call-style initializer must be direct init.");
8478234353Sdim    VDecl->setInitStyle(VarDecl::CallInit);
8479234353Sdim  } else if (DirectInit) {
8480234353Sdim    // This must be list-initialization. No other way is direct-initialization.
8481234353Sdim    VDecl->setInitStyle(VarDecl::ListInit);
8482226633Sdim  }
8483193326Sed
8484218893Sdim  CheckCompleteVariableDeclaration(VDecl);
8485193326Sed}
8486193326Sed
8487206084Srdivacky/// ActOnInitializerError - Given that there was an error parsing an
8488206084Srdivacky/// initializer for the given declaration, try to return to some form
8489206084Srdivacky/// of sanity.
8490212904Sdimvoid Sema::ActOnInitializerError(Decl *D) {
8491206084Srdivacky  // Our main concern here is re-establishing invariants like "a
8492206084Srdivacky  // variable's type is either dependent or complete".
8493206084Srdivacky  if (!D || D->isInvalidDecl()) return;
8494206084Srdivacky
8495206084Srdivacky  VarDecl *VD = dyn_cast<VarDecl>(D);
8496206084Srdivacky  if (!VD) return;
8497206084Srdivacky
8498218893Sdim  // Auto types are meaningless if we can't make sense of the initializer.
8499219077Sdim  if (ParsingInitForAutoVars.count(D)) {
8500219077Sdim    D->setInvalidDecl();
8501218893Sdim    return;
8502218893Sdim  }
8503218893Sdim
8504206084Srdivacky  QualType Ty = VD->getType();
8505206084Srdivacky  if (Ty->isDependentType()) return;
8506206084Srdivacky
8507206084Srdivacky  // Require a complete type.
8508206084Srdivacky  if (RequireCompleteType(VD->getLocation(),
8509206084Srdivacky                          Context.getBaseElementType(Ty),
8510206084Srdivacky                          diag::err_typecheck_decl_incomplete_type)) {
8511206084Srdivacky    VD->setInvalidDecl();
8512206084Srdivacky    return;
8513206084Srdivacky  }
8514206084Srdivacky
8515206084Srdivacky  // Require an abstract type.
8516206084Srdivacky  if (RequireNonAbstractType(VD->getLocation(), Ty,
8517206084Srdivacky                             diag::err_abstract_type_in_decl,
8518206084Srdivacky                             AbstractVariableType)) {
8519206084Srdivacky    VD->setInvalidDecl();
8520206084Srdivacky    return;
8521206084Srdivacky  }
8522206084Srdivacky
8523206084Srdivacky  // Don't bother complaining about constructors or destructors,
8524206084Srdivacky  // though.
8525206084Srdivacky}
8526206084Srdivacky
8527212904Sdimvoid Sema::ActOnUninitializedDecl(Decl *RealDecl,
8528218893Sdim                                  bool TypeMayContainAuto) {
8529193326Sed  // If there is no declaration, there was an error parsing it. Just ignore it.
8530193326Sed  if (RealDecl == 0)
8531193326Sed    return;
8532193326Sed
8533193326Sed  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8534193326Sed    QualType Type = Var->getType();
8535193326Sed
8536234353Sdim    // C++11 [dcl.spec.auto]p3
8537218893Sdim    if (TypeMayContainAuto && Type->getContainedAutoType()) {
8538203955Srdivacky      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8539203955Srdivacky        << Var->getDeclName() << Type;
8540203955Srdivacky      Var->setInvalidDecl();
8541203955Srdivacky      return;
8542203955Srdivacky    }
8543193326Sed
8544234353Sdim    // C++11 [class.static.data]p3: A static data member can be declared with
8545226633Sdim    // the constexpr specifier; if so, its declaration shall specify
8546226633Sdim    // a brace-or-equal-initializer.
8547234353Sdim    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8548234353Sdim    // the definition of a variable [...] or the declaration of a static data
8549234353Sdim    // member.
8550234353Sdim    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8551234353Sdim      if (Var->isStaticDataMember())
8552234353Sdim        Diag(Var->getLocation(),
8553234353Sdim             diag::err_constexpr_static_mem_var_requires_init)
8554234353Sdim          << Var->getDeclName();
8555234353Sdim      else
8556234353Sdim        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8557226633Sdim      Var->setInvalidDecl();
8558226633Sdim      return;
8559226633Sdim    }
8560226633Sdim
8561203955Srdivacky    switch (Var->isThisDeclarationADefinition()) {
8562203955Srdivacky    case VarDecl::Definition:
8563203955Srdivacky      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8564203955Srdivacky        break;
8565198092Srdivacky
8566203955Srdivacky      // We have an out-of-line definition of a static data member
8567203955Srdivacky      // that has an in-class initializer, so we type-check this like
8568203955Srdivacky      // a declaration.
8569203955Srdivacky      //
8570203955Srdivacky      // Fall through
8571203955Srdivacky
8572203955Srdivacky    case VarDecl::DeclarationOnly:
8573203955Srdivacky      // It's only a declaration.
8574203955Srdivacky
8575203955Srdivacky      // Block scope. C99 6.7p7: If an identifier for an object is
8576203955Srdivacky      // declared with no linkage (C99 6.2.2p6), the type for the
8577203955Srdivacky      // object shall be complete.
8578218893Sdim      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8579263508Sdim          !Var->hasLinkage() && !Var->isInvalidDecl() &&
8580203955Srdivacky          RequireCompleteType(Var->getLocation(), Type,
8581203955Srdivacky                              diag::err_typecheck_decl_incomplete_type))
8582203955Srdivacky        Var->setInvalidDecl();
8583203955Srdivacky
8584203955Srdivacky      // Make sure that the type is not abstract.
8585203955Srdivacky      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8586203955Srdivacky          RequireNonAbstractType(Var->getLocation(), Type,
8587203955Srdivacky                                 diag::err_abstract_type_in_decl,
8588203955Srdivacky                                 AbstractVariableType))
8589203955Srdivacky        Var->setInvalidDecl();
8590239462Sdim      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8591243830Sdim          Var->getStorageClass() == SC_PrivateExtern) {
8592239462Sdim        Diag(Var->getLocation(), diag::warn_private_extern);
8593243830Sdim        Diag(Var->getLocation(), diag::note_private_extern);
8594243830Sdim      }
8595239462Sdim
8596203955Srdivacky      return;
8597203955Srdivacky
8598203955Srdivacky    case VarDecl::TentativeDefinition:
8599203955Srdivacky      // File scope. C99 6.9.2p2: A declaration of an identifier for an
8600203955Srdivacky      // object that has file scope without an initializer, and without a
8601203955Srdivacky      // storage-class specifier or with the storage-class specifier "static",
8602203955Srdivacky      // constitutes a tentative definition. Note: A tentative definition with
8603203955Srdivacky      // external linkage is valid (C99 6.2.2p5).
8604203955Srdivacky      if (!Var->isInvalidDecl()) {
8605203955Srdivacky        if (const IncompleteArrayType *ArrayT
8606203955Srdivacky                                    = Context.getAsIncompleteArrayType(Type)) {
8607203955Srdivacky          if (RequireCompleteType(Var->getLocation(),
8608203955Srdivacky                                  ArrayT->getElementType(),
8609203955Srdivacky                                  diag::err_illegal_decl_array_incomplete_type))
8610203955Srdivacky            Var->setInvalidDecl();
8611212904Sdim        } else if (Var->getStorageClass() == SC_Static) {
8612203955Srdivacky          // C99 6.9.2p3: If the declaration of an identifier for an object is
8613203955Srdivacky          // a tentative definition and has internal linkage (C99 6.2.2p3), the
8614203955Srdivacky          // declared type shall not be an incomplete type.
8615203955Srdivacky          // NOTE: code such as the following
8616203955Srdivacky          //     static struct s;
8617203955Srdivacky          //     struct s { int a; };
8618203955Srdivacky          // is accepted by gcc. Hence here we issue a warning instead of
8619203955Srdivacky          // an error and we do not invalidate the static declaration.
8620203955Srdivacky          // NOTE: to avoid multiple warnings, only check the first declaration.
8621263508Sdim          if (Var->isFirstDecl())
8622203955Srdivacky            RequireCompleteType(Var->getLocation(), Type,
8623203955Srdivacky                                diag::ext_typecheck_decl_incomplete_type);
8624203955Srdivacky        }
8625203955Srdivacky      }
8626203955Srdivacky
8627203955Srdivacky      // Record the tentative definition; we're done.
8628203955Srdivacky      if (!Var->isInvalidDecl())
8629203955Srdivacky        TentativeDefinitions.push_back(Var);
8630203955Srdivacky      return;
8631198092Srdivacky    }
8632198092Srdivacky
8633203955Srdivacky    // Provide a specific diagnostic for uninitialized variable
8634203955Srdivacky    // definitions with incomplete array type.
8635203955Srdivacky    if (Type->isIncompleteArrayType()) {
8636203955Srdivacky      Diag(Var->getLocation(),
8637203955Srdivacky           diag::err_typecheck_incomplete_array_needs_initializer);
8638193326Sed      Var->setInvalidDecl();
8639193326Sed      return;
8640193326Sed    }
8641193326Sed
8642212904Sdim    // Provide a specific diagnostic for uninitialized variable
8643212904Sdim    // definitions with reference type.
8644212904Sdim    if (Type->isReferenceType()) {
8645212904Sdim      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8646212904Sdim        << Var->getDeclName()
8647212904Sdim        << SourceRange(Var->getLocation(), Var->getLocation());
8648212904Sdim      Var->setInvalidDecl();
8649212904Sdim      return;
8650212904Sdim    }
8651203955Srdivacky
8652203955Srdivacky    // Do not attempt to type-check the default initializer for a
8653203955Srdivacky    // variable with dependent type.
8654203955Srdivacky    if (Type->isDependentType())
8655203955Srdivacky      return;
8656203955Srdivacky
8657203955Srdivacky    if (Var->isInvalidDecl())
8658203955Srdivacky      return;
8659203955Srdivacky
8660203955Srdivacky    if (RequireCompleteType(Var->getLocation(),
8661203955Srdivacky                            Context.getBaseElementType(Type),
8662203955Srdivacky                            diag::err_typecheck_decl_incomplete_type)) {
8663198092Srdivacky      Var->setInvalidDecl();
8664198092Srdivacky      return;
8665198092Srdivacky    }
8666198092Srdivacky
8667203955Srdivacky    // The variable can not have an abstract class type.
8668203955Srdivacky    if (RequireNonAbstractType(Var->getLocation(), Type,
8669203955Srdivacky                               diag::err_abstract_type_in_decl,
8670203955Srdivacky                               AbstractVariableType)) {
8671199482Srdivacky      Var->setInvalidDecl();
8672199482Srdivacky      return;
8673199482Srdivacky    }
8674199482Srdivacky
8675223017Sdim    // Check for jumps past the implicit initializer.  C++0x
8676223017Sdim    // clarifies that this applies to a "variable with automatic
8677223017Sdim    // storage duration", not a "local variable".
8678234353Sdim    // C++11 [stmt.dcl]p3
8679223017Sdim    //   A program that jumps from a point where a variable with automatic
8680223017Sdim    //   storage duration is not in scope to a point where it is in scope is
8681223017Sdim    //   ill-formed unless the variable has scalar type, class type with a
8682223017Sdim    //   trivial default constructor and a trivial destructor, a cv-qualified
8683223017Sdim    //   version of one of these types, or an array of one of the preceding
8684223017Sdim    //   types and is declared without an initializer.
8685234353Sdim    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8686223017Sdim      if (const RecordType *Record
8687223017Sdim            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8688223017Sdim        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8689234353Sdim        // Mark the function for further checking even if the looser rules of
8690234353Sdim        // C++11 do not require such checks, so that we can diagnose
8691234353Sdim        // incompatibilities with C++98.
8692234353Sdim        if (!CXXRecord->isPOD())
8693223017Sdim          getCurFunction()->setHasBranchProtectedScope();
8694223017Sdim      }
8695223017Sdim    }
8696198092Srdivacky
8697223017Sdim    // C++03 [dcl.init]p9:
8698223017Sdim    //   If no initializer is specified for an object, and the
8699223017Sdim    //   object is of (possibly cv-qualified) non-POD class type (or
8700223017Sdim    //   array thereof), the object shall be default-initialized; if
8701223017Sdim    //   the object is of const-qualified type, the underlying class
8702223017Sdim    //   type shall have a user-declared default
8703223017Sdim    //   constructor. Otherwise, if no initializer is specified for
8704223017Sdim    //   a non- static object, the object and its subobjects, if
8705223017Sdim    //   any, have an indeterminate initial value); if the object
8706223017Sdim    //   or any of its subobjects are of const-qualified type, the
8707223017Sdim    //   program is ill-formed.
8708223017Sdim    // C++0x [dcl.init]p11:
8709223017Sdim    //   If no initializer is specified for an object, the object is
8710223017Sdim    //   default-initialized; [...].
8711223017Sdim    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8712223017Sdim    InitializationKind Kind
8713223017Sdim      = InitializationKind::CreateDefault(Var->getLocation());
8714251662Sdim
8715251662Sdim    InitializationSequence InitSeq(*this, Entity, Kind, None);
8716251662Sdim    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8717223017Sdim    if (Init.isInvalid())
8718223017Sdim      Var->setInvalidDecl();
8719234353Sdim    else if (Init.get()) {
8720223017Sdim      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8721234353Sdim      // This is important for template substitution.
8722234353Sdim      Var->setInitStyle(VarDecl::CallInit);
8723234353Sdim    }
8724212904Sdim
8725218893Sdim    CheckCompleteVariableDeclaration(Var);
8726218893Sdim  }
8727218893Sdim}
8728218893Sdim
8729221345Sdimvoid Sema::ActOnCXXForRangeDecl(Decl *D) {
8730221345Sdim  VarDecl *VD = dyn_cast<VarDecl>(D);
8731221345Sdim  if (!VD) {
8732221345Sdim    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8733221345Sdim    D->setInvalidDecl();
8734221345Sdim    return;
8735221345Sdim  }
8736221345Sdim
8737221345Sdim  VD->setCXXForRangeDecl(true);
8738221345Sdim
8739221345Sdim  // for-range-declaration cannot be given a storage class specifier.
8740221345Sdim  int Error = -1;
8741249423Sdim  switch (VD->getStorageClass()) {
8742221345Sdim  case SC_None:
8743221345Sdim    break;
8744221345Sdim  case SC_Extern:
8745221345Sdim    Error = 0;
8746221345Sdim    break;
8747221345Sdim  case SC_Static:
8748221345Sdim    Error = 1;
8749221345Sdim    break;
8750221345Sdim  case SC_PrivateExtern:
8751221345Sdim    Error = 2;
8752221345Sdim    break;
8753221345Sdim  case SC_Auto:
8754221345Sdim    Error = 3;
8755221345Sdim    break;
8756221345Sdim  case SC_Register:
8757221345Sdim    Error = 4;
8758221345Sdim    break;
8759226633Sdim  case SC_OpenCLWorkGroupLocal:
8760226633Sdim    llvm_unreachable("Unexpected storage class");
8761221345Sdim  }
8762226633Sdim  if (VD->isConstexpr())
8763226633Sdim    Error = 5;
8764221345Sdim  if (Error != -1) {
8765221345Sdim    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8766221345Sdim      << VD->getDeclName() << Error;
8767221345Sdim    D->setInvalidDecl();
8768221345Sdim  }
8769221345Sdim}
8770221345Sdim
8771218893Sdimvoid Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8772218893Sdim  if (var->isInvalidDecl()) return;
8773218893Sdim
8774224145Sdim  // In ARC, don't allow jumps past the implicit initialization of a
8775224145Sdim  // local retaining variable.
8776234353Sdim  if (getLangOpts().ObjCAutoRefCount &&
8777224145Sdim      var->hasLocalStorage()) {
8778224145Sdim    switch (var->getType().getObjCLifetime()) {
8779224145Sdim    case Qualifiers::OCL_None:
8780224145Sdim    case Qualifiers::OCL_ExplicitNone:
8781224145Sdim    case Qualifiers::OCL_Autoreleasing:
8782224145Sdim      break;
8783224145Sdim
8784224145Sdim    case Qualifiers::OCL_Weak:
8785224145Sdim    case Qualifiers::OCL_Strong:
8786224145Sdim      getCurFunction()->setHasBranchProtectedScope();
8787224145Sdim      break;
8788224145Sdim    }
8789224145Sdim  }
8790224145Sdim
8791242080Sed  if (var->isThisDeclarationADefinition() &&
8792263508Sdim      var->isExternallyVisible() && var->hasLinkage() &&
8793249423Sdim      getDiagnostics().getDiagnosticLevel(
8794249423Sdim                       diag::warn_missing_variable_declarations,
8795249423Sdim                       var->getLocation())) {
8796242080Sed    // Find a previous declaration that's not a definition.
8797242080Sed    VarDecl *prev = var->getPreviousDecl();
8798242080Sed    while (prev && prev->isThisDeclarationADefinition())
8799242080Sed      prev = prev->getPreviousDecl();
8800242080Sed
8801242080Sed    if (!prev)
8802242080Sed      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8803242080Sed  }
8804242080Sed
8805251662Sdim  if (var->getTLSKind() == VarDecl::TLS_Static &&
8806251662Sdim      var->getType().isDestructedType()) {
8807251662Sdim    // GNU C++98 edits for __thread, [basic.start.term]p3:
8808251662Sdim    //   The type of an object with thread storage duration shall not
8809251662Sdim    //   have a non-trivial destructor.
8810251662Sdim    Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8811251662Sdim    if (getLangOpts().CPlusPlus11)
8812251662Sdim      Diag(var->getLocation(), diag::note_use_thread_local);
8813251662Sdim  }
8814251662Sdim
8815218893Sdim  // All the following checks are C++ only.
8816234353Sdim  if (!getLangOpts().CPlusPlus) return;
8817218893Sdim
8818243830Sdim  QualType type = var->getType();
8819243830Sdim  if (type->isDependentType()) return;
8820218893Sdim
8821218893Sdim  // __block variables might require us to capture a copy-initializer.
8822218893Sdim  if (var->hasAttr<BlocksAttr>()) {
8823218893Sdim    // It's currently invalid to ever have a __block variable with an
8824218893Sdim    // array type; should we diagnose that here?
8825218893Sdim
8826218893Sdim    // Regardless, we don't want to ignore array nesting when
8827218893Sdim    // constructing this copy.
8828218893Sdim    if (type->isStructureOrClassType()) {
8829249423Sdim      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8830218893Sdim      SourceLocation poi = var->getLocation();
8831234353Sdim      Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8832249423Sdim      ExprResult result
8833249423Sdim        = PerformMoveOrCopyInitialization(
8834249423Sdim            InitializedEntity::InitializeBlock(poi, type, false),
8835249423Sdim            var, var->getType(), varRef, /*AllowNRVO=*/true);
8836218893Sdim      if (!result.isInvalid()) {
8837218893Sdim        result = MaybeCreateExprWithCleanups(result);
8838218893Sdim        Expr *init = result.takeAs<Expr>();
8839218893Sdim        Context.setBlockVarCopyInits(var, init);
8840212904Sdim      }
8841204962Srdivacky    }
8842218893Sdim  }
8843198092Srdivacky
8844234353Sdim  Expr *Init = var->getInit();
8845234353Sdim  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8846243830Sdim  QualType baseType = Context.getBaseElementType(type);
8847218893Sdim
8848243830Sdim  if (!var->getDeclContext()->isDependentContext() &&
8849243830Sdim      Init && !Init->isValueDependent()) {
8850234353Sdim    if (IsGlobal && !var->isConstexpr() &&
8851234353Sdim        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8852234353Sdim                                            var->getLocation())
8853263508Sdim          != DiagnosticsEngine::Ignored) {
8854263508Sdim      // Warn about globals which don't have a constant initializer.  Don't
8855263508Sdim      // warn about globals with a non-trivial destructor because we already
8856263508Sdim      // warned about them.
8857263508Sdim      CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8858263508Sdim      if (!(RD && !RD->hasTrivialDestructor()) &&
8859263508Sdim          !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8860263508Sdim        Diag(var->getLocation(), diag::warn_global_constructor)
8861263508Sdim          << Init->getSourceRange();
8862263508Sdim    }
8863234353Sdim
8864234353Sdim    if (var->isConstexpr()) {
8865249423Sdim      SmallVector<PartialDiagnosticAt, 8> Notes;
8866234353Sdim      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8867234353Sdim        SourceLocation DiagLoc = var->getLocation();
8868234353Sdim        // If the note doesn't add any useful information other than a source
8869234353Sdim        // location, fold it into the primary diagnostic.
8870234353Sdim        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8871234353Sdim              diag::note_invalid_subexpr_in_const_expr) {
8872234353Sdim          DiagLoc = Notes[0].first;
8873234353Sdim          Notes.clear();
8874234353Sdim        }
8875234353Sdim        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8876234353Sdim          << var << Init->getSourceRange();
8877234353Sdim        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8878234353Sdim          Diag(Notes[I].first, Notes[I].second);
8879234353Sdim      }
8880234353Sdim    } else if (var->isUsableInConstantExpressions(Context)) {
8881234353Sdim      // Check whether the initializer of a const variable of integral or
8882234353Sdim      // enumeration type is an ICE now, since we can't tell whether it was
8883234353Sdim      // initialized by a constant expression if we check later.
8884234353Sdim      var->checkInitIsICE();
8885234353Sdim    }
8886234353Sdim  }
8887234353Sdim
8888218893Sdim  // Require the destructor.
8889218893Sdim  if (const RecordType *recordType = baseType->getAs<RecordType>())
8890218893Sdim    FinalizeVarWithDestructor(var, recordType);
8891193326Sed}
8892193326Sed
8893219077Sdim/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8894219077Sdim/// any semantic actions necessary after any initializer has been attached.
8895219077Sdimvoid
8896219077SdimSema::FinalizeDeclaration(Decl *ThisDecl) {
8897219077Sdim  // Note that we are no longer parsing the initializer for this declaration.
8898219077Sdim  ParsingInitForAutoVars.erase(ThisDecl);
8899239462Sdim
8900249423Sdim  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8901249423Sdim  if (!VD)
8902249423Sdim    return;
8903249423Sdim
8904263508Sdim  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8905263508Sdim    if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8906263508Sdim      Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8907263508Sdim      VD->dropAttr<UsedAttr>();
8908263508Sdim    }
8909263508Sdim  }
8910263508Sdim
8911263508Sdim  if (!VD->isInvalidDecl() &&
8912263508Sdim      VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8913263508Sdim    if (const VarDecl *Def = VD->getDefinition()) {
8914263508Sdim      if (Def->hasAttr<AliasAttr>()) {
8915263508Sdim        Diag(VD->getLocation(), diag::err_tentative_after_alias)
8916263508Sdim            << VD->getDeclName();
8917263508Sdim        Diag(Def->getLocation(), diag::note_previous_definition);
8918263508Sdim        VD->setInvalidDecl();
8919263508Sdim      }
8920263508Sdim    }
8921263508Sdim  }
8922263508Sdim
8923249423Sdim  const DeclContext *DC = VD->getDeclContext();
8924249423Sdim  // If there's a #pragma GCC visibility in scope, and this isn't a class
8925249423Sdim  // member, set the visibility of this variable.
8926263508Sdim  if (!DC->isRecord() && VD->isExternallyVisible())
8927249423Sdim    AddPushedVisibilityAttribute(VD);
8928249423Sdim
8929249423Sdim  if (VD->isFileVarDecl())
8930249423Sdim    MarkUnusedFileScopedDecl(VD);
8931249423Sdim
8932239462Sdim  // Now we have parsed the initializer and can update the table of magic
8933239462Sdim  // tag values.
8934249423Sdim  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8935249423Sdim      !VD->getType()->isIntegralOrEnumerationType())
8936249423Sdim    return;
8937249423Sdim
8938249423Sdim  for (specific_attr_iterator<TypeTagForDatatypeAttr>
8939249423Sdim         I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8940249423Sdim         E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8941249423Sdim       I != E; ++I) {
8942249423Sdim    const Expr *MagicValueExpr = VD->getInit();
8943249423Sdim    if (!MagicValueExpr) {
8944249423Sdim      continue;
8945239462Sdim    }
8946249423Sdim    llvm::APSInt MagicValueInt;
8947249423Sdim    if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8948249423Sdim      Diag(I->getRange().getBegin(),
8949249423Sdim           diag::err_type_tag_for_datatype_not_ice)
8950249423Sdim        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8951249423Sdim      continue;
8952249423Sdim    }
8953249423Sdim    if (MagicValueInt.getActiveBits() > 64) {
8954249423Sdim      Diag(I->getRange().getBegin(),
8955249423Sdim           diag::err_type_tag_for_datatype_too_large)
8956249423Sdim        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8957249423Sdim      continue;
8958249423Sdim    }
8959249423Sdim    uint64_t MagicValue = MagicValueInt.getZExtValue();
8960249423Sdim    RegisterTypeTagForDatatype(I->getArgumentKind(),
8961249423Sdim                               MagicValue,
8962249423Sdim                               I->getMatchingCType(),
8963249423Sdim                               I->getLayoutCompatible(),
8964249423Sdim                               I->getMustBeNull());
8965239462Sdim  }
8966219077Sdim}
8967219077Sdim
8968263508SdimSema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8969263508Sdim                                                   ArrayRef<Decl *> Group) {
8970226633Sdim  SmallVector<Decl*, 8> Decls;
8971193326Sed
8972193326Sed  if (DS.isTypeSpecOwned())
8973212904Sdim    Decls.push_back(DS.getRepAsDecl());
8974193326Sed
8975263508Sdim  DeclaratorDecl *FirstDeclaratorInGroup = 0;
8976263508Sdim  for (unsigned i = 0, e = Group.size(); i != e; ++i)
8977263508Sdim    if (Decl *D = Group[i]) {
8978263508Sdim      if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8979263508Sdim        if (!FirstDeclaratorInGroup)
8980263508Sdim          FirstDeclaratorInGroup = DD;
8981219077Sdim      Decls.push_back(D);
8982263508Sdim    }
8983219077Sdim
8984263508Sdim  if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8985263508Sdim    if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8986263508Sdim      HandleTagNumbering(*this, Tag);
8987263508Sdim      if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8988263508Sdim        Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8989263508Sdim    }
8990263508Sdim  }
8991249423Sdim
8992263508Sdim  return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
8993219077Sdim}
8994219077Sdim
8995219077Sdim/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8996219077Sdim/// group, performing any necessary semantic checking.
8997219077SdimSema::DeclGroupPtrTy
8998263508SdimSema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
8999219077Sdim                           bool TypeMayContainAuto) {
9000218893Sdim  // C++0x [dcl.spec.auto]p7:
9001218893Sdim  //   If the type deduced for the template parameter U is not the same in each
9002218893Sdim  //   deduction, the program is ill-formed.
9003218893Sdim  // FIXME: When initializer-list support is added, a distinction is needed
9004218893Sdim  // between the deduced type U and the deduced type which 'auto' stands for.
9005218893Sdim  //   auto a = 0, b = { 1, 2, 3 };
9006218893Sdim  // is legal because the deduced type U is 'int' in both cases.
9007263508Sdim  if (TypeMayContainAuto && Group.size() > 1) {
9008218893Sdim    QualType Deduced;
9009218893Sdim    CanQualType DeducedCanon;
9010218893Sdim    VarDecl *DeducedDecl = 0;
9011263508Sdim    for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9012218893Sdim      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9013218893Sdim        AutoType *AT = D->getType()->getContainedAutoType();
9014219077Sdim        // Don't reissue diagnostics when instantiating a template.
9015219077Sdim        if (AT && D->isInvalidDecl())
9016219077Sdim          break;
9017251662Sdim        QualType U = AT ? AT->getDeducedType() : QualType();
9018251662Sdim        if (!U.isNull()) {
9019218893Sdim          CanQualType UCanon = Context.getCanonicalType(U);
9020218893Sdim          if (Deduced.isNull()) {
9021218893Sdim            Deduced = U;
9022218893Sdim            DeducedCanon = UCanon;
9023218893Sdim            DeducedDecl = D;
9024218893Sdim          } else if (DeducedCanon != UCanon) {
9025219077Sdim            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9026219077Sdim                 diag::err_auto_different_deductions)
9027251662Sdim              << (AT->isDecltypeAuto() ? 1 : 0)
9028218893Sdim              << Deduced << DeducedDecl->getDeclName()
9029218893Sdim              << U << D->getDeclName()
9030218893Sdim              << DeducedDecl->getInit()->getSourceRange()
9031218893Sdim              << D->getInit()->getSourceRange();
9032219077Sdim            D->setInvalidDecl();
9033218893Sdim            break;
9034218893Sdim          }
9035218893Sdim        }
9036218893Sdim      }
9037218893Sdim    }
9038218893Sdim  }
9039218893Sdim
9040263508Sdim  ActOnDocumentableDecls(Group);
9041239462Sdim
9042263508Sdim  return DeclGroupPtrTy::make(
9043263508Sdim      DeclGroupRef::Create(Context, Group.data(), Group.size()));
9044193326Sed}
9045193326Sed
9046239462Sdimvoid Sema::ActOnDocumentableDecl(Decl *D) {
9047263508Sdim  ActOnDocumentableDecls(D);
9048239462Sdim}
9049193326Sed
9050263508Sdimvoid Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9051239462Sdim  // Don't parse the comment if Doxygen diagnostics are ignored.
9052263508Sdim  if (Group.empty() || !Group[0])
9053239462Sdim   return;
9054239462Sdim
9055239462Sdim  if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9056239462Sdim                               Group[0]->getLocation())
9057239462Sdim        == DiagnosticsEngine::Ignored)
9058239462Sdim    return;
9059239462Sdim
9060263508Sdim  if (Group.size() >= 2) {
9061239462Sdim    // This is a decl group.  Normally it will contain only declarations
9062263508Sdim    // produced from declarator list.  But in case we have any definitions or
9063239462Sdim    // additional declaration references:
9064239462Sdim    //   'typedef struct S {} S;'
9065239462Sdim    //   'typedef struct S *S;'
9066239462Sdim    //   'struct S *pS;'
9067239462Sdim    // FinalizeDeclaratorGroup adds these as separate declarations.
9068239462Sdim    Decl *MaybeTagDecl = Group[0];
9069239462Sdim    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9070263508Sdim      Group = Group.slice(1);
9071239462Sdim    }
9072239462Sdim  }
9073239462Sdim
9074239462Sdim  // See if there are any new comments that are not attached to a decl.
9075239462Sdim  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9076239462Sdim  if (!Comments.empty() &&
9077239462Sdim      !Comments.back()->isAttached()) {
9078239462Sdim    // There is at least one comment that not attached to a decl.
9079239462Sdim    // Maybe it should be attached to one of these decls?
9080239462Sdim    //
9081239462Sdim    // Note that this way we pick up not only comments that precede the
9082239462Sdim    // declaration, but also comments that *follow* the declaration -- thanks to
9083239462Sdim    // the lookahead in the lexer: we've consumed the semicolon and looked
9084239462Sdim    // ahead through comments.
9085263508Sdim    for (unsigned i = 0, e = Group.size(); i != e; ++i)
9086243830Sdim      Context.getCommentForDecl(Group[i], &PP);
9087239462Sdim  }
9088239462Sdim}
9089239462Sdim
9090193326Sed/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9091193326Sed/// to introduce parameters into function prototype scope.
9092212904SdimDecl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9093193326Sed  const DeclSpec &DS = D.getDeclSpec();
9094193326Sed
9095193326Sed  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9096263508Sdim
9097234353Sdim  // C++03 [dcl.stc]p2 also permits 'auto'.
9098212904Sdim  VarDecl::StorageClass StorageClass = SC_None;
9099193326Sed  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9100212904Sdim    StorageClass = SC_Register;
9101234353Sdim  } else if (getLangOpts().CPlusPlus &&
9102234353Sdim             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9103234353Sdim    StorageClass = SC_Auto;
9104193326Sed  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9105193326Sed    Diag(DS.getStorageClassSpecLoc(),
9106193326Sed         diag::err_invalid_storage_class_in_func_decl);
9107193326Sed    D.getMutableDeclSpec().ClearStorageClassSpecs();
9108193326Sed  }
9109193326Sed
9110251662Sdim  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9111251662Sdim    Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9112251662Sdim      << DeclSpec::getSpecifierName(TSCS);
9113251662Sdim  if (DS.isConstexprSpecified())
9114251662Sdim    Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9115226633Sdim      << 0;
9116193326Sed
9117251662Sdim  DiagnoseFunctionSpecifiers(DS);
9118193326Sed
9119224145Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9120210299Sed  QualType parmDeclType = TInfo->getType();
9121198092Srdivacky
9122234353Sdim  if (getLangOpts().CPlusPlus) {
9123218893Sdim    // Check that there are no default arguments inside the type of this
9124218893Sdim    // parameter.
9125218893Sdim    CheckExtraCXXDefaultArguments(D);
9126218893Sdim
9127218893Sdim    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9128218893Sdim    if (D.getCXXScopeSpec().isSet()) {
9129218893Sdim      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9130218893Sdim        << D.getCXXScopeSpec().getRange();
9131218893Sdim      D.getCXXScopeSpec().clear();
9132218893Sdim    }
9133193326Sed  }
9134193326Sed
9135218893Sdim  // Ensure we have a valid name
9136218893Sdim  IdentifierInfo *II = 0;
9137218893Sdim  if (D.hasName()) {
9138218893Sdim    II = D.getIdentifier();
9139218893Sdim    if (!II) {
9140218893Sdim      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9141218893Sdim        << GetNameForDeclarator(D).getName().getAsString();
9142218893Sdim      D.setInvalidType(true);
9143218893Sdim    }
9144218893Sdim  }
9145218893Sdim
9146204643Srdivacky  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9147193326Sed  if (II) {
9148205408Srdivacky    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9149205408Srdivacky                   ForRedeclaration);
9150205408Srdivacky    LookupName(R, S);
9151205408Srdivacky    if (R.isSingleResult()) {
9152205408Srdivacky      NamedDecl *PrevDecl = R.getFoundDecl();
9153193326Sed      if (PrevDecl->isTemplateParameter()) {
9154193326Sed        // Maybe we will complain about the shadowed template parameter.
9155193326Sed        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9156193326Sed        // Just pretend that we didn't see the previous declaration.
9157193326Sed        PrevDecl = 0;
9158212904Sdim      } else if (S->isDeclScope(PrevDecl)) {
9159193326Sed        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9160204643Srdivacky        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9161193326Sed
9162193326Sed        // Recover by removing the name
9163193326Sed        II = 0;
9164193326Sed        D.SetIdentifier(0, D.getIdentifierLoc());
9165203955Srdivacky        D.setInvalidType(true);
9166193326Sed      }
9167193326Sed    }
9168193326Sed  }
9169193326Sed
9170202879Srdivacky  // Temporarily put parameter variables in the translation unit, not
9171202879Srdivacky  // the enclosing context.  This prevents them from accidentally
9172202879Srdivacky  // looking like class members in C++.
9173207619Srdivacky  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9174234353Sdim                                    D.getLocStart(),
9175221345Sdim                                    D.getIdentifierLoc(), II,
9176221345Sdim                                    parmDeclType, TInfo,
9177249423Sdim                                    StorageClass);
9178202879Srdivacky
9179193326Sed  if (D.isInvalidType())
9180221345Sdim    New->setInvalidDecl();
9181221345Sdim
9182221345Sdim  assert(S->isFunctionPrototypeScope());
9183221345Sdim  assert(S->getFunctionPrototypeDepth() >= 1);
9184221345Sdim  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9185221345Sdim                    S->getNextFunctionPrototypeIndex());
9186207619Srdivacky
9187193326Sed  // Add the parameter declaration into this scope.
9188212904Sdim  S->AddDecl(New);
9189193326Sed  if (II)
9190193326Sed    IdResolver.AddDecl(New);
9191193326Sed
9192194613Sed  ProcessDeclAttributes(S, New, D);
9193193326Sed
9194226633Sdim  if (D.getDeclSpec().isModulePrivateSpecified())
9195226633Sdim    Diag(New->getLocation(), diag::err_module_private_local)
9196226633Sdim      << 1 << New->getDeclName()
9197226633Sdim      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9198226633Sdim      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9199226633Sdim
9200195341Sed  if (New->hasAttr<BlocksAttr>()) {
9201193326Sed    Diag(New->getLocation(), diag::err_block_on_nonlocal);
9202193326Sed  }
9203212904Sdim  return New;
9204193326Sed}
9205193326Sed
9206210299Sed/// \brief Synthesizes a variable for a parameter arising from a
9207210299Sed/// typedef.
9208210299SedParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9209210299Sed                                              SourceLocation Loc,
9210210299Sed                                              QualType T) {
9211221345Sdim  /* FIXME: setting StartLoc == Loc.
9212221345Sdim     Would it be worth to modify callers so as to provide proper source
9213221345Sdim     location for the unnamed parameters, embedding the parameter's type? */
9214221345Sdim  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9215210299Sed                                T, Context.getTrivialTypeSourceInfo(T, Loc),
9216249423Sdim                                           SC_None, 0);
9217210299Sed  Param->setImplicit();
9218210299Sed  return Param;
9219210299Sed}
9220210299Sed
9221212904Sdimvoid Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9222212904Sdim                                    ParmVarDecl * const *ParamEnd) {
9223212904Sdim  // Don't diagnose unused-parameter errors in template instantiations; we
9224212904Sdim  // will already have done so in the template itself.
9225212904Sdim  if (!ActiveTemplateInstantiations.empty())
9226212904Sdim    return;
9227212904Sdim
9228212904Sdim  for (; Param != ParamEnd; ++Param) {
9229234353Sdim    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9230212904Sdim        !(*Param)->hasAttr<UnusedAttr>()) {
9231212904Sdim      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9232212904Sdim        << (*Param)->getDeclName();
9233212904Sdim    }
9234212904Sdim  }
9235212904Sdim}
9236212904Sdim
9237218893Sdimvoid Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9238218893Sdim                                                  ParmVarDecl * const *ParamEnd,
9239218893Sdim                                                  QualType ReturnTy,
9240218893Sdim                                                  NamedDecl *D) {
9241218893Sdim  if (LangOpts.NumLargeByValueCopy == 0) // No check.
9242218893Sdim    return;
9243218893Sdim
9244218893Sdim  // Warn if the return value is pass-by-value and larger than the specified
9245218893Sdim  // threshold.
9246234353Sdim  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9247218893Sdim    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9248218893Sdim    if (Size > LangOpts.NumLargeByValueCopy)
9249218893Sdim      Diag(D->getLocation(), diag::warn_return_value_size)
9250218893Sdim          << D->getDeclName() << Size;
9251218893Sdim  }
9252218893Sdim
9253218893Sdim  // Warn if any parameter is pass-by-value and larger than the specified
9254218893Sdim  // threshold.
9255218893Sdim  for (; Param != ParamEnd; ++Param) {
9256218893Sdim    QualType T = (*Param)->getType();
9257234353Sdim    if (T->isDependentType() || !T.isPODType(Context))
9258218893Sdim      continue;
9259218893Sdim    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9260218893Sdim    if (Size > LangOpts.NumLargeByValueCopy)
9261218893Sdim      Diag((*Param)->getLocation(), diag::warn_parameter_size)
9262218893Sdim          << (*Param)->getDeclName() << Size;
9263218893Sdim  }
9264218893Sdim}
9265218893Sdim
9266221345SdimParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9267221345Sdim                                  SourceLocation NameLoc, IdentifierInfo *Name,
9268221345Sdim                                  QualType T, TypeSourceInfo *TSInfo,
9269249423Sdim                                  VarDecl::StorageClass StorageClass) {
9270224145Sdim  // In ARC, infer a lifetime qualifier for appropriate parameter types.
9271234353Sdim  if (getLangOpts().ObjCAutoRefCount &&
9272224145Sdim      T.getObjCLifetime() == Qualifiers::OCL_None &&
9273224145Sdim      T->isObjCLifetimeType()) {
9274224145Sdim
9275224145Sdim    Qualifiers::ObjCLifetime lifetime;
9276224145Sdim
9277224145Sdim    // Special cases for arrays:
9278224145Sdim    //   - if it's const, use __unsafe_unretained
9279224145Sdim    //   - otherwise, it's an error
9280224145Sdim    if (T->isArrayType()) {
9281224145Sdim      if (!T.isConstQualified()) {
9282226633Sdim        DelayedDiagnostics.add(
9283226633Sdim            sema::DelayedDiagnostic::makeForbiddenType(
9284226633Sdim            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9285224145Sdim      }
9286224145Sdim      lifetime = Qualifiers::OCL_ExplicitNone;
9287224145Sdim    } else {
9288224145Sdim      lifetime = T->getObjCARCImplicitLifetime();
9289224145Sdim    }
9290224145Sdim    T = Context.getLifetimeQualifiedType(T, lifetime);
9291224145Sdim  }
9292224145Sdim
9293221345Sdim  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9294224145Sdim                                         Context.getAdjustedParameterType(T),
9295224145Sdim                                         TSInfo,
9296249423Sdim                                         StorageClass, 0);
9297207619Srdivacky
9298207619Srdivacky  // Parameters can not be abstract class types.
9299207619Srdivacky  // For record types, this is done by the AbstractClassUsageDiagnoser once
9300207619Srdivacky  // the class has been completely parsed.
9301207619Srdivacky  if (!CurContext->isRecord() &&
9302207619Srdivacky      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9303207619Srdivacky                             AbstractParamType))
9304207619Srdivacky    New->setInvalidDecl();
9305207619Srdivacky
9306207619Srdivacky  // Parameter declarators cannot be interface types. All ObjC objects are
9307207619Srdivacky  // passed by reference.
9308208600Srdivacky  if (T->isObjCObjectType()) {
9309239462Sdim    SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9310207619Srdivacky    Diag(NameLoc,
9311226633Sdim         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9312239462Sdim      << FixItHint::CreateInsertion(TypeEndLoc, "*");
9313226633Sdim    T = Context.getObjCObjectPointerType(T);
9314226633Sdim    New->setType(T);
9315207619Srdivacky  }
9316207619Srdivacky
9317207619Srdivacky  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9318207619Srdivacky  // duration shall not be qualified by an address-space qualifier."
9319207619Srdivacky  // Since all parameters have automatic store duration, they can not have
9320207619Srdivacky  // an address space.
9321207619Srdivacky  if (T.getAddressSpace() != 0) {
9322207619Srdivacky    Diag(NameLoc, diag::err_arg_with_address_space);
9323207619Srdivacky    New->setInvalidDecl();
9324207619Srdivacky  }
9325207619Srdivacky
9326207619Srdivacky  return New;
9327203955Srdivacky}
9328203955Srdivacky
9329193326Sedvoid Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9330193326Sed                                           SourceLocation LocAfterDecls) {
9331218893Sdim  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9332193326Sed
9333193326Sed  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9334193326Sed  // for a K&R function.
9335193326Sed  if (!FTI.hasPrototype) {
9336193326Sed    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9337193326Sed      --i;
9338193326Sed      if (FTI.ArgInfo[i].Param == 0) {
9339234353Sdim        SmallString<256> Code;
9340198398Srdivacky        llvm::raw_svector_ostream(Code) << "  int "
9341198398Srdivacky                                        << FTI.ArgInfo[i].Ident->getName()
9342198398Srdivacky                                        << ";\n";
9343193326Sed        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
9344193326Sed          << FTI.ArgInfo[i].Ident
9345206084Srdivacky          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9346193326Sed
9347193326Sed        // Implicitly declare the argument as type 'int' for lack of a better
9348193326Sed        // type.
9349221345Sdim        AttributeFactory attrs;
9350221345Sdim        DeclSpec DS(attrs);
9351193326Sed        const char* PrevSpec; // unused
9352198092Srdivacky        unsigned DiagID; // unused
9353198092Srdivacky        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
9354198092Srdivacky                           PrevSpec, DiagID);
9355243830Sdim        // Use the identifier location for the type source range.
9356243830Sdim        DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9357243830Sdim        DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
9358193326Sed        Declarator ParamD(DS, Declarator::KNRTypeListContext);
9359193326Sed        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
9360193326Sed        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
9361193326Sed      }
9362193326Sed    }
9363198092Srdivacky  }
9364193326Sed}
9365193326Sed
9366234982SdimDecl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9367193326Sed  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9368218893Sdim  assert(D.isFunctionDeclarator() && "Not a function declarator!");
9369193326Sed  Scope *ParentScope = FnBodyScope->getParent();
9370193326Sed
9371234353Sdim  D.setFunctionDefinitionKind(FDK_Definition);
9372243830Sdim  Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9373193326Sed  return ActOnStartOfFunctionDef(FnBodyScope, DP);
9374193326Sed}
9375193326Sed
9376249423Sdimstatic bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9377249423Sdim                             const FunctionDecl*& PossibleZeroParamPrototype) {
9378200583Srdivacky  // Don't warn about invalid declarations.
9379200583Srdivacky  if (FD->isInvalidDecl())
9380200583Srdivacky    return false;
9381200583Srdivacky
9382200583Srdivacky  // Or declarations that aren't global.
9383200583Srdivacky  if (!FD->isGlobal())
9384200583Srdivacky    return false;
9385200583Srdivacky
9386200583Srdivacky  // Don't warn about C++ member functions.
9387200583Srdivacky  if (isa<CXXMethodDecl>(FD))
9388200583Srdivacky    return false;
9389200583Srdivacky
9390200583Srdivacky  // Don't warn about 'main'.
9391200583Srdivacky  if (FD->isMain())
9392200583Srdivacky    return false;
9393200583Srdivacky
9394200583Srdivacky  // Don't warn about inline functions.
9395221345Sdim  if (FD->isInlined())
9396200583Srdivacky    return false;
9397200583Srdivacky
9398200583Srdivacky  // Don't warn about function templates.
9399200583Srdivacky  if (FD->getDescribedFunctionTemplate())
9400200583Srdivacky    return false;
9401200583Srdivacky
9402200583Srdivacky  // Don't warn about function template specializations.
9403200583Srdivacky  if (FD->isFunctionTemplateSpecialization())
9404200583Srdivacky    return false;
9405200583Srdivacky
9406239462Sdim  // Don't warn for OpenCL kernels.
9407239462Sdim  if (FD->hasAttr<OpenCLKernelAttr>())
9408239462Sdim    return false;
9409263508Sdim
9410200583Srdivacky  bool MissingPrototype = true;
9411234353Sdim  for (const FunctionDecl *Prev = FD->getPreviousDecl();
9412234353Sdim       Prev; Prev = Prev->getPreviousDecl()) {
9413200583Srdivacky    // Ignore any declarations that occur in function or method
9414200583Srdivacky    // scope, because they aren't visible from the header.
9415263508Sdim    if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9416200583Srdivacky      continue;
9417263508Sdim
9418200583Srdivacky    MissingPrototype = !Prev->getType()->isFunctionProtoType();
9419249423Sdim    if (FD->getNumParams() == 0)
9420249423Sdim      PossibleZeroParamPrototype = Prev;
9421200583Srdivacky    break;
9422200583Srdivacky  }
9423263508Sdim
9424200583Srdivacky  return MissingPrototype;
9425200583Srdivacky}
9426200583Srdivacky
9427263508Sdimvoid
9428263508SdimSema::CheckForFunctionRedefinition(FunctionDecl *FD,
9429263508Sdim                                   const FunctionDecl *EffectiveDefinition) {
9430221345Sdim  // Don't complain if we're in GNU89 mode and the previous definition
9431221345Sdim  // was an extern inline function.
9432263508Sdim  const FunctionDecl *Definition = EffectiveDefinition;
9433263508Sdim  if (!Definition)
9434263508Sdim    if (!FD->isDefined(Definition))
9435263508Sdim      return;
9436263508Sdim
9437263508Sdim  if (canRedefineFunction(Definition, getLangOpts()))
9438263508Sdim    return;
9439263508Sdim
9440263508Sdim  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9441263508Sdim      Definition->getStorageClass() == SC_Extern)
9442263508Sdim    Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9443234353Sdim        << FD->getDeclName() << getLangOpts().CPlusPlus;
9444263508Sdim  else
9445263508Sdim    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9446263508Sdim
9447263508Sdim  Diag(Definition->getLocation(), diag::note_previous_definition);
9448263508Sdim  FD->setInvalidDecl();
9449263508Sdim}
9450263508Sdim
9451263508Sdim
9452263508Sdimstatic void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9453263508Sdim                                   Sema &S) {
9454263508Sdim  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9455263508Sdim
9456263508Sdim  LambdaScopeInfo *LSI = S.PushLambdaScope();
9457263508Sdim  LSI->CallOperator = CallOperator;
9458263508Sdim  LSI->Lambda = LambdaClass;
9459263508Sdim  LSI->ReturnType = CallOperator->getResultType();
9460263508Sdim  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9461263508Sdim
9462263508Sdim  if (LCD == LCD_None)
9463263508Sdim    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9464263508Sdim  else if (LCD == LCD_ByCopy)
9465263508Sdim    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9466263508Sdim  else if (LCD == LCD_ByRef)
9467263508Sdim    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9468263508Sdim  DeclarationNameInfo DNI = CallOperator->getNameInfo();
9469263508Sdim
9470263508Sdim  LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9471263508Sdim  LSI->Mutable = !CallOperator->isConst();
9472263508Sdim
9473263508Sdim  // Add the captures to the LSI so they can be noted as already
9474263508Sdim  // captured within tryCaptureVar.
9475263508Sdim  for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9476263508Sdim      CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9477263508Sdim    if (C->capturesVariable()) {
9478263508Sdim      VarDecl *VD = C->getCapturedVar();
9479263508Sdim      if (VD->isInitCapture())
9480263508Sdim        S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9481263508Sdim      QualType CaptureType = VD->getType();
9482263508Sdim      const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9483263508Sdim      LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9484263508Sdim          /*RefersToEnclosingLocal*/true, C->getLocation(),
9485263508Sdim          /*EllipsisLoc*/C->isPackExpansion()
9486263508Sdim                         ? C->getEllipsisLoc() : SourceLocation(),
9487263508Sdim          CaptureType, /*Expr*/ 0);
9488263508Sdim
9489263508Sdim    } else if (C->capturesThis()) {
9490263508Sdim      LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9491263508Sdim                              S.getCurrentThisType(), /*Expr*/ 0);
9492263508Sdim    }
9493221345Sdim  }
9494221345Sdim}
9495221345Sdim
9496212904SdimDecl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9497198893Srdivacky  // Clear the last template instantiation error context.
9498198893Srdivacky  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9499198893Srdivacky
9500195099Sed  if (!D)
9501195099Sed    return D;
9502198092Srdivacky  FunctionDecl *FD = 0;
9503193326Sed
9504212904Sdim  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9505198092Srdivacky    FD = FunTmpl->getTemplatedDecl();
9506198092Srdivacky  else
9507212904Sdim    FD = cast<FunctionDecl>(D);
9508263508Sdim  // If we are instantiating a generic lambda call operator, push
9509263508Sdim  // a LambdaScopeInfo onto the function stack.  But use the information
9510263508Sdim  // that's already been calculated (ActOnLambdaExpr) to prime the current
9511263508Sdim  // LambdaScopeInfo.
9512263508Sdim  // When the template operator is being specialized, the LambdaScopeInfo,
9513263508Sdim  // has to be properly restored so that tryCaptureVariable doesn't try
9514263508Sdim  // and capture any new variables. In addition when calculating potential
9515263508Sdim  // captures during transformation of nested lambdas, it is necessary to
9516263508Sdim  // have the LSI properly restored.
9517263508Sdim  if (isGenericLambdaCallOperatorSpecialization(FD)) {
9518263508Sdim    assert(ActiveTemplateInstantiations.size() &&
9519263508Sdim      "There should be an active template instantiation on the stack "
9520263508Sdim      "when instantiating a generic lambda!");
9521263508Sdim    RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9522263508Sdim  }
9523263508Sdim  else
9524263508Sdim    // Enter a new function scope
9525263508Sdim    PushFunctionScope();
9526198092Srdivacky
9527193326Sed  // See if this is a redefinition.
9528221345Sdim  if (!FD->isLateTemplateParsed())
9529221345Sdim    CheckForFunctionRedefinition(FD);
9530193326Sed
9531193326Sed  // Builtin functions cannot be defined.
9532198092Srdivacky  if (unsigned BuiltinID = FD->getBuiltinID()) {
9533251790Sandrew    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9534251790Sandrew        !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9535193326Sed      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9536193326Sed      FD->setInvalidDecl();
9537193326Sed    }
9538193326Sed  }
9539193326Sed
9540193326Sed  // The return type of a function definition must be complete
9541193326Sed  // (C99 6.9.1p3, C++ [dcl.fct]p6).
9542193326Sed  QualType ResultType = FD->getResultType();
9543193326Sed  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9544193326Sed      !FD->isInvalidDecl() &&
9545193326Sed      RequireCompleteType(FD->getLocation(), ResultType,
9546193326Sed                          diag::err_func_def_incomplete_result))
9547193326Sed    FD->setInvalidDecl();
9548193326Sed
9549193326Sed  // GNU warning -Wmissing-prototypes:
9550193326Sed  //   Warn if a global function is defined without a previous
9551193326Sed  //   prototype declaration. This warning is issued even if the
9552193326Sed  //   definition itself provides a prototype. The aim is to detect
9553193326Sed  //   global functions that fail to be declared in header files.
9554249423Sdim  const FunctionDecl *PossibleZeroParamPrototype = 0;
9555249423Sdim  if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9556200583Srdivacky    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9557263508Sdim
9558249423Sdim    if (PossibleZeroParamPrototype) {
9559263508Sdim      // We found a declaration that is not a prototype,
9560249423Sdim      // but that could be a zero-parameter prototype
9561263508Sdim      if (TypeSourceInfo *TI =
9562263508Sdim              PossibleZeroParamPrototype->getTypeSourceInfo()) {
9563263508Sdim        TypeLoc TL = TI->getTypeLoc();
9564263508Sdim        if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9565263508Sdim          Diag(PossibleZeroParamPrototype->getLocation(),
9566263508Sdim               diag::note_declaration_not_a_prototype)
9567263508Sdim            << PossibleZeroParamPrototype
9568263508Sdim            << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9569263508Sdim      }
9570249423Sdim    }
9571249423Sdim  }
9572193326Sed
9573193326Sed  if (FnBodyScope)
9574193326Sed    PushDeclContext(FnBodyScope, FD);
9575193326Sed
9576193326Sed  // Check the validity of our function parameters
9577218893Sdim  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9578218893Sdim                           /*CheckParameterNames=*/true);
9579193326Sed
9580193326Sed  // Introduce our parameters into the function scope
9581193326Sed  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9582193326Sed    ParmVarDecl *Param = FD->getParamDecl(p);
9583193326Sed    Param->setOwningFunction(FD);
9584193326Sed
9585193326Sed    // If this has an identifier, add it to the scope stack.
9586206084Srdivacky    if (Param->getIdentifier() && FnBodyScope) {
9587218893Sdim      CheckShadow(FnBodyScope, Param);
9588206084Srdivacky
9589193326Sed      PushOnScopeChains(Param, FnBodyScope);
9590206084Srdivacky    }
9591193326Sed  }
9592193326Sed
9593234353Sdim  // If we had any tags defined in the function prototype,
9594234353Sdim  // introduce them into the function scope.
9595234353Sdim  if (FnBodyScope) {
9596263508Sdim    for (ArrayRef<NamedDecl *>::iterator
9597263508Sdim             I = FD->getDeclsInPrototypeScope().begin(),
9598263508Sdim             E = FD->getDeclsInPrototypeScope().end();
9599263508Sdim         I != E; ++I) {
9600234353Sdim      NamedDecl *D = *I;
9601234353Sdim
9602234353Sdim      // Some of these decls (like enums) may have been pinned to the translation unit
9603234353Sdim      // for lack of a real context earlier. If so, remove from the translation unit
9604234353Sdim      // and reattach to the current context.
9605234353Sdim      if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9606234353Sdim        // Is the decl actually in the context?
9607234353Sdim        for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9608234353Sdim               DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9609234353Sdim          if (*DI == D) {
9610234353Sdim            Context.getTranslationUnitDecl()->removeDecl(D);
9611234353Sdim            break;
9612234353Sdim          }
9613234353Sdim        }
9614234353Sdim        // Either way, reassign the lexical decl context to our FunctionDecl.
9615234353Sdim        D->setLexicalDeclContext(CurContext);
9616234353Sdim      }
9617234353Sdim
9618234353Sdim      // If the decl has a non-null name, make accessible in the current scope.
9619234353Sdim      if (!D->getName().empty())
9620234353Sdim        PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9621234353Sdim
9622234353Sdim      // Similarly, dive into enums and fish their constants out, making them
9623234353Sdim      // accessible in this scope.
9624234353Sdim      if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9625234353Sdim        for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9626234353Sdim               EE = ED->enumerator_end(); EI != EE; ++EI)
9627234353Sdim          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9628234353Sdim      }
9629234353Sdim    }
9630234353Sdim  }
9631234353Sdim
9632234982Sdim  // Ensure that the function's exception specification is instantiated.
9633234982Sdim  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9634234982Sdim    ResolveExceptionSpec(D->getLocation(), FPT);
9635234982Sdim
9636193326Sed  // Checking attributes of current function definition
9637193326Sed  // dllimport attribute.
9638212904Sdim  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9639212904Sdim  if (DA && (!FD->getAttr<DLLExportAttr>())) {
9640212904Sdim    // dllimport attribute cannot be directly applied to definition.
9641221345Sdim    // Microsoft accepts dllimport for functions defined within class scope.
9642221345Sdim    if (!DA->isInherited() &&
9643226633Sdim        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9644193326Sed      Diag(FD->getLocation(),
9645193326Sed           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9646193326Sed        << "dllimport";
9647193326Sed      FD->setInvalidDecl();
9648249423Sdim      return D;
9649204643Srdivacky    }
9650204643Srdivacky
9651204643Srdivacky    // Visual C++ appears to not think this is an issue, so only issue
9652204643Srdivacky    // a warning when Microsoft extensions are disabled.
9653226633Sdim    if (!LangOpts.MicrosoftExt) {
9654193326Sed      // If a symbol previously declared dllimport is later defined, the
9655193326Sed      // attribute is ignored in subsequent references, and a warning is
9656193326Sed      // emitted.
9657193326Sed      Diag(FD->getLocation(),
9658193326Sed           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9659212904Sdim        << FD->getName() << "dllimport";
9660193326Sed    }
9661193326Sed  }
9662239462Sdim  // We want to attach documentation to original Decl (which might be
9663239462Sdim  // a function template).
9664239462Sdim  ActOnDocumentableDecl(D);
9665249423Sdim  return D;
9666193326Sed}
9667193326Sed
9668208600Srdivacky/// \brief Given the set of return statements within a function body,
9669208600Srdivacky/// compute the variables that are subject to the named return value
9670208600Srdivacky/// optimization.
9671208600Srdivacky///
9672208600Srdivacky/// Each of the variables that is subject to the named return value
9673208600Srdivacky/// optimization will be marked as NRVO variables in the AST, and any
9674208600Srdivacky/// return statement that has a marked NRVO variable as its NRVO candidate can
9675208600Srdivacky/// use the named return value optimization.
9676208600Srdivacky///
9677208600Srdivacky/// This function applies a very simplistic algorithm for NRVO: if every return
9678208600Srdivacky/// statement in the function has the same NRVO candidate, that candidate is
9679208600Srdivacky/// the NRVO variable.
9680208600Srdivacky///
9681208600Srdivacky/// FIXME: Employ a smarter algorithm that accounts for multiple return
9682208600Srdivacky/// statements and the lifetimes of the NRVO candidates. We should be able to
9683208600Srdivacky/// find a maximal set of NRVO variables.
9684226633Sdimvoid Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9685212904Sdim  ReturnStmt **Returns = Scope->Returns.data();
9686212904Sdim
9687208600Srdivacky  const VarDecl *NRVOCandidate = 0;
9688212904Sdim  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9689208600Srdivacky    if (!Returns[I]->getNRVOCandidate())
9690208600Srdivacky      return;
9691208600Srdivacky
9692208600Srdivacky    if (!NRVOCandidate)
9693208600Srdivacky      NRVOCandidate = Returns[I]->getNRVOCandidate();
9694208600Srdivacky    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9695208600Srdivacky      return;
9696208600Srdivacky  }
9697208600Srdivacky
9698208600Srdivacky  if (NRVOCandidate)
9699208600Srdivacky    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9700208600Srdivacky}
9701208600Srdivacky
9702249423Sdimbool Sema::canSkipFunctionBody(Decl *D) {
9703249423Sdim  if (!Consumer.shouldSkipFunctionBody(D))
9704249423Sdim    return false;
9705249423Sdim
9706249423Sdim  if (isa<ObjCMethodDecl>(D))
9707249423Sdim    return true;
9708249423Sdim
9709249423Sdim  FunctionDecl *FD = 0;
9710249423Sdim  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9711249423Sdim    FD = FTD->getTemplatedDecl();
9712249423Sdim  else
9713249423Sdim    FD = cast<FunctionDecl>(D);
9714249423Sdim
9715249423Sdim  // We cannot skip the body of a function (or function template) which is
9716249423Sdim  // constexpr, since we may need to evaluate its body in order to parse the
9717249423Sdim  // rest of the file.
9718263508Sdim  // We cannot skip the body of a function with an undeduced return type,
9719263508Sdim  // because any callers of that function need to know the type.
9720263508Sdim  return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
9721249423Sdim}
9722249423Sdim
9723249423SdimDecl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9724249423Sdim  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9725249423Sdim    FD->setHasSkippedBody();
9726249423Sdim  else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9727249423Sdim    MD->setHasSkippedBody();
9728249423Sdim  return ActOnFinishFunctionBody(Decl, 0);
9729249423Sdim}
9730249423Sdim
9731212904SdimDecl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9732243830Sdim  return ActOnFinishFunctionBody(D, BodyArg, false);
9733193326Sed}
9734193326Sed
9735212904SdimDecl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9736212904Sdim                                    bool IsInstantiation) {
9737198092Srdivacky  FunctionDecl *FD = 0;
9738198092Srdivacky  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9739198092Srdivacky  if (FunTmpl)
9740198092Srdivacky    FD = FunTmpl->getTemplatedDecl();
9741198092Srdivacky  else
9742198092Srdivacky    FD = dyn_cast_or_null<FunctionDecl>(dcl);
9743198092Srdivacky
9744206084Srdivacky  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9745219077Sdim  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9746205408Srdivacky
9747198092Srdivacky  if (FD) {
9748193326Sed    FD->setBody(Body);
9749234353Sdim
9750263508Sdim    if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9751263508Sdim        !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9752263508Sdim      // If the function has a deduced result type but contains no 'return'
9753263508Sdim      // statements, the result type as written must be exactly 'auto', and
9754263508Sdim      // the deduced result type is 'void'.
9755263508Sdim      if (!FD->getResultType()->getAs<AutoType>()) {
9756263508Sdim        Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9757263508Sdim          << FD->getResultType();
9758263508Sdim        FD->setInvalidDecl();
9759263508Sdim      } else {
9760263508Sdim        // Substitute 'void' for the 'auto' in the type.
9761263508Sdim        TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9762263508Sdim            IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9763263508Sdim        Context.adjustDeducedFunctionResultType(
9764263508Sdim            FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9765251662Sdim      }
9766251662Sdim    }
9767251662Sdim
9768249423Sdim    // The only way to be included in UndefinedButUsed is if there is an
9769249423Sdim    // ODR use before the definition. Avoid the expensive map lookup if this
9770249423Sdim    // is the first declaration.
9771263508Sdim    if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9772263508Sdim      if (!FD->isExternallyVisible())
9773249423Sdim        UndefinedButUsed.erase(FD);
9774249423Sdim      else if (FD->isInlined() &&
9775249423Sdim               (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9776249423Sdim               (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9777249423Sdim        UndefinedButUsed.erase(FD);
9778249423Sdim    }
9779249423Sdim
9780234353Sdim    // If the function implicitly returns zero (like 'main') or is naked,
9781234353Sdim    // don't complain about missing return statements.
9782234353Sdim    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9783206084Srdivacky      WP.disableCheckFallThrough();
9784198092Srdivacky
9785223017Sdim    // MSVC permits the use of pure specifier (=0) on function definition,
9786223017Sdim    // defined at class scope, warn about this non standard construct.
9787263508Sdim    if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9788223017Sdim      Diag(FD->getLocation(), diag::warn_pure_function_definition);
9789223017Sdim
9790208600Srdivacky    if (!FD->isInvalidDecl()) {
9791194613Sed      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9792218893Sdim      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9793218893Sdim                                             FD->getResultType(), FD);
9794208600Srdivacky
9795208600Srdivacky      // If this is a constructor, we need a vtable.
9796208600Srdivacky      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9797208600Srdivacky        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9798208600Srdivacky
9799239462Sdim      // Try to apply the named return value optimization. We have to check
9800239462Sdim      // if we can do this here because lambdas keep return statements around
9801239462Sdim      // to deduce an implicit return type.
9802239462Sdim      if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9803239462Sdim          !FD->isDependentContext())
9804239462Sdim        computeNRVO(Body, getCurFunction());
9805208600Srdivacky    }
9806208600Srdivacky
9807234353Sdim    assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9808234353Sdim           "Function parsing confused");
9809193326Sed  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9810193326Sed    assert(MD == getCurMethodDecl() && "Method parsing confused");
9811193326Sed    MD->setBody(Body);
9812218893Sdim    if (!MD->isInvalidDecl()) {
9813194613Sed      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9814218893Sdim      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9815218893Sdim                                             MD->getResultType(), MD);
9816226633Sdim
9817226633Sdim      if (Body)
9818226633Sdim        computeNRVO(Body, getCurFunction());
9819218893Sdim    }
9820243830Sdim    if (getCurFunction()->ObjCShouldCallSuper) {
9821243830Sdim      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9822243830Sdim        << MD->getSelector().getAsString();
9823243830Sdim      getCurFunction()->ObjCShouldCallSuper = false;
9824226633Sdim    }
9825193326Sed  } else {
9826212904Sdim    return 0;
9827193326Sed  }
9828193326Sed
9829243830Sdim  assert(!getCurFunction()->ObjCShouldCallSuper &&
9830239462Sdim         "This should only be set for ObjC methods, which should have been "
9831239462Sdim         "handled in the block above.");
9832226633Sdim
9833193326Sed  // Verify and clean out per-function state.
9834204643Srdivacky  if (Body) {
9835204643Srdivacky    // C++ constructors that have function-try-blocks can't have return
9836204643Srdivacky    // statements in the handlers of that block. (C++ [except.handle]p14)
9837204643Srdivacky    // Verify this.
9838204643Srdivacky    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9839204643Srdivacky      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9840204643Srdivacky
9841226633Sdim    // Verify that gotos and switch cases don't jump into scopes illegally.
9842212904Sdim    if (getCurFunction()->NeedsScopeChecking() &&
9843208600Srdivacky        !dcl->isInvalidDecl() &&
9844239462Sdim        !hasAnyUnrecoverableErrorsInThisFunction() &&
9845239462Sdim        !PP.isCodeCompletionEnabled())
9846204643Srdivacky      DiagnoseInvalidJumps(Body);
9847193326Sed
9848212904Sdim    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9849212904Sdim      if (!Destructor->getParent()->isDependentType())
9850212904Sdim        CheckDestructor(Destructor);
9851212904Sdim
9852205408Srdivacky      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9853205408Srdivacky                                             Destructor->getParent());
9854212904Sdim    }
9855204643Srdivacky
9856204643Srdivacky    // If any errors have occurred, clear out any temporaries that may have
9857204643Srdivacky    // been leftover. This ensures that these temporaries won't be picked up for
9858204643Srdivacky    // deletion in some later function.
9859221345Sdim    if (PP.getDiagnostics().hasErrorOccurred() ||
9860224145Sdim        PP.getDiagnostics().getSuppressAllDiagnostics()) {
9861234353Sdim      DiscardCleanupsInEvaluationContext();
9862249423Sdim    }
9863249423Sdim    if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9864249423Sdim        !isa<FunctionTemplateDecl>(dcl)) {
9865205408Srdivacky      // Since the body is valid, issue any analysis-based warnings that are
9866205408Srdivacky      // enabled.
9867219077Sdim      ActivePolicy = &WP;
9868205408Srdivacky    }
9869205408Srdivacky
9870234353Sdim    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9871234353Sdim        (!CheckConstexprFunctionDecl(FD) ||
9872234353Sdim         !CheckConstexprFunctionBody(FD, Body)))
9873226633Sdim      FD->setInvalidDecl();
9874226633Sdim
9875234353Sdim    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9876224145Sdim    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9877234353Sdim    assert(MaybeODRUseExprs.empty() &&
9878234353Sdim           "Leftover expressions for odr-use checking");
9879204643Srdivacky  }
9880199482Srdivacky
9881206084Srdivacky  if (!IsInstantiation)
9882206084Srdivacky    PopDeclContext();
9883206084Srdivacky
9884234353Sdim  PopFunctionScopeInfo(ActivePolicy, dcl);
9885199482Srdivacky  // If any errors have occurred, clear out any temporaries that may have
9886199482Srdivacky  // been leftover. This ensures that these temporaries won't be picked up for
9887199482Srdivacky  // deletion in some later function.
9888224145Sdim  if (getDiagnostics().hasErrorOccurred()) {
9889234353Sdim    DiscardCleanupsInEvaluationContext();
9890224145Sdim  }
9891212904Sdim
9892212904Sdim  return dcl;
9893193326Sed}
9894193326Sed
9895226633Sdim
9896226633Sdim/// When we finish delayed parsing of an attribute, we must attach it to the
9897226633Sdim/// relevant Decl.
9898226633Sdimvoid Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9899226633Sdim                                       ParsedAttributes &Attrs) {
9900234353Sdim  // Always attach attributes to the underlying decl.
9901234353Sdim  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9902234353Sdim    D = TD->getTemplatedDecl();
9903234982Sdim  ProcessDeclAttributeList(S, D, Attrs.getList());
9904234982Sdim
9905234982Sdim  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9906234982Sdim    if (Method->isStatic())
9907234982Sdim      checkThisInStaticMemberFunctionAttributes(Method);
9908226633Sdim}
9909226633Sdim
9910226633Sdim
9911193326Sed/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9912193326Sed/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9913198092SrdivackyNamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9914193326Sed                                          IdentifierInfo &II, Scope *S) {
9915193326Sed  // Before we produce a declaration for an implicitly defined
9916193326Sed  // function, see whether there was a locally-scoped declaration of
9917193326Sed  // this name as a function or variable. If so, use that
9918193326Sed  // (non-visible) declaration, and complain about it.
9919263508Sdim  if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9920263508Sdim    Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9921263508Sdim    Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9922263508Sdim    return ExternCPrev;
9923193326Sed  }
9924193326Sed
9925193326Sed  // Extension in C99.  Legal in C90, but warn about it.
9926234353Sdim  unsigned diag_id;
9927198398Srdivacky  if (II.getName().startswith("__builtin_"))
9928234353Sdim    diag_id = diag::warn_builtin_unknown;
9929234353Sdim  else if (getLangOpts().C99)
9930234353Sdim    diag_id = diag::ext_implicit_function_decl;
9931193326Sed  else
9932234353Sdim    diag_id = diag::warn_implicit_function_decl;
9933234353Sdim  Diag(Loc, diag_id) << &II;
9934193326Sed
9935234353Sdim  // Because typo correction is expensive, only do it if the implicit
9936234353Sdim  // function declaration is going to be treated as an error.
9937234353Sdim  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9938234353Sdim    TypoCorrection Corrected;
9939234353Sdim    DeclFilterCCC<FunctionDecl> Validator;
9940234353Sdim    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9941263508Sdim                                      LookupOrdinaryName, S, 0, Validator)))
9942263508Sdim      diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9943263508Sdim                   /*ErrorRecovery*/false);
9944234353Sdim  }
9945234353Sdim
9946193326Sed  // Set a Declarator for the implicit definition: int foo();
9947193326Sed  const char *Dummy;
9948221345Sdim  AttributeFactory attrFactory;
9949221345Sdim  DeclSpec DS(attrFactory);
9950198092Srdivacky  unsigned DiagID;
9951198092Srdivacky  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
9952218893Sdim  (void)Error; // Silence warning.
9953193326Sed  assert(!Error && "Error setting up implicit decl!");
9954243830Sdim  SourceLocation NoLoc;
9955193326Sed  Declarator D(DS, Declarator::BlockContext);
9956243830Sdim  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9957243830Sdim                                             /*IsAmbiguous=*/false,
9958243830Sdim                                             /*RParenLoc=*/NoLoc,
9959243830Sdim                                             /*ArgInfo=*/0,
9960243830Sdim                                             /*NumArgs=*/0,
9961243830Sdim                                             /*EllipsisLoc=*/NoLoc,
9962243830Sdim                                             /*RParenLoc=*/NoLoc,
9963243830Sdim                                             /*TypeQuals=*/0,
9964243830Sdim                                             /*RefQualifierIsLvalueRef=*/true,
9965243830Sdim                                             /*RefQualifierLoc=*/NoLoc,
9966243830Sdim                                             /*ConstQualifierLoc=*/NoLoc,
9967243830Sdim                                             /*VolatileQualifierLoc=*/NoLoc,
9968243830Sdim                                             /*MutableLoc=*/NoLoc,
9969243830Sdim                                             EST_None,
9970243830Sdim                                             /*ESpecLoc=*/NoLoc,
9971243830Sdim                                             /*Exceptions=*/0,
9972243830Sdim                                             /*ExceptionRanges=*/0,
9973243830Sdim                                             /*NumExceptions=*/0,
9974243830Sdim                                             /*NoexceptExpr=*/0,
9975243830Sdim                                             Loc, Loc, D),
9976221345Sdim                DS.getAttributes(),
9977193326Sed                SourceLocation());
9978193326Sed  D.SetIdentifier(&II, Loc);
9979193326Sed
9980193326Sed  // Insert this function into translation-unit scope.
9981193326Sed
9982193326Sed  DeclContext *PrevDC = CurContext;
9983193326Sed  CurContext = Context.getTranslationUnitDecl();
9984198092Srdivacky
9985249423Sdim  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9986193326Sed  FD->setImplicit();
9987193326Sed
9988193326Sed  CurContext = PrevDC;
9989193326Sed
9990193326Sed  AddKnownFunctionAttributes(FD);
9991193326Sed
9992193326Sed  return FD;
9993193326Sed}
9994193326Sed
9995193326Sed/// \brief Adds any function attributes that we know a priori based on
9996193326Sed/// the declaration of this function.
9997193326Sed///
9998193326Sed/// These attributes can apply both to implicitly-declared builtins
9999193326Sed/// (like __builtin___printf_chk) or to library-declared functions
10000193326Sed/// like NSLog or printf.
10001224145Sdim///
10002224145Sdim/// We need to check for duplicate attributes both here and where user-written
10003224145Sdim/// attributes are applied to declarations.
10004193326Sedvoid Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10005193326Sed  if (FD->isInvalidDecl())
10006193326Sed    return;
10007193326Sed
10008193326Sed  // If this is a built-in function, map its builtin attributes to
10009193326Sed  // actual attributes.
10010198092Srdivacky  if (unsigned BuiltinID = FD->getBuiltinID()) {
10011193326Sed    // Handle printf-formatting attributes.
10012193326Sed    unsigned FormatIdx;
10013193326Sed    bool HasVAListArg;
10014193326Sed    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10015234353Sdim      if (!FD->getAttr<FormatAttr>()) {
10016234353Sdim        const char *fmt = "printf";
10017234353Sdim        unsigned int NumParams = FD->getNumParams();
10018234353Sdim        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10019234353Sdim            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10020234353Sdim          fmt = "NSString";
10021212904Sdim        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
10022263508Sdim                                               &Context.Idents.get(fmt),
10023263508Sdim                                               FormatIdx+1,
10024203955Srdivacky                                               HasVAListArg ? 0 : FormatIdx+2));
10025234353Sdim      }
10026193326Sed    }
10027212904Sdim    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10028212904Sdim                                             HasVAListArg)) {
10029212904Sdim     if (!FD->getAttr<FormatAttr>())
10030212904Sdim       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
10031263508Sdim                                              &Context.Idents.get("scanf"),
10032263508Sdim                                              FormatIdx+1,
10033212904Sdim                                              HasVAListArg ? 0 : FormatIdx+2));
10034212904Sdim    }
10035193326Sed
10036193326Sed    // Mark const if we don't care about errno and that is the only
10037193326Sed    // thing preventing the function from being const. This allows
10038193326Sed    // IRgen to use LLVM intrinsics for such functions.
10039234353Sdim    if (!getLangOpts().MathErrno &&
10040193326Sed        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10041195341Sed      if (!FD->getAttr<ConstAttr>())
10042212904Sdim        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
10043193326Sed    }
10044198092Srdivacky
10045226633Sdim    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10046226633Sdim        !FD->getAttr<ReturnsTwiceAttr>())
10047226633Sdim      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
10048224145Sdim    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
10049212904Sdim      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
10050224145Sdim    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
10051212904Sdim      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
10052193326Sed  }
10053193326Sed
10054193326Sed  IdentifierInfo *Name = FD->getIdentifier();
10055193326Sed  if (!Name)
10056193326Sed    return;
10057234353Sdim  if ((!getLangOpts().CPlusPlus &&
10058193326Sed       FD->getDeclContext()->isTranslationUnit()) ||
10059193326Sed      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10060198092Srdivacky       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10061193326Sed       LinkageSpecDecl::lang_c)) {
10062193326Sed    // Okay: this could be a libc/libm/Objective-C function we know
10063193326Sed    // about.
10064193326Sed  } else
10065193326Sed    return;
10066193326Sed
10067234353Sdim  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10068198092Srdivacky    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10069198092Srdivacky    // target-specific builtins, perhaps?
10070195341Sed    if (!FD->getAttr<FormatAttr>())
10071212904Sdim      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
10072263508Sdim                                             &Context.Idents.get("printf"), 2,
10073194179Sed                                             Name->isStr("vasprintf") ? 0 : 3));
10074193326Sed  }
10075239462Sdim
10076239462Sdim  if (Name->isStr("__CFStringMakeConstantString")) {
10077239462Sdim    // We already have a __builtin___CFStringMakeConstantString,
10078239462Sdim    // but builds that use -fno-constant-cfstrings don't go through that.
10079239462Sdim    if (!FD->getAttr<FormatArgAttr>())
10080239462Sdim      FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10081239462Sdim  }
10082193326Sed}
10083193326Sed
10084198893SrdivackyTypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10085200583Srdivacky                                    TypeSourceInfo *TInfo) {
10086193326Sed  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10087193326Sed  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10088198092Srdivacky
10089200583Srdivacky  if (!TInfo) {
10090198893Srdivacky    assert(D.isInvalidType() && "no declarator info for valid type");
10091200583Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(T);
10092198893Srdivacky  }
10093198893Srdivacky
10094193326Sed  // Scope manipulation handled by caller.
10095193326Sed  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10096234353Sdim                                           D.getLocStart(),
10097193326Sed                                           D.getIdentifierLoc(),
10098198092Srdivacky                                           D.getIdentifier(),
10099200583Srdivacky                                           TInfo);
10100198092Srdivacky
10101218893Sdim  // Bail out immediately if we have an invalid declaration.
10102218893Sdim  if (D.isInvalidType()) {
10103218893Sdim    NewTD->setInvalidDecl();
10104218893Sdim    return NewTD;
10105218893Sdim  }
10106263508Sdim
10107226633Sdim  if (D.getDeclSpec().isModulePrivateSpecified()) {
10108226633Sdim    if (CurContext->isFunctionOrMethod())
10109226633Sdim      Diag(NewTD->getLocation(), diag::err_module_private_local)
10110226633Sdim        << 2 << NewTD->getDeclName()
10111226633Sdim        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10112226633Sdim        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10113226633Sdim    else
10114226633Sdim      NewTD->setModulePrivate();
10115226633Sdim  }
10116226633Sdim
10117218893Sdim  // C++ [dcl.typedef]p8:
10118218893Sdim  //   If the typedef declaration defines an unnamed class (or
10119218893Sdim  //   enum), the first typedef-name declared by the declaration
10120218893Sdim  //   to be that class type (or enum type) is used to denote the
10121218893Sdim  //   class type (or enum type) for linkage purposes only.
10122218893Sdim  // We need to check whether the type was declared in the declaration.
10123218893Sdim  switch (D.getDeclSpec().getTypeSpecType()) {
10124218893Sdim  case TST_enum:
10125218893Sdim  case TST_struct:
10126243830Sdim  case TST_interface:
10127218893Sdim  case TST_union:
10128218893Sdim  case TST_class: {
10129218893Sdim    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10130218893Sdim
10131218893Sdim    // Do nothing if the tag is not anonymous or already has an
10132218893Sdim    // associated typedef (from an earlier typedef in this decl group).
10133218893Sdim    if (tagFromDeclSpec->getIdentifier()) break;
10134221345Sdim    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10135218893Sdim
10136218893Sdim    // A well-formed anonymous tag must always be a TUK_Definition.
10137218893Sdim    assert(tagFromDeclSpec->isThisDeclarationADefinition());
10138218893Sdim
10139218893Sdim    // The type must match the tag exactly;  no qualifiers allowed.
10140218893Sdim    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10141218893Sdim      break;
10142218893Sdim
10143218893Sdim    // Otherwise, set this is the anon-decl typedef for the tag.
10144221345Sdim    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10145218893Sdim    break;
10146193326Sed  }
10147218893Sdim
10148218893Sdim  default:
10149218893Sdim    break;
10150218893Sdim  }
10151193326Sed
10152193326Sed  return NewTD;
10153193326Sed}
10154193326Sed
10155193326Sed
10156234353Sdim/// \brief Check that this is a valid underlying type for an enum declaration.
10157234353Sdimbool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10158234353Sdim  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10159234353Sdim  QualType T = TI->getType();
10160234353Sdim
10161249423Sdim  if (T->isDependentType())
10162234353Sdim    return false;
10163234353Sdim
10164249423Sdim  if (const BuiltinType *BT = T->getAs<BuiltinType>())
10165249423Sdim    if (BT->isInteger())
10166249423Sdim      return false;
10167249423Sdim
10168234353Sdim  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10169234353Sdim  return true;
10170234353Sdim}
10171234353Sdim
10172234353Sdim/// Check whether this is a valid redeclaration of a previous enumeration.
10173234353Sdim/// \return true if the redeclaration was invalid.
10174234353Sdimbool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10175234353Sdim                                  QualType EnumUnderlyingTy,
10176234353Sdim                                  const EnumDecl *Prev) {
10177234353Sdim  bool IsFixed = !EnumUnderlyingTy.isNull();
10178234353Sdim
10179234353Sdim  if (IsScoped != Prev->isScoped()) {
10180234353Sdim    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10181234353Sdim      << Prev->isScoped();
10182234353Sdim    Diag(Prev->getLocation(), diag::note_previous_use);
10183234353Sdim    return true;
10184234353Sdim  }
10185234353Sdim
10186234353Sdim  if (IsFixed && Prev->isFixed()) {
10187234353Sdim    if (!EnumUnderlyingTy->isDependentType() &&
10188234353Sdim        !Prev->getIntegerType()->isDependentType() &&
10189234353Sdim        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10190234353Sdim                                        Prev->getIntegerType())) {
10191234353Sdim      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10192234353Sdim        << EnumUnderlyingTy << Prev->getIntegerType();
10193234353Sdim      Diag(Prev->getLocation(), diag::note_previous_use);
10194234353Sdim      return true;
10195234353Sdim    }
10196234353Sdim  } else if (IsFixed != Prev->isFixed()) {
10197234353Sdim    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10198234353Sdim      << Prev->isFixed();
10199234353Sdim    Diag(Prev->getLocation(), diag::note_previous_use);
10200234353Sdim    return true;
10201234353Sdim  }
10202234353Sdim
10203234353Sdim  return false;
10204234353Sdim}
10205234353Sdim
10206243830Sdim/// \brief Get diagnostic %select index for tag kind for
10207243830Sdim/// redeclaration diagnostic message.
10208243830Sdim/// WARNING: Indexes apply to particular diagnostics only!
10209243830Sdim///
10210243830Sdim/// \returns diagnostic %select index.
10211243830Sdimstatic unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10212243830Sdim  switch (Tag) {
10213243830Sdim  case TTK_Struct: return 0;
10214243830Sdim  case TTK_Interface: return 1;
10215243830Sdim  case TTK_Class:  return 2;
10216243830Sdim  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10217243830Sdim  }
10218243830Sdim}
10219243830Sdim
10220243830Sdim/// \brief Determine if tag kind is a class-key compatible with
10221243830Sdim/// class for redeclaration (class, struct, or __interface).
10222243830Sdim///
10223243830Sdim/// \returns true iff the tag kind is compatible.
10224243830Sdimstatic bool isClassCompatTagKind(TagTypeKind Tag)
10225243830Sdim{
10226243830Sdim  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10227243830Sdim}
10228243830Sdim
10229193326Sed/// \brief Determine whether a tag with a given kind is acceptable
10230193326Sed/// as a redeclaration of the given tag declaration.
10231193326Sed///
10232193326Sed/// \returns true if the new tag kind is acceptable, false otherwise.
10233198092Srdivackybool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10234223017Sdim                                        TagTypeKind NewTag, bool isDefinition,
10235193326Sed                                        SourceLocation NewTagLoc,
10236193326Sed                                        const IdentifierInfo &Name) {
10237193326Sed  // C++ [dcl.type.elab]p3:
10238193326Sed  //   The class-key or enum keyword present in the
10239193326Sed  //   elaborated-type-specifier shall agree in kind with the
10240208600Srdivacky  //   declaration to which the name in the elaborated-type-specifier
10241193326Sed  //   refers. This rule also applies to the form of
10242193326Sed  //   elaborated-type-specifier that declares a class-name or
10243193326Sed  //   friend class since it can be construed as referring to the
10244193326Sed  //   definition of the class. Thus, in any
10245193326Sed  //   elaborated-type-specifier, the enum keyword shall be used to
10246208600Srdivacky  //   refer to an enumeration (7.2), the union class-key shall be
10247193326Sed  //   used to refer to a union (clause 9), and either the class or
10248193326Sed  //   struct class-key shall be used to refer to a class (clause 9)
10249193326Sed  //   declared using the class or struct class-key.
10250208600Srdivacky  TagTypeKind OldTag = Previous->getTagKind();
10251243830Sdim  if (!isDefinition || !isClassCompatTagKind(NewTag))
10252223017Sdim    if (OldTag == NewTag)
10253223017Sdim      return true;
10254198092Srdivacky
10255243830Sdim  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10256193326Sed    // Warn about the struct/class tag mismatch.
10257193326Sed    bool isTemplate = false;
10258193326Sed    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10259193326Sed      isTemplate = Record->getDescribedClassTemplate();
10260193326Sed
10261223017Sdim    if (!ActiveTemplateInstantiations.empty()) {
10262223017Sdim      // In a template instantiation, do not offer fix-its for tag mismatches
10263223017Sdim      // since they usually mess up the template instead of fixing the problem.
10264223017Sdim      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10265243830Sdim        << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10266243830Sdim        << getRedeclDiagFromTagKind(OldTag);
10267223017Sdim      return true;
10268223017Sdim    }
10269223017Sdim
10270223017Sdim    if (isDefinition) {
10271223017Sdim      // On definitions, check previous tags and issue a fix-it for each
10272223017Sdim      // one that doesn't match the current tag.
10273223017Sdim      if (Previous->getDefinition()) {
10274223017Sdim        // Don't suggest fix-its for redefinitions.
10275223017Sdim        return true;
10276223017Sdim      }
10277223017Sdim
10278223017Sdim      bool previousMismatch = false;
10279223017Sdim      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10280223017Sdim           E(Previous->redecls_end()); I != E; ++I) {
10281223017Sdim        if (I->getTagKind() != NewTag) {
10282223017Sdim          if (!previousMismatch) {
10283223017Sdim            previousMismatch = true;
10284223017Sdim            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10285243830Sdim              << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10286243830Sdim              << getRedeclDiagFromTagKind(I->getTagKind());
10287223017Sdim          }
10288223017Sdim          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10289243830Sdim            << getRedeclDiagFromTagKind(NewTag)
10290223017Sdim            << FixItHint::CreateReplacement(I->getInnerLocStart(),
10291243830Sdim                 TypeWithKeyword::getTagTypeKindName(NewTag));
10292223017Sdim        }
10293223017Sdim      }
10294223017Sdim      return true;
10295223017Sdim    }
10296223017Sdim
10297223017Sdim    // Check for a previous definition.  If current tag and definition
10298223017Sdim    // are same type, do nothing.  If no definition, but disagree with
10299223017Sdim    // with previous tag type, give a warning, but no fix-it.
10300223017Sdim    const TagDecl *Redecl = Previous->getDefinition() ?
10301223017Sdim                            Previous->getDefinition() : Previous;
10302223017Sdim    if (Redecl->getTagKind() == NewTag) {
10303223017Sdim      return true;
10304223017Sdim    }
10305223017Sdim
10306193326Sed    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10307243830Sdim      << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10308243830Sdim      << getRedeclDiagFromTagKind(OldTag);
10309223017Sdim    Diag(Redecl->getLocation(), diag::note_previous_use);
10310223017Sdim
10311223017Sdim    // If there is a previous defintion, suggest a fix-it.
10312223017Sdim    if (Previous->getDefinition()) {
10313223017Sdim        Diag(NewTagLoc, diag::note_struct_class_suggestion)
10314243830Sdim          << getRedeclDiagFromTagKind(Redecl->getTagKind())
10315223017Sdim          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10316243830Sdim               TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10317223017Sdim    }
10318223017Sdim
10319193326Sed    return true;
10320193326Sed  }
10321193326Sed  return false;
10322193326Sed}
10323193326Sed
10324193326Sed/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10325193326Sed/// former case, Name will be non-null.  In the later case, Name will be null.
10326198092Srdivacky/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10327193326Sed/// reference/declaration/definition of a tag.
10328212904SdimDecl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10329218893Sdim                     SourceLocation KWLoc, CXXScopeSpec &SS,
10330218893Sdim                     IdentifierInfo *Name, SourceLocation NameLoc,
10331218893Sdim                     AttributeList *Attr, AccessSpecifier AS,
10332226633Sdim                     SourceLocation ModulePrivateLoc,
10333218893Sdim                     MultiTemplateParamsArg TemplateParameterLists,
10334218893Sdim                     bool &OwnedDecl, bool &IsDependent,
10335234353Sdim                     SourceLocation ScopedEnumKWLoc,
10336234353Sdim                     bool ScopedEnumUsesClassTag,
10337218893Sdim                     TypeResult UnderlyingType) {
10338193326Sed  // If this is not a definition, it must have a name.
10339234353Sdim  IdentifierInfo *OrigName = Name;
10340198092Srdivacky  assert((Name != 0 || TUK == TUK_Definition) &&
10341193326Sed         "Nameless record must be a definition!");
10342218893Sdim  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10343193326Sed
10344193326Sed  OwnedDecl = false;
10345208600Srdivacky  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10346234353Sdim  bool ScopedEnum = ScopedEnumKWLoc.isValid();
10347198092Srdivacky
10348198092Srdivacky  // FIXME: Check explicit specializations more carefully.
10349198092Srdivacky  bool isExplicitSpecialization = false;
10350210299Sed  bool Invalid = false;
10351218893Sdim
10352218893Sdim  // We only need to do this matching if we have template parameters
10353218893Sdim  // or a scope specifier, which also conveniently avoids this work
10354218893Sdim  // for non-C++ cases.
10355221345Sdim  if (TemplateParameterLists.size() > 0 ||
10356218893Sdim      (SS.isNotEmpty() && TUK != TUK_Reference)) {
10357263508Sdim    if (TemplateParameterList *TemplateParams =
10358263508Sdim            MatchTemplateParametersToScopeSpecifier(
10359263508Sdim                KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10360263508Sdim                isExplicitSpecialization, Invalid)) {
10361249423Sdim      if (Kind == TTK_Enum) {
10362249423Sdim        Diag(KWLoc, diag::err_enum_template);
10363249423Sdim        return 0;
10364249423Sdim      }
10365249423Sdim
10366198092Srdivacky      if (TemplateParams->size() > 0) {
10367198092Srdivacky        // This is a declaration or definition of a class template (which may
10368198092Srdivacky        // be a member of another template).
10369221345Sdim
10370210299Sed        if (Invalid)
10371212904Sdim          return 0;
10372221345Sdim
10373198092Srdivacky        OwnedDecl = false;
10374198092Srdivacky        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10375198092Srdivacky                                               SS, Name, NameLoc, Attr,
10376221345Sdim                                               TemplateParams, AS,
10377226633Sdim                                               ModulePrivateLoc,
10378243830Sdim                                               TemplateParameterLists.size()-1,
10379243830Sdim                                               TemplateParameterLists.data());
10380198092Srdivacky        return Result.get();
10381198092Srdivacky      } else {
10382198092Srdivacky        // The "template<>" header is extraneous.
10383198092Srdivacky        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10384208600Srdivacky          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10385198092Srdivacky        isExplicitSpecialization = true;
10386198092Srdivacky      }
10387198092Srdivacky    }
10388193326Sed  }
10389198092Srdivacky
10390218893Sdim  // Figure out the underlying type if this a enum declaration. We need to do
10391218893Sdim  // this early, because it's needed to detect if this is an incompatible
10392218893Sdim  // redeclaration.
10393218893Sdim  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10394218893Sdim
10395218893Sdim  if (Kind == TTK_Enum) {
10396218893Sdim    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10397218893Sdim      // No underlying type explicitly specified, or we failed to parse the
10398218893Sdim      // type, default to int.
10399218893Sdim      EnumUnderlying = Context.IntTy.getTypePtr();
10400218893Sdim    else if (UnderlyingType.get()) {
10401218893Sdim      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10402218893Sdim      // integral type; any cv-qualification is ignored.
10403218893Sdim      TypeSourceInfo *TI = 0;
10404234353Sdim      GetTypeFromParser(UnderlyingType.get(), &TI);
10405218893Sdim      EnumUnderlying = TI;
10406218893Sdim
10407234353Sdim      if (CheckEnumUnderlyingType(TI))
10408218893Sdim        // Recover by falling back to int.
10409218893Sdim        EnumUnderlying = Context.IntTy.getTypePtr();
10410218893Sdim
10411234353Sdim      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10412218893Sdim                                          UPPC_FixedUnderlyingType))
10413218893Sdim        EnumUnderlying = Context.IntTy.getTypePtr();
10414218893Sdim
10415234353Sdim    } else if (getLangOpts().MicrosoftMode)
10416218893Sdim      // Microsoft enums are always of int type.
10417218893Sdim      EnumUnderlying = Context.IntTy.getTypePtr();
10418218893Sdim  }
10419218893Sdim
10420193326Sed  DeclContext *SearchDC = CurContext;
10421193326Sed  DeclContext *DC = CurContext;
10422198092Srdivacky  bool isStdBadAlloc = false;
10423193326Sed
10424204643Srdivacky  RedeclarationKind Redecl = ForRedeclaration;
10425204643Srdivacky  if (TUK == TUK_Friend || TUK == TUK_Reference)
10426204643Srdivacky    Redecl = NotForRedeclaration;
10427198092Srdivacky
10428199512Srdivacky  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10429263508Sdim  bool FriendSawTagOutsideEnclosingNamespace = false;
10430193326Sed  if (Name && SS.isNotEmpty()) {
10431193326Sed    // We have a nested-name tag ('struct foo::bar').
10432193326Sed
10433193326Sed    // Check for invalid 'foo::'.
10434193326Sed    if (SS.isInvalid()) {
10435193326Sed      Name = 0;
10436193326Sed      goto CreateNewDecl;
10437193326Sed    }
10438193326Sed
10439198092Srdivacky    // If this is a friend or a reference to a class in a dependent
10440198092Srdivacky    // context, don't try to make a decl for it.
10441198092Srdivacky    if (TUK == TUK_Friend || TUK == TUK_Reference) {
10442198092Srdivacky      DC = computeDeclContext(SS, false);
10443198092Srdivacky      if (!DC) {
10444198092Srdivacky        IsDependent = true;
10445212904Sdim        return 0;
10446198092Srdivacky      }
10447207619Srdivacky    } else {
10448207619Srdivacky      DC = computeDeclContext(SS, true);
10449207619Srdivacky      if (!DC) {
10450207619Srdivacky        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10451207619Srdivacky          << SS.getRange();
10452212904Sdim        return 0;
10453207619Srdivacky      }
10454198092Srdivacky    }
10455198092Srdivacky
10456207619Srdivacky    if (RequireCompleteDeclContext(SS, DC))
10457212904Sdim      return 0;
10458193326Sed
10459193326Sed    SearchDC = DC;
10460193326Sed    // Look-up name inside 'foo::'.
10461199512Srdivacky    LookupQualifiedName(Previous, DC);
10462193326Sed
10463199512Srdivacky    if (Previous.isAmbiguous())
10464212904Sdim      return 0;
10465198092Srdivacky
10466199512Srdivacky    if (Previous.empty()) {
10467202379Srdivacky      // Name lookup did not find anything. However, if the
10468202379Srdivacky      // nested-name-specifier refers to the current instantiation,
10469202379Srdivacky      // and that current instantiation has any dependent base
10470202379Srdivacky      // classes, we might find something at instantiation time: treat
10471202379Srdivacky      // this as a dependent elaborated-type-specifier.
10472218893Sdim      // But this only makes any sense for reference-like lookups.
10473218893Sdim      if (Previous.wasNotFoundInCurrentInstantiation() &&
10474218893Sdim          (TUK == TUK_Reference || TUK == TUK_Friend)) {
10475202379Srdivacky        IsDependent = true;
10476212904Sdim        return 0;
10477202379Srdivacky      }
10478202379Srdivacky
10479202379Srdivacky      // A tag 'foo::bar' must already exist.
10480206084Srdivacky      Diag(NameLoc, diag::err_not_tag_in_scope)
10481206084Srdivacky        << Kind << Name << DC << SS.getRange();
10482193326Sed      Name = 0;
10483193326Sed      Invalid = true;
10484193326Sed      goto CreateNewDecl;
10485193326Sed    }
10486193326Sed  } else if (Name) {
10487193326Sed    // If this is a named struct, check to see if there was a previous forward
10488193326Sed    // declaration or definition.
10489193326Sed    // FIXME: We're looking into outer scopes here, even when we
10490193326Sed    // shouldn't be. Doing so can result in ambiguities that we
10491193326Sed    // shouldn't be diagnosing.
10492199512Srdivacky    LookupName(Previous, S);
10493193326Sed
10494249423Sdim    // When declaring or defining a tag, ignore ambiguities introduced
10495249423Sdim    // by types using'ed into this scope.
10496223017Sdim    if (Previous.isAmbiguous() &&
10497223017Sdim        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10498223017Sdim      LookupResult::Filter F = Previous.makeFilter();
10499223017Sdim      while (F.hasNext()) {
10500223017Sdim        NamedDecl *ND = F.next();
10501223017Sdim        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10502223017Sdim          F.erase();
10503223017Sdim      }
10504223017Sdim      F.done();
10505223017Sdim    }
10506249423Sdim
10507249423Sdim    // C++11 [namespace.memdef]p3:
10508249423Sdim    //   If the name in a friend declaration is neither qualified nor
10509249423Sdim    //   a template-id and the declaration is a function or an
10510249423Sdim    //   elaborated-type-specifier, the lookup to determine whether
10511249423Sdim    //   the entity has been previously declared shall not consider
10512249423Sdim    //   any scopes outside the innermost enclosing namespace.
10513249423Sdim    //
10514249423Sdim    // Does it matter that this should be by scope instead of by
10515249423Sdim    // semantic context?
10516249423Sdim    if (!Previous.empty() && TUK == TUK_Friend) {
10517249423Sdim      DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10518249423Sdim      LookupResult::Filter F = Previous.makeFilter();
10519249423Sdim      while (F.hasNext()) {
10520249423Sdim        NamedDecl *ND = F.next();
10521249423Sdim        DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10522263508Sdim        if (DC->isFileContext() &&
10523263508Sdim            !EnclosingNS->Encloses(ND->getDeclContext())) {
10524249423Sdim          F.erase();
10525263508Sdim          FriendSawTagOutsideEnclosingNamespace = true;
10526263508Sdim        }
10527249423Sdim      }
10528249423Sdim      F.done();
10529249423Sdim    }
10530223017Sdim
10531199512Srdivacky    // Note:  there used to be some attempt at recovery here.
10532199512Srdivacky    if (Previous.isAmbiguous())
10533212904Sdim      return 0;
10534199512Srdivacky
10535234353Sdim    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10536193326Sed      // FIXME: This makes sure that we ignore the contexts associated
10537193326Sed      // with C structs, unions, and enums when looking for a matching
10538193326Sed      // tag declaration or definition. See the similar lookup tweak
10539193326Sed      // in Sema::LookupName; is there a better way to deal with this?
10540193326Sed      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10541193326Sed        SearchDC = SearchDC->getParent();
10542193326Sed    }
10543218893Sdim  } else if (S->isFunctionPrototypeScope()) {
10544218893Sdim    // If this is an enum declaration in function prototype scope, set its
10545218893Sdim    // initial context to the translation unit.
10546234353Sdim    // FIXME: [citation needed]
10547218893Sdim    SearchDC = Context.getTranslationUnitDecl();
10548193326Sed  }
10549193326Sed
10550199512Srdivacky  if (Previous.isSingleResult() &&
10551199512Srdivacky      Previous.getFoundDecl()->isTemplateParameter()) {
10552193326Sed    // Maybe we will complain about the shadowed template parameter.
10553199512Srdivacky    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10554193326Sed    // Just pretend that we didn't see the previous declaration.
10555199512Srdivacky    Previous.clear();
10556193326Sed  }
10557193326Sed
10558234353Sdim  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10559212904Sdim      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10560198092Srdivacky    // This is a declaration of or a reference to "std::bad_alloc".
10561198092Srdivacky    isStdBadAlloc = true;
10562198092Srdivacky
10563199512Srdivacky    if (Previous.empty() && StdBadAlloc) {
10564198092Srdivacky      // std::bad_alloc has been implicitly declared (but made invisible to
10565198092Srdivacky      // name lookup). Fill in this implicit declaration as the previous
10566198092Srdivacky      // declaration, so that the declarations get chained appropriately.
10567212904Sdim      Previous.addDecl(getStdBadAlloc());
10568198092Srdivacky    }
10569198092Srdivacky  }
10570199512Srdivacky
10571206084Srdivacky  // If we didn't find a previous declaration, and this is a reference
10572206084Srdivacky  // (or friend reference), move to the correct scope.  In C++, we
10573206084Srdivacky  // also need to do a redeclaration lookup there, just in case
10574206084Srdivacky  // there's a shadow friend decl.
10575206084Srdivacky  if (Name && Previous.empty() &&
10576206084Srdivacky      (TUK == TUK_Reference || TUK == TUK_Friend)) {
10577206084Srdivacky    if (Invalid) goto CreateNewDecl;
10578206084Srdivacky    assert(SS.isEmpty());
10579206084Srdivacky
10580206084Srdivacky    if (TUK == TUK_Reference) {
10581206084Srdivacky      // C++ [basic.scope.pdecl]p5:
10582206084Srdivacky      //   -- for an elaborated-type-specifier of the form
10583206084Srdivacky      //
10584206084Srdivacky      //          class-key identifier
10585206084Srdivacky      //
10586206084Srdivacky      //      if the elaborated-type-specifier is used in the
10587206084Srdivacky      //      decl-specifier-seq or parameter-declaration-clause of a
10588206084Srdivacky      //      function defined in namespace scope, the identifier is
10589206084Srdivacky      //      declared as a class-name in the namespace that contains
10590206084Srdivacky      //      the declaration; otherwise, except as a friend
10591206084Srdivacky      //      declaration, the identifier is declared in the smallest
10592206084Srdivacky      //      non-class, non-function-prototype scope that contains the
10593206084Srdivacky      //      declaration.
10594206084Srdivacky      //
10595206084Srdivacky      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10596206084Srdivacky      // C structs and unions.
10597206084Srdivacky      //
10598206084Srdivacky      // It is an error in C++ to declare (rather than define) an enum
10599206084Srdivacky      // type, including via an elaborated type specifier.  We'll
10600206084Srdivacky      // diagnose that later; for now, declare the enum in the same
10601206084Srdivacky      // scope as we would have picked for any other tag type.
10602206084Srdivacky      //
10603206084Srdivacky      // GNU C also supports this behavior as part of its incomplete
10604206084Srdivacky      // enum types extension, while GNU C++ does not.
10605206084Srdivacky      //
10606206084Srdivacky      // Find the context where we'll be declaring the tag.
10607206084Srdivacky      // FIXME: We would like to maintain the current DeclContext as the
10608206084Srdivacky      // lexical context,
10609234353Sdim      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10610206084Srdivacky        SearchDC = SearchDC->getParent();
10611206084Srdivacky
10612206084Srdivacky      // Find the scope where we'll be declaring the tag.
10613206084Srdivacky      while (S->isClassScope() ||
10614234353Sdim             (getLangOpts().CPlusPlus &&
10615206084Srdivacky              S->isFunctionPrototypeScope()) ||
10616206084Srdivacky             ((S->getFlags() & Scope::DeclScope) == 0) ||
10617263508Sdim             (S->getEntity() && S->getEntity()->isTransparentContext()))
10618206084Srdivacky        S = S->getParent();
10619206084Srdivacky    } else {
10620206084Srdivacky      assert(TUK == TUK_Friend);
10621206084Srdivacky      // C++ [namespace.memdef]p3:
10622206084Srdivacky      //   If a friend declaration in a non-local class first declares a
10623206084Srdivacky      //   class or function, the friend class or function is a member of
10624206084Srdivacky      //   the innermost enclosing namespace.
10625206084Srdivacky      SearchDC = SearchDC->getEnclosingNamespaceContext();
10626206084Srdivacky    }
10627206084Srdivacky
10628207619Srdivacky    // In C++, we need to do a redeclaration lookup to properly
10629207619Srdivacky    // diagnose some problems.
10630234353Sdim    if (getLangOpts().CPlusPlus) {
10631206084Srdivacky      Previous.setRedeclarationKind(ForRedeclaration);
10632206084Srdivacky      LookupQualifiedName(Previous, SearchDC);
10633206084Srdivacky    }
10634206084Srdivacky  }
10635206084Srdivacky
10636199512Srdivacky  if (!Previous.empty()) {
10637207619Srdivacky    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
10638207619Srdivacky
10639207619Srdivacky    // It's okay to have a tag decl in the same scope as a typedef
10640207619Srdivacky    // which hides a tag decl in the same scope.  Finding this
10641207619Srdivacky    // insanity with a redeclaration lookup can only actually happen
10642207619Srdivacky    // in C++.
10643207619Srdivacky    //
10644207619Srdivacky    // This is also okay for elaborated-type-specifiers, which is
10645207619Srdivacky    // technically forbidden by the current standard but which is
10646207619Srdivacky    // okay according to the likely resolution of an open issue;
10647207619Srdivacky    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10648234353Sdim    if (getLangOpts().CPlusPlus) {
10649221345Sdim      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10650207619Srdivacky        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10651207619Srdivacky          TagDecl *Tag = TT->getDecl();
10652207619Srdivacky          if (Tag->getDeclName() == Name &&
10653212904Sdim              Tag->getDeclContext()->getRedeclContext()
10654212904Sdim                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
10655207619Srdivacky            PrevDecl = Tag;
10656207619Srdivacky            Previous.clear();
10657207619Srdivacky            Previous.addDecl(Tag);
10658212904Sdim            Previous.resolveKind();
10659207619Srdivacky          }
10660207619Srdivacky        }
10661207619Srdivacky      }
10662207619Srdivacky    }
10663207619Srdivacky
10664193326Sed    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10665193326Sed      // If this is a use of a previous tag, or if the tag is already declared
10666193326Sed      // in the same scope (so that the definition/declaration completes or
10667193326Sed      // rementions the tag), reuse the decl.
10668198092Srdivacky      if (TUK == TUK_Reference || TUK == TUK_Friend ||
10669221345Sdim          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
10670193326Sed        // Make sure that this wasn't declared as an enum and now used as a
10671193326Sed        // struct or something similar.
10672223017Sdim        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10673223017Sdim                                          TUK == TUK_Definition, KWLoc,
10674223017Sdim                                          *Name)) {
10675198092Srdivacky          bool SafeToContinue
10676208600Srdivacky            = (PrevTagDecl->getTagKind() != TTK_Enum &&
10677208600Srdivacky               Kind != TTK_Enum);
10678193326Sed          if (SafeToContinue)
10679198092Srdivacky            Diag(KWLoc, diag::err_use_with_wrong_tag)
10680193326Sed              << Name
10681206084Srdivacky              << FixItHint::CreateReplacement(SourceRange(KWLoc),
10682206084Srdivacky                                              PrevTagDecl->getKindName());
10683193326Sed          else
10684193326Sed            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10685199512Srdivacky          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10686193326Sed
10687198092Srdivacky          if (SafeToContinue)
10688193326Sed            Kind = PrevTagDecl->getTagKind();
10689193326Sed          else {
10690193326Sed            // Recover by making this an anonymous redefinition.
10691193326Sed            Name = 0;
10692199512Srdivacky            Previous.clear();
10693193326Sed            Invalid = true;
10694193326Sed          }
10695193326Sed        }
10696193326Sed
10697218893Sdim        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10698218893Sdim          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10699218893Sdim
10700234353Sdim          // If this is an elaborated-type-specifier for a scoped enumeration,
10701234353Sdim          // the 'class' keyword is not necessary and not permitted.
10702234353Sdim          if (TUK == TUK_Reference || TUK == TUK_Friend) {
10703234353Sdim            if (ScopedEnum)
10704234353Sdim              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10705234353Sdim                << PrevEnum->isScoped()
10706234353Sdim                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10707218893Sdim            return PrevTagDecl;
10708218893Sdim          }
10709218893Sdim
10710234353Sdim          QualType EnumUnderlyingTy;
10711234353Sdim          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10712234353Sdim            EnumUnderlyingTy = TI->getType();
10713234353Sdim          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10714234353Sdim            EnumUnderlyingTy = QualType(T, 0);
10715234353Sdim
10716234353Sdim          // All conflicts with previous declarations are recovered by
10717234353Sdim          // returning the previous declaration, unless this is a definition,
10718234353Sdim          // in which case we want the caller to bail out.
10719234353Sdim          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10720234353Sdim                                     ScopedEnum, EnumUnderlyingTy, PrevEnum))
10721234353Sdim            return TUK == TUK_Declaration ? PrevTagDecl : 0;
10722218893Sdim        }
10723218893Sdim
10724263508Sdim        // C++11 [class.mem]p1:
10725263508Sdim        //   A member shall not be declared twice in the member-specification,
10726263508Sdim        //   except that a nested class or member class template can be declared
10727263508Sdim        //   and then later defined.
10728263508Sdim        if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10729263508Sdim            S->isDeclScope(PrevDecl)) {
10730263508Sdim          Diag(NameLoc, diag::ext_member_redeclared);
10731263508Sdim          Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10732263508Sdim        }
10733263508Sdim
10734193326Sed        if (!Invalid) {
10735193326Sed          // If this is a use, just return the declaration we found.
10736193326Sed
10737193326Sed          // FIXME: In the future, return a variant or some other clue
10738193326Sed          // for the consumer of this Decl to know it doesn't own it.
10739193326Sed          // For our current ASTs this shouldn't be a problem, but will
10740193326Sed          // need to be changed with DeclGroups.
10741223017Sdim          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10742234353Sdim               getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10743212904Sdim            return PrevTagDecl;
10744193326Sed
10745193326Sed          // Diagnose attempts to redefine a tag.
10746198092Srdivacky          if (TUK == TUK_Definition) {
10747203955Srdivacky            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10748198092Srdivacky              // If we're defining a specialization and the previous definition
10749198092Srdivacky              // is from an implicit instantiation, don't emit an error
10750198092Srdivacky              // here; we'll catch this in the general case below.
10751234353Sdim              bool IsExplicitSpecializationAfterInstantiation = false;
10752234353Sdim              if (isExplicitSpecialization) {
10753234353Sdim                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10754234353Sdim                  IsExplicitSpecializationAfterInstantiation =
10755234353Sdim                    RD->getTemplateSpecializationKind() !=
10756234353Sdim                    TSK_ExplicitSpecialization;
10757234353Sdim                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10758234353Sdim                  IsExplicitSpecializationAfterInstantiation =
10759234353Sdim                    ED->getTemplateSpecializationKind() !=
10760234353Sdim                    TSK_ExplicitSpecialization;
10761234353Sdim              }
10762234353Sdim
10763234353Sdim              if (!IsExplicitSpecializationAfterInstantiation) {
10764234353Sdim                // A redeclaration in function prototype scope in C isn't
10765234353Sdim                // visible elsewhere, so merely issue a warning.
10766234353Sdim                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10767234353Sdim                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10768234353Sdim                else
10769234353Sdim                  Diag(NameLoc, diag::err_redefinition) << Name;
10770198092Srdivacky                Diag(Def->getLocation(), diag::note_previous_definition);
10771198092Srdivacky                // If this is a redefinition, recover by making this
10772198092Srdivacky                // struct be anonymous, which will make any later
10773198092Srdivacky                // references get the previous definition.
10774198092Srdivacky                Name = 0;
10775199512Srdivacky                Previous.clear();
10776198092Srdivacky                Invalid = true;
10777198092Srdivacky              }
10778193326Sed            } else {
10779193326Sed              // If the type is currently being defined, complain
10780193326Sed              // about a nested redefinition.
10781218893Sdim              const TagType *Tag
10782218893Sdim                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10783193326Sed              if (Tag->isBeingDefined()) {
10784193326Sed                Diag(NameLoc, diag::err_nested_redefinition) << Name;
10785198092Srdivacky                Diag(PrevTagDecl->getLocation(),
10786193326Sed                     diag::note_previous_definition);
10787193326Sed                Name = 0;
10788199512Srdivacky                Previous.clear();
10789193326Sed                Invalid = true;
10790193326Sed              }
10791193326Sed            }
10792193326Sed
10793193326Sed            // Okay, this is definition of a previously declared or referenced
10794193326Sed            // tag PrevDecl. We're going to create a new Decl for it.
10795193326Sed          }
10796193326Sed        }
10797193326Sed        // If we get here we have (another) forward declaration or we
10798198092Srdivacky        // have a definition.  Just create a new decl.
10799198092Srdivacky
10800193326Sed      } else {
10801193326Sed        // If we get here, this is a definition of a new tag type in a nested
10802198092Srdivacky        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10803193326Sed        // new decl/type.  We set PrevDecl to NULL so that the entities
10804193326Sed        // have distinct types.
10805199512Srdivacky        Previous.clear();
10806193326Sed      }
10807193326Sed      // If we get here, we're going to create a new Decl. If PrevDecl
10808193326Sed      // is non-NULL, it's a definition of the tag declared by
10809193326Sed      // PrevDecl. If it's NULL, we have a new definition.
10810207619Srdivacky
10811207619Srdivacky
10812207619Srdivacky    // Otherwise, PrevDecl is not a tag, but was found with tag
10813207619Srdivacky    // lookup.  This is only actually possible in C++, where a few
10814207619Srdivacky    // things like templates still live in the tag namespace.
10815193326Sed    } else {
10816207619Srdivacky      // Use a better diagnostic if an elaborated-type-specifier
10817207619Srdivacky      // found the wrong kind of type on the first
10818207619Srdivacky      // (non-redeclaration) lookup.
10819207619Srdivacky      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10820207619Srdivacky          !Previous.isForRedeclaration()) {
10821207619Srdivacky        unsigned Kind = 0;
10822207619Srdivacky        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10823221345Sdim        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10824221345Sdim        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10825207619Srdivacky        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10826207619Srdivacky        Diag(PrevDecl->getLocation(), diag::note_declared_at);
10827207619Srdivacky        Invalid = true;
10828207619Srdivacky
10829207619Srdivacky      // Otherwise, only diagnose if the declaration is in scope.
10830221345Sdim      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10831221345Sdim                                isExplicitSpecialization)) {
10832207619Srdivacky        // do nothing
10833207619Srdivacky
10834207619Srdivacky      // Diagnose implicit declarations introduced by elaborated types.
10835207619Srdivacky      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10836207619Srdivacky        unsigned Kind = 0;
10837207619Srdivacky        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10838221345Sdim        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10839221345Sdim        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10840207619Srdivacky        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10841207619Srdivacky        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10842207619Srdivacky        Invalid = true;
10843207619Srdivacky
10844207619Srdivacky      // Otherwise it's a declaration.  Call out a particularly common
10845207619Srdivacky      // case here.
10846221345Sdim      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10847221345Sdim        unsigned Kind = 0;
10848221345Sdim        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10849207619Srdivacky        Diag(NameLoc, diag::err_tag_definition_of_typedef)
10850221345Sdim          << Name << Kind << TND->getUnderlyingType();
10851207619Srdivacky        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10852207619Srdivacky        Invalid = true;
10853207619Srdivacky
10854207619Srdivacky      // Otherwise, diagnose.
10855207619Srdivacky      } else {
10856207619Srdivacky        // The tag name clashes with something else in the target scope,
10857207619Srdivacky        // issue an error and recover by making this tag be anonymous.
10858193326Sed        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10859193326Sed        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10860193326Sed        Name = 0;
10861193326Sed        Invalid = true;
10862193326Sed      }
10863207619Srdivacky
10864207619Srdivacky      // The existing declaration isn't relevant to us; we're in a
10865207619Srdivacky      // new scope, so clear out the previous declaration.
10866207619Srdivacky      Previous.clear();
10867193326Sed    }
10868193326Sed  }
10869193326Sed
10870193326SedCreateNewDecl:
10871198092Srdivacky
10872199512Srdivacky  TagDecl *PrevDecl = 0;
10873199512Srdivacky  if (Previous.isSingleResult())
10874199512Srdivacky    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10875199512Srdivacky
10876193326Sed  // If there is an identifier, use the location of the identifier as the
10877193326Sed  // location of the decl, otherwise use the location of the struct/union
10878193326Sed  // keyword.
10879193326Sed  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10880198092Srdivacky
10881193326Sed  // Otherwise, create a new declaration. If there is a previous
10882193326Sed  // declaration of the same entity, the two will be linked via
10883193326Sed  // PrevDecl.
10884193326Sed  TagDecl *New;
10885193326Sed
10886218893Sdim  bool IsForwardReference = false;
10887208600Srdivacky  if (Kind == TTK_Enum) {
10888193326Sed    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10889193326Sed    // enum X { A, B, C } D;    D should chain to X.
10890221345Sdim    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10891218893Sdim                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10892218893Sdim                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10893193326Sed    // If this is an undefined enum, warn.
10894210299Sed    if (TUK != TUK_Definition && !Invalid) {
10895210299Sed      TagDecl *Def;
10896249423Sdim      if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10897249423Sdim          cast<EnumDecl>(New)->isFixed()) {
10898218893Sdim        // C++0x: 7.2p2: opaque-enum-declaration.
10899218893Sdim        // Conflicts are diagnosed above. Do nothing.
10900218893Sdim      }
10901218893Sdim      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10902210299Sed        Diag(Loc, diag::ext_forward_ref_enum_def)
10903210299Sed          << New;
10904210299Sed        Diag(Def->getLocation(), diag::note_previous_definition);
10905210299Sed      } else {
10906218893Sdim        unsigned DiagID = diag::ext_forward_ref_enum;
10907234353Sdim        if (getLangOpts().MicrosoftMode)
10908218893Sdim          DiagID = diag::ext_ms_forward_ref_enum;
10909234353Sdim        else if (getLangOpts().CPlusPlus)
10910218893Sdim          DiagID = diag::err_forward_ref_enum;
10911218893Sdim        Diag(Loc, DiagID);
10912218893Sdim
10913218893Sdim        // If this is a forward-declared reference to an enumeration, make a
10914218893Sdim        // note of it; we won't actually be introducing the declaration into
10915218893Sdim        // the declaration context.
10916218893Sdim        if (TUK == TUK_Reference)
10917218893Sdim          IsForwardReference = true;
10918210299Sed      }
10919193326Sed    }
10920218893Sdim
10921218893Sdim    if (EnumUnderlying) {
10922218893Sdim      EnumDecl *ED = cast<EnumDecl>(New);
10923218893Sdim      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10924218893Sdim        ED->setIntegerTypeSourceInfo(TI);
10925218893Sdim      else
10926218893Sdim        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10927218893Sdim      ED->setPromotionType(ED->getIntegerType());
10928218893Sdim    }
10929218893Sdim
10930193326Sed  } else {
10931193326Sed    // struct/union/class
10932193326Sed
10933193326Sed    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10934193326Sed    // struct X { int A; } D;    D should chain to X.
10935234353Sdim    if (getLangOpts().CPlusPlus) {
10936193326Sed      // FIXME: Look for a way to use RecordDecl for simple structs.
10937221345Sdim      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10938193326Sed                                  cast_or_null<CXXRecordDecl>(PrevDecl));
10939221345Sdim
10940212904Sdim      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10941198092Srdivacky        StdBadAlloc = cast<CXXRecordDecl>(New);
10942198092Srdivacky    } else
10943221345Sdim      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10944193326Sed                               cast_or_null<RecordDecl>(PrevDecl));
10945193326Sed  }
10946193326Sed
10947205219Srdivacky  // Maybe add qualifier info.
10948205219Srdivacky  if (SS.isNotEmpty()) {
10949208600Srdivacky    if (SS.isSet()) {
10950234353Sdim      // If this is either a declaration or a definition, check the
10951234353Sdim      // nested-name-specifier against the current context. We don't do this
10952234353Sdim      // for explicit specializations, because they have similar checking
10953234353Sdim      // (with more specific diagnostics) in the call to
10954234353Sdim      // CheckMemberSpecialization, below.
10955234353Sdim      if (!isExplicitSpecialization &&
10956234353Sdim          (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10957234353Sdim          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10958234353Sdim        Invalid = true;
10959234353Sdim
10960219077Sdim      New->setQualifierInfo(SS.getWithLocInContext(Context));
10961221345Sdim      if (TemplateParameterLists.size() > 0) {
10962210299Sed        New->setTemplateParameterListsInfo(Context,
10963221345Sdim                                           TemplateParameterLists.size(),
10964243830Sdim                                           TemplateParameterLists.data());
10965210299Sed      }
10966208600Srdivacky    }
10967208600Srdivacky    else
10968208600Srdivacky      Invalid = true;
10969205219Srdivacky  }
10970205219Srdivacky
10971208600Srdivacky  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10972208600Srdivacky    // Add alignment attributes if necessary; these attributes are checked when
10973208600Srdivacky    // the ASTContext lays out the structure.
10974193326Sed    //
10975193326Sed    // It is important for implementing the correct semantics that this
10976193326Sed    // happen here (in act on tag decl). The #pragma pack stack is
10977193326Sed    // maintained as a result of parser callbacks which can occur at
10978193326Sed    // many points during the parsing of a struct declaration (because
10979193326Sed    // the #pragma tokens are effectively skipped over during the
10980193326Sed    // parsing of the struct).
10981239462Sdim    if (TUK == TUK_Definition) {
10982239462Sdim      AddAlignmentAttributesForRecord(RD);
10983239462Sdim      AddMsStructLayoutForRecord(RD);
10984239462Sdim    }
10985193326Sed  }
10986193326Sed
10987234353Sdim  if (ModulePrivateLoc.isValid()) {
10988226633Sdim    if (isExplicitSpecialization)
10989226633Sdim      Diag(New->getLocation(), diag::err_module_private_specialization)
10990226633Sdim        << 2
10991226633Sdim        << FixItHint::CreateRemoval(ModulePrivateLoc);
10992226633Sdim    // __module_private__ does not apply to local classes. However, we only
10993226633Sdim    // diagnose this as an error when the declaration specifiers are
10994226633Sdim    // freestanding. Here, we just ignore the __module_private__.
10995226633Sdim    else if (!SearchDC->isFunctionOrMethod())
10996226633Sdim      New->setModulePrivate();
10997226633Sdim  }
10998226633Sdim
10999198092Srdivacky  // If this is a specialization of a member class (of a class template),
11000198092Srdivacky  // check the specialization.
11001199512Srdivacky  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11002198092Srdivacky    Invalid = true;
11003234353Sdim
11004193326Sed  if (Invalid)
11005193326Sed    New->setInvalidDecl();
11006193326Sed
11007193326Sed  if (Attr)
11008194613Sed    ProcessDeclAttributeList(S, New, Attr);
11009193326Sed
11010193326Sed  // If we're declaring or defining a tag in function prototype scope
11011193326Sed  // in C, note that this type can only be used within the function.
11012234353Sdim  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
11013193326Sed    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11014193326Sed
11015193326Sed  // Set the lexical context. If the tag has a C++ scope specifier, the
11016193326Sed  // lexical context will be different from the semantic context.
11017193326Sed  New->setLexicalDeclContext(CurContext);
11018193326Sed
11019198092Srdivacky  // Mark this as a friend decl if applicable.
11020223017Sdim  // In Microsoft mode, a friend declaration also acts as a forward
11021223017Sdim  // declaration so we always pass true to setObjectOfFriendDecl to make
11022223017Sdim  // the tag name visible.
11023198092Srdivacky  if (TUK == TUK_Friend)
11024263508Sdim    New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11025234353Sdim                               getLangOpts().MicrosoftExt);
11026198092Srdivacky
11027193326Sed  // Set the access specifier.
11028206084Srdivacky  if (!Invalid && SearchDC->isRecord())
11029193326Sed    SetMemberAccessSpecifier(New, PrevDecl, AS);
11030193326Sed
11031198092Srdivacky  if (TUK == TUK_Definition)
11032193326Sed    New->startDefinition();
11033198092Srdivacky
11034193326Sed  // If this has an identifier, add it to the scope stack.
11035198092Srdivacky  if (TUK == TUK_Friend) {
11036198092Srdivacky    // We might be replacing an existing declaration in the lookup tables;
11037198092Srdivacky    // if so, borrow its access specifier.
11038198092Srdivacky    if (PrevDecl)
11039198092Srdivacky      New->setAccess(PrevDecl->getAccess());
11040198092Srdivacky
11041212904Sdim    DeclContext *DC = New->getDeclContext()->getRedeclContext();
11042234353Sdim    DC->makeDeclVisibleInContext(New);
11043206084Srdivacky    if (Name) // can be null along some error paths
11044198092Srdivacky      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11045198092Srdivacky        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11046198092Srdivacky  } else if (Name) {
11047193326Sed    S = getNonFieldDeclScope(S);
11048218893Sdim    PushOnScopeChains(New, S, !IsForwardReference);
11049218893Sdim    if (IsForwardReference)
11050234353Sdim      SearchDC->makeDeclVisibleInContext(New);
11051218893Sdim
11052193326Sed  } else {
11053195341Sed    CurContext->addDecl(New);
11054193326Sed  }
11055193326Sed
11056198092Srdivacky  // If this is the C FILE type, notify the AST context.
11057198092Srdivacky  if (IdentifierInfo *II = New->getIdentifier())
11058198092Srdivacky    if (!New->isInvalidDecl() &&
11059212904Sdim        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11060198092Srdivacky        II->isStr("FILE"))
11061198092Srdivacky      Context.setFILEDecl(New);
11062198092Srdivacky
11063234353Sdim  // If we were in function prototype scope (and not in C++ mode), add this
11064234353Sdim  // tag to the list of decls to inject into the function definition scope.
11065234353Sdim  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
11066234353Sdim      InFunctionDeclarator && Name)
11067234353Sdim    DeclsInPrototypeScope.push_back(New);
11068234353Sdim
11069239462Sdim  if (PrevDecl)
11070239462Sdim    mergeDeclAttributes(New, PrevDecl);
11071239462Sdim
11072239462Sdim  // If there's a #pragma GCC visibility in scope, set the visibility of this
11073239462Sdim  // record.
11074239462Sdim  AddPushedVisibilityAttribute(New);
11075239462Sdim
11076193326Sed  OwnedDecl = true;
11077249423Sdim  // In C++, don't return an invalid declaration. We can't recover well from
11078249423Sdim  // the cases where we make the type anonymous.
11079249423Sdim  return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11080193326Sed}
11081193326Sed
11082212904Sdimvoid Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11083193326Sed  AdjustDeclIfTemplate(TagD);
11084212904Sdim  TagDecl *Tag = cast<TagDecl>(TagD);
11085207619Srdivacky
11086193326Sed  // Enter the tag context.
11087193326Sed  PushDeclContext(S, Tag);
11088239462Sdim
11089239462Sdim  ActOnDocumentableDecl(TagD);
11090239462Sdim
11091239462Sdim  // If there's a #pragma GCC visibility in scope, set the visibility of this
11092239462Sdim  // record.
11093239462Sdim  AddPushedVisibilityAttribute(Tag);
11094201361Srdivacky}
11095193326Sed
11096226633SdimDecl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11097226633Sdim  assert(isa<ObjCContainerDecl>(IDecl) &&
11098226633Sdim         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11099226633Sdim  DeclContext *OCD = cast<DeclContext>(IDecl);
11100226633Sdim  assert(getContainingDC(OCD) == CurContext &&
11101226633Sdim      "The next DeclContext should be lexically contained in the current one.");
11102226633Sdim  CurContext = OCD;
11103226633Sdim  return IDecl;
11104226633Sdim}
11105226633Sdim
11106212904Sdimvoid Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11107221345Sdim                                           SourceLocation FinalLoc,
11108263508Sdim                                           bool IsFinalSpelledSealed,
11109201361Srdivacky                                           SourceLocation LBraceLoc) {
11110201361Srdivacky  AdjustDeclIfTemplate(TagD);
11111212904Sdim  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11112193326Sed
11113201361Srdivacky  FieldCollector->StartClass();
11114201361Srdivacky
11115201361Srdivacky  if (!Record->getIdentifier())
11116201361Srdivacky    return;
11117201361Srdivacky
11118221345Sdim  if (FinalLoc.isValid())
11119263508Sdim    Record->addAttr(new (Context)
11120263508Sdim                    FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11121263508Sdim
11122201361Srdivacky  // C++ [class]p2:
11123201361Srdivacky  //   [...] The class-name is also inserted into the scope of the
11124201361Srdivacky  //   class itself; this is known as the injected-class-name. For
11125201361Srdivacky  //   purposes of access checking, the injected-class-name is treated
11126201361Srdivacky  //   as if it were a public member name.
11127201361Srdivacky  CXXRecordDecl *InjectedClassName
11128221345Sdim    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11129221345Sdim                            Record->getLocStart(), Record->getLocation(),
11130201361Srdivacky                            Record->getIdentifier(),
11131218893Sdim                            /*PrevDecl=*/0,
11132218893Sdim                            /*DelayTypeCreation=*/true);
11133218893Sdim  Context.getTypeDeclType(InjectedClassName, Record);
11134201361Srdivacky  InjectedClassName->setImplicit();
11135201361Srdivacky  InjectedClassName->setAccess(AS_public);
11136201361Srdivacky  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11137201361Srdivacky      InjectedClassName->setDescribedClassTemplate(Template);
11138201361Srdivacky  PushOnScopeChains(InjectedClassName, S);
11139201361Srdivacky  assert(InjectedClassName->isInjectedClassName() &&
11140201361Srdivacky         "Broken injected-class-name");
11141193326Sed}
11142193326Sed
11143212904Sdimvoid Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11144198092Srdivacky                                    SourceLocation RBraceLoc) {
11145193326Sed  AdjustDeclIfTemplate(TagD);
11146212904Sdim  TagDecl *Tag = cast<TagDecl>(TagD);
11147198092Srdivacky  Tag->setRBraceLoc(RBraceLoc);
11148193326Sed
11149234353Sdim  // Make sure we "complete" the definition even it is invalid.
11150234353Sdim  if (Tag->isBeingDefined()) {
11151234353Sdim    assert(Tag->isInvalidDecl() && "We should already have completed it");
11152234353Sdim    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11153234353Sdim      RD->completeDefinition();
11154234353Sdim  }
11155234353Sdim
11156193326Sed  if (isa<CXXRecordDecl>(Tag))
11157193326Sed    FieldCollector->FinishClass();
11158193326Sed
11159193326Sed  // Exit this scope of this tag's definition.
11160193326Sed  PopDeclContext();
11161249423Sdim
11162249423Sdim  if (getCurLexicalContext()->isObjCContainer() &&
11163249423Sdim      Tag->getDeclContext()->isFileContext())
11164249423Sdim    Tag->setTopLevelDeclInObjCContainer();
11165249423Sdim
11166193326Sed  // Notify the consumer that we've defined a tag.
11167252587Sdim  if (!Tag->isInvalidDecl())
11168252587Sdim    Consumer.HandleTagDeclDefinition(Tag);
11169193326Sed}
11170193326Sed
11171226633Sdimvoid Sema::ActOnObjCContainerFinishDefinition() {
11172226633Sdim  // Exit this scope of this interface definition.
11173226633Sdim  PopDeclContext();
11174226633Sdim}
11175226633Sdim
11176234353Sdimvoid Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11177234353Sdim  assert(DC == CurContext && "Mismatch of container contexts");
11178234353Sdim  OriginalLexicalContext = DC;
11179226633Sdim  ActOnObjCContainerFinishDefinition();
11180226633Sdim}
11181226633Sdim
11182234353Sdimvoid Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11183234353Sdim  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11184226633Sdim  OriginalLexicalContext = 0;
11185226633Sdim}
11186226633Sdim
11187212904Sdimvoid Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11188205408Srdivacky  AdjustDeclIfTemplate(TagD);
11189212904Sdim  TagDecl *Tag = cast<TagDecl>(TagD);
11190205408Srdivacky  Tag->setInvalidDecl();
11191205408Srdivacky
11192234353Sdim  // Make sure we "complete" the definition even it is invalid.
11193234353Sdim  if (Tag->isBeingDefined()) {
11194234353Sdim    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11195234353Sdim      RD->completeDefinition();
11196234353Sdim  }
11197234353Sdim
11198205408Srdivacky  // We're undoing ActOnTagStartDefinition here, not
11199205408Srdivacky  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11200205408Srdivacky  // the FieldCollector.
11201205408Srdivacky
11202205408Srdivacky  PopDeclContext();
11203205408Srdivacky}
11204205408Srdivacky
11205193326Sed// Note that FieldName may be null for anonymous bitfields.
11206234353SdimExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11207234353Sdim                                IdentifierInfo *FieldName,
11208263508Sdim                                QualType FieldTy, bool IsMsStruct,
11209263508Sdim                                Expr *BitWidth, bool *ZeroWidth) {
11210198092Srdivacky  // Default to true; that shouldn't confuse checks for emptiness
11211198092Srdivacky  if (ZeroWidth)
11212198092Srdivacky    *ZeroWidth = true;
11213198092Srdivacky
11214193326Sed  // C99 6.7.2.1p4 - verify the field type.
11215193326Sed  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11216210299Sed  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11217193326Sed    // Handle incomplete types with specific error.
11218193326Sed    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11219234353Sdim      return ExprError();
11220193326Sed    if (FieldName)
11221193326Sed      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11222193326Sed        << FieldName << FieldTy << BitWidth->getSourceRange();
11223193326Sed    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11224193326Sed      << FieldTy << BitWidth->getSourceRange();
11225218893Sdim  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11226218893Sdim                                             UPPC_BitFieldWidth))
11227234353Sdim    return ExprError();
11228193326Sed
11229193326Sed  // If the bit-width is type- or value-dependent, don't try to check
11230193326Sed  // it now.
11231193326Sed  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11232234353Sdim    return Owned(BitWidth);
11233193326Sed
11234193326Sed  llvm::APSInt Value;
11235234353Sdim  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11236234353Sdim  if (ICE.isInvalid())
11237234353Sdim    return ICE;
11238234353Sdim  BitWidth = ICE.take();
11239193326Sed
11240198092Srdivacky  if (Value != 0 && ZeroWidth)
11241198092Srdivacky    *ZeroWidth = false;
11242198092Srdivacky
11243193326Sed  // Zero-width bitfield is ok for anonymous field.
11244193326Sed  if (Value == 0 && FieldName)
11245193326Sed    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11246198092Srdivacky
11247193326Sed  if (Value.isSigned() && Value.isNegative()) {
11248193326Sed    if (FieldName)
11249198092Srdivacky      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11250193326Sed               << FieldName << Value.toString(10);
11251193326Sed    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11252193326Sed      << Value.toString(10);
11253193326Sed  }
11254193326Sed
11255193326Sed  if (!FieldTy->isDependentType()) {
11256193326Sed    uint64_t TypeSize = Context.getTypeSize(FieldTy);
11257193326Sed    if (Value.getZExtValue() > TypeSize) {
11258263508Sdim      if (!getLangOpts().CPlusPlus || IsMsStruct) {
11259207619Srdivacky        if (FieldName)
11260207619Srdivacky          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11261207619Srdivacky            << FieldName << (unsigned)Value.getZExtValue()
11262207619Srdivacky            << (unsigned)TypeSize;
11263207619Srdivacky
11264207619Srdivacky        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11265207619Srdivacky          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11266207619Srdivacky      }
11267207619Srdivacky
11268193326Sed      if (FieldName)
11269207619Srdivacky        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11270207619Srdivacky          << FieldName << (unsigned)Value.getZExtValue()
11271207619Srdivacky          << (unsigned)TypeSize;
11272207619Srdivacky      else
11273207619Srdivacky        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11274207619Srdivacky          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11275193326Sed    }
11276193326Sed  }
11277193326Sed
11278234353Sdim  return Owned(BitWidth);
11279193326Sed}
11280193326Sed
11281223017Sdim/// ActOnField - Each field of a C struct/union is passed into this in order
11282193326Sed/// to create a FieldDecl object for it.
11283223017SdimDecl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11284226633Sdim                       Declarator &D, Expr *BitfieldWidth) {
11285212904Sdim  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11286193326Sed                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11287239462Sdim                               /*InitStyle=*/ICIS_NoInit, AS_public);
11288212904Sdim  return Res;
11289193326Sed}
11290193326Sed
11291193326Sed/// HandleField - Analyze a field of a C struct or a C++ data member.
11292193326Sed///
11293193326SedFieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11294193326Sed                             SourceLocation DeclStart,
11295239462Sdim                             Declarator &D, Expr *BitWidth,
11296239462Sdim                             InClassInitStyle InitStyle,
11297193326Sed                             AccessSpecifier AS) {
11298193326Sed  IdentifierInfo *II = D.getIdentifier();
11299193326Sed  SourceLocation Loc = DeclStart;
11300193326Sed  if (II) Loc = D.getIdentifierLoc();
11301198092Srdivacky
11302210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11303210299Sed  QualType T = TInfo->getType();
11304234353Sdim  if (getLangOpts().CPlusPlus) {
11305193326Sed    CheckExtraCXXDefaultArguments(D);
11306193326Sed
11307218893Sdim    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11308218893Sdim                                        UPPC_DataMemberType)) {
11309218893Sdim      D.setInvalidType();
11310218893Sdim      T = Context.IntTy;
11311218893Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11312218893Sdim    }
11313218893Sdim  }
11314218893Sdim
11315249423Sdim  // TR 18037 does not allow fields to be declared with address spaces.
11316249423Sdim  if (T.getQualifiers().hasAddressSpace()) {
11317249423Sdim    Diag(Loc, diag::err_field_with_address_space);
11318249423Sdim    D.setInvalidType();
11319249423Sdim  }
11320193326Sed
11321249423Sdim  // OpenCL 1.2 spec, s6.9 r:
11322249423Sdim  // The event type cannot be used to declare a structure or union field.
11323249423Sdim  if (LangOpts.OpenCL && T->isEventT()) {
11324249423Sdim    Diag(Loc, diag::err_event_t_struct_field);
11325249423Sdim    D.setInvalidType();
11326249423Sdim  }
11327249423Sdim
11328249423Sdim  DiagnoseFunctionSpecifiers(D.getDeclSpec());
11329249423Sdim
11330251662Sdim  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11331251662Sdim    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11332251662Sdim         diag::err_invalid_thread)
11333251662Sdim      << DeclSpec::getSpecifierName(TSCS);
11334249423Sdim
11335212904Sdim  // Check to see if this name was declared as a member previously
11336234353Sdim  NamedDecl *PrevDecl = 0;
11337212904Sdim  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11338212904Sdim  LookupName(Previous, S);
11339234353Sdim  switch (Previous.getResultKind()) {
11340234353Sdim    case LookupResult::Found:
11341234353Sdim    case LookupResult::FoundUnresolvedValue:
11342234353Sdim      PrevDecl = Previous.getAsSingle<NamedDecl>();
11343234353Sdim      break;
11344234353Sdim
11345234353Sdim    case LookupResult::FoundOverloaded:
11346234353Sdim      PrevDecl = Previous.getRepresentativeDecl();
11347234353Sdim      break;
11348234353Sdim
11349234353Sdim    case LookupResult::NotFound:
11350234353Sdim    case LookupResult::NotFoundInCurrentInstantiation:
11351234353Sdim    case LookupResult::Ambiguous:
11352234353Sdim      break;
11353234353Sdim  }
11354234353Sdim  Previous.suppressDiagnostics();
11355193326Sed
11356194613Sed  if (PrevDecl && PrevDecl->isTemplateParameter()) {
11357194613Sed    // Maybe we will complain about the shadowed template parameter.
11358194613Sed    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11359194613Sed    // Just pretend that we didn't see the previous declaration.
11360194613Sed    PrevDecl = 0;
11361194613Sed  }
11362194613Sed
11363193326Sed  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11364193326Sed    PrevDecl = 0;
11365193326Sed
11366198092Srdivacky  bool Mutable
11367198092Srdivacky    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11368234353Sdim  SourceLocation TSSL = D.getLocStart();
11369198092Srdivacky  FieldDecl *NewFD
11370239462Sdim    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11371223017Sdim                     TSSL, AS, PrevDecl, &D);
11372206084Srdivacky
11373206084Srdivacky  if (NewFD->isInvalidDecl())
11374206084Srdivacky    Record->setInvalidDecl();
11375206084Srdivacky
11376226633Sdim  if (D.getDeclSpec().isModulePrivateSpecified())
11377226633Sdim    NewFD->setModulePrivate();
11378226633Sdim
11379193326Sed  if (NewFD->isInvalidDecl() && PrevDecl) {
11380193326Sed    // Don't introduce NewFD into scope; there's already something
11381193326Sed    // with the same name in the same scope.
11382193326Sed  } else if (II) {
11383193326Sed    PushOnScopeChains(NewFD, S);
11384193326Sed  } else
11385195341Sed    Record->addDecl(NewFD);
11386193326Sed
11387193326Sed  return NewFD;
11388193326Sed}
11389193326Sed
11390193326Sed/// \brief Build a new FieldDecl and check its well-formedness.
11391193326Sed///
11392193326Sed/// This routine builds a new FieldDecl given the fields name, type,
11393193326Sed/// record, etc. \p PrevDecl should refer to any previous declaration
11394193326Sed/// with the same name and in the same scope as the field to be
11395193326Sed/// created.
11396193326Sed///
11397193326Sed/// \returns a new FieldDecl.
11398193326Sed///
11399198092Srdivacky/// \todo The Declarator argument is a hack. It will be removed once
11400198092SrdivackyFieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11401200583Srdivacky                                TypeSourceInfo *TInfo,
11402193326Sed                                RecordDecl *Record, SourceLocation Loc,
11403239462Sdim                                bool Mutable, Expr *BitWidth,
11404239462Sdim                                InClassInitStyle InitStyle,
11405198092Srdivacky                                SourceLocation TSSL,
11406193326Sed                                AccessSpecifier AS, NamedDecl *PrevDecl,
11407193326Sed                                Declarator *D) {
11408193326Sed  IdentifierInfo *II = Name.getAsIdentifierInfo();
11409193326Sed  bool InvalidDecl = false;
11410193326Sed  if (D) InvalidDecl = D->isInvalidType();
11411193326Sed
11412193326Sed  // If we receive a broken type, recover by assuming 'int' and
11413193326Sed  // marking this declaration as invalid.
11414193326Sed  if (T.isNull()) {
11415193326Sed    InvalidDecl = true;
11416193326Sed    T = Context.IntTy;
11417193326Sed  }
11418193326Sed
11419200583Srdivacky  QualType EltTy = Context.getBaseElementType(T);
11420234353Sdim  if (!EltTy->isDependentType()) {
11421234353Sdim    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11422234353Sdim      // Fields of incomplete type force their record to be invalid.
11423234353Sdim      Record->setInvalidDecl();
11424234353Sdim      InvalidDecl = true;
11425234353Sdim    } else {
11426234353Sdim      NamedDecl *Def;
11427234353Sdim      EltTy->isIncompleteType(&Def);
11428234353Sdim      if (Def && Def->isInvalidDecl()) {
11429234353Sdim        Record->setInvalidDecl();
11430234353Sdim        InvalidDecl = true;
11431234353Sdim      }
11432234353Sdim    }
11433212904Sdim  }
11434200583Srdivacky
11435249423Sdim  // OpenCL v1.2 s6.9.c: bitfields are not supported.
11436249423Sdim  if (BitWidth && getLangOpts().OpenCL) {
11437249423Sdim    Diag(Loc, diag::err_opencl_bitfields);
11438249423Sdim    InvalidDecl = true;
11439249423Sdim  }
11440249423Sdim
11441193326Sed  // C99 6.7.2.1p8: A member of a structure or union may have any type other
11442193326Sed  // than a variably modified type.
11443200583Srdivacky  if (!InvalidDecl && T->isVariablyModifiedType()) {
11444193326Sed    bool SizeIsNegative;
11445212904Sdim    llvm::APSInt Oversized;
11446243830Sdim
11447243830Sdim    TypeSourceInfo *FixedTInfo =
11448243830Sdim      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11449243830Sdim                                                    SizeIsNegative,
11450243830Sdim                                                    Oversized);
11451243830Sdim    if (FixedTInfo) {
11452193326Sed      Diag(Loc, diag::warn_illegal_constant_array_size);
11453243830Sdim      TInfo = FixedTInfo;
11454243830Sdim      T = FixedTInfo->getType();
11455193326Sed    } else {
11456193326Sed      if (SizeIsNegative)
11457193326Sed        Diag(Loc, diag::err_typecheck_negative_array_size);
11458212904Sdim      else if (Oversized.getBoolValue())
11459212904Sdim        Diag(Loc, diag::err_array_too_large)
11460212904Sdim          << Oversized.toString(10);
11461193326Sed      else
11462193326Sed        Diag(Loc, diag::err_typecheck_field_variable_size);
11463193326Sed      InvalidDecl = true;
11464193326Sed    }
11465193326Sed  }
11466198092Srdivacky
11467193326Sed  // Fields can not have abstract class types
11468200583Srdivacky  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11469200583Srdivacky                                             diag::err_abstract_type_in_decl,
11470200583Srdivacky                                             AbstractFieldType))
11471193326Sed    InvalidDecl = true;
11472198092Srdivacky
11473198092Srdivacky  bool ZeroWidth = false;
11474193326Sed  // If this is declared as a bit-field, check the bit-field.
11475234353Sdim  if (!InvalidDecl && BitWidth) {
11476263508Sdim    BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11477263508Sdim                              &ZeroWidth).take();
11478234353Sdim    if (!BitWidth) {
11479234353Sdim      InvalidDecl = true;
11480234353Sdim      BitWidth = 0;
11481234353Sdim      ZeroWidth = false;
11482234353Sdim    }
11483193326Sed  }
11484198092Srdivacky
11485210299Sed  // Check that 'mutable' is consistent with the type of the declaration.
11486210299Sed  if (!InvalidDecl && Mutable) {
11487210299Sed    unsigned DiagID = 0;
11488210299Sed    if (T->isReferenceType())
11489210299Sed      DiagID = diag::err_mutable_reference;
11490210299Sed    else if (T.isConstQualified())
11491210299Sed      DiagID = diag::err_mutable_const;
11492210299Sed
11493210299Sed    if (DiagID) {
11494210299Sed      SourceLocation ErrLoc = Loc;
11495210299Sed      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11496210299Sed        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11497210299Sed      Diag(ErrLoc, DiagID);
11498210299Sed      Mutable = false;
11499210299Sed      InvalidDecl = true;
11500210299Sed    }
11501210299Sed  }
11502210299Sed
11503221345Sdim  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11504239462Sdim                                       BitWidth, Mutable, InitStyle);
11505193326Sed  if (InvalidDecl)
11506193326Sed    NewFD->setInvalidDecl();
11507193326Sed
11508193326Sed  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11509193326Sed    Diag(Loc, diag::err_duplicate_member) << II;
11510193326Sed    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11511193326Sed    NewFD->setInvalidDecl();
11512193326Sed  }
11513193326Sed
11514234353Sdim  if (!InvalidDecl && getLangOpts().CPlusPlus) {
11515218893Sdim    if (Record->isUnion()) {
11516218893Sdim      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11517218893Sdim        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11518218893Sdim        if (RDecl->getDefinition()) {
11519218893Sdim          // C++ [class.union]p1: An object of a class with a non-trivial
11520218893Sdim          // constructor, a non-trivial copy constructor, a non-trivial
11521218893Sdim          // destructor, or a non-trivial copy assignment operator
11522218893Sdim          // cannot be a member of a union, nor can an array of such
11523218893Sdim          // objects.
11524234353Sdim          if (CheckNontrivialField(NewFD))
11525218893Sdim            NewFD->setInvalidDecl();
11526218893Sdim        }
11527218893Sdim      }
11528198092Srdivacky
11529218893Sdim      // C++ [class.union]p1: If a union contains a member of reference type,
11530263508Sdim      // the program is ill-formed, except when compiling with MSVC extensions
11531263508Sdim      // enabled.
11532218893Sdim      if (EltTy->isReferenceType()) {
11533263508Sdim        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11534263508Sdim                                    diag::ext_union_member_of_reference_type :
11535263508Sdim                                    diag::err_union_member_of_reference_type)
11536218893Sdim          << NewFD->getDeclName() << EltTy;
11537263508Sdim        if (!getLangOpts().MicrosoftExt)
11538263508Sdim          NewFD->setInvalidDecl();
11539198092Srdivacky      }
11540198092Srdivacky    }
11541198092Srdivacky  }
11542198092Srdivacky
11543193326Sed  // FIXME: We need to pass in the attributes given an AST
11544193326Sed  // representation, not a parser representation.
11545249423Sdim  if (D) {
11546251662Sdim    // FIXME: The current scope is almost... but not entirely... correct here.
11547251662Sdim    ProcessDeclAttributes(getCurScope(), NewFD, *D);
11548193326Sed
11549249423Sdim    if (NewFD->hasAttrs())
11550249423Sdim      CheckAlignasUnderalignment(NewFD);
11551249423Sdim  }
11552249423Sdim
11553224145Sdim  // In auto-retain/release, infer strong retension for fields of
11554224145Sdim  // retainable type.
11555234353Sdim  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11556224145Sdim    NewFD->setInvalidDecl();
11557224145Sdim
11558193326Sed  if (T.isObjCGCWeak())
11559193326Sed    Diag(Loc, diag::warn_attribute_weak_on_field);
11560193326Sed
11561193326Sed  NewFD->setAccess(AS);
11562193326Sed  return NewFD;
11563193326Sed}
11564193326Sed
11565212904Sdimbool Sema::CheckNontrivialField(FieldDecl *FD) {
11566212904Sdim  assert(FD);
11567234353Sdim  assert(getLangOpts().CPlusPlus && "valid check only for C++");
11568212904Sdim
11569263508Sdim  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11570263508Sdim    return false;
11571212904Sdim
11572212904Sdim  QualType EltTy = Context.getBaseElementType(FD->getType());
11573212904Sdim  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11574249423Sdim    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11575212904Sdim    if (RDecl->getDefinition()) {
11576212904Sdim      // We check for copy constructors before constructors
11577212904Sdim      // because otherwise we'll never get complaints about
11578212904Sdim      // copy constructors.
11579212904Sdim
11580212904Sdim      CXXSpecialMember member = CXXInvalid;
11581249423Sdim      // We're required to check for any non-trivial constructors. Since the
11582249423Sdim      // implicit default constructor is suppressed if there are any
11583249423Sdim      // user-declared constructors, we just need to check that there is a
11584249423Sdim      // trivial default constructor and a trivial copy constructor. (We don't
11585249423Sdim      // worry about move constructors here, since this is a C++98 check.)
11586249423Sdim      if (RDecl->hasNonTrivialCopyConstructor())
11587212904Sdim        member = CXXCopyConstructor;
11588223017Sdim      else if (!RDecl->hasTrivialDefaultConstructor())
11589223017Sdim        member = CXXDefaultConstructor;
11590249423Sdim      else if (RDecl->hasNonTrivialCopyAssignment())
11591212904Sdim        member = CXXCopyAssignment;
11592249423Sdim      else if (RDecl->hasNonTrivialDestructor())
11593212904Sdim        member = CXXDestructor;
11594212904Sdim
11595212904Sdim      if (member != CXXInvalid) {
11596249423Sdim        if (!getLangOpts().CPlusPlus11 &&
11597234353Sdim            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11598224145Sdim          // Objective-C++ ARC: it is an error to have a non-trivial field of
11599224145Sdim          // a union. However, system headers in Objective-C programs
11600224145Sdim          // occasionally have Objective-C lifetime objects within unions,
11601224145Sdim          // and rather than cause the program to fail, we make those
11602224145Sdim          // members unavailable.
11603224145Sdim          SourceLocation Loc = FD->getLocation();
11604224145Sdim          if (getSourceManager().isInSystemHeader(Loc)) {
11605224145Sdim            if (!FD->hasAttr<UnavailableAttr>())
11606224145Sdim              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
11607224145Sdim                                  "this system field has retaining ownership"));
11608224145Sdim            return false;
11609224145Sdim          }
11610224145Sdim        }
11611234353Sdim
11612249423Sdim        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11613234353Sdim               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11614234353Sdim               diag::err_illegal_union_or_anon_struct_member)
11615234353Sdim          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11616249423Sdim        DiagnoseNontrivial(RDecl, member);
11617249423Sdim        return !getLangOpts().CPlusPlus11;
11618212904Sdim      }
11619212904Sdim    }
11620212904Sdim  }
11621249423Sdim
11622212904Sdim  return false;
11623212904Sdim}
11624212904Sdim
11625198092Srdivacky/// TranslateIvarVisibility - Translate visibility from a token ID to an
11626193326Sed///  AST enum value.
11627193326Sedstatic ObjCIvarDecl::AccessControl
11628193326SedTranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11629193326Sed  switch (ivarVisibility) {
11630226633Sdim  default: llvm_unreachable("Unknown visitibility kind");
11631193326Sed  case tok::objc_private: return ObjCIvarDecl::Private;
11632193326Sed  case tok::objc_public: return ObjCIvarDecl::Public;
11633193326Sed  case tok::objc_protected: return ObjCIvarDecl::Protected;
11634193326Sed  case tok::objc_package: return ObjCIvarDecl::Package;
11635193326Sed  }
11636193326Sed}
11637193326Sed
11638198092Srdivacky/// ActOnIvar - Each ivar field of an objective-c class is passed into this
11639193326Sed/// in order to create an IvarDecl object for it.
11640212904SdimDecl *Sema::ActOnIvar(Scope *S,
11641198092Srdivacky                                SourceLocation DeclStart,
11642226633Sdim                                Declarator &D, Expr *BitfieldWidth,
11643193326Sed                                tok::ObjCKeywordKind Visibility) {
11644198092Srdivacky
11645193326Sed  IdentifierInfo *II = D.getIdentifier();
11646193326Sed  Expr *BitWidth = (Expr*)BitfieldWidth;
11647193326Sed  SourceLocation Loc = DeclStart;
11648193326Sed  if (II) Loc = D.getIdentifierLoc();
11649198092Srdivacky
11650193326Sed  // FIXME: Unnamed fields can be handled in various different ways, for
11651193326Sed  // example, unnamed unions inject all members into the struct namespace!
11652198092Srdivacky
11653210299Sed  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11654210299Sed  QualType T = TInfo->getType();
11655198092Srdivacky
11656193326Sed  if (BitWidth) {
11657193326Sed    // 6.7.2.1p3, 6.7.2.1p4
11658263508Sdim    BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11659234353Sdim    if (!BitWidth)
11660193326Sed      D.setInvalidType();
11661193326Sed  } else {
11662193326Sed    // Not a bitfield.
11663198092Srdivacky
11664193326Sed    // validate II.
11665198092Srdivacky
11666193326Sed  }
11667207619Srdivacky  if (T->isReferenceType()) {
11668207619Srdivacky    Diag(Loc, diag::err_ivar_reference_type);
11669207619Srdivacky    D.setInvalidType();
11670207619Srdivacky  }
11671193326Sed  // C99 6.7.2.1p8: A member of a structure or union may have any type other
11672193326Sed  // than a variably modified type.
11673207619Srdivacky  else if (T->isVariablyModifiedType()) {
11674193326Sed    Diag(Loc, diag::err_typecheck_ivar_variable_size);
11675193326Sed    D.setInvalidType();
11676193326Sed  }
11677198092Srdivacky
11678193326Sed  // Get the visibility (access control) for this ivar.
11679198092Srdivacky  ObjCIvarDecl::AccessControl ac =
11680193326Sed    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11681193326Sed                                        : ObjCIvarDecl::None;
11682193576Sed  // Must set ivar's DeclContext to its enclosing interface.
11683226633Sdim  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11684234353Sdim  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11685234353Sdim    return 0;
11686206125Srdivacky  ObjCContainerDecl *EnclosingContext;
11687198092Srdivacky  if (ObjCImplementationDecl *IMPDecl =
11688193576Sed      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11689239462Sdim    if (LangOpts.ObjCRuntime.isFragile()) {
11690193576Sed    // Case of ivar declared in an implementation. Context is that of its class.
11691212904Sdim      EnclosingContext = IMPDecl->getClassInterface();
11692212904Sdim      assert(EnclosingContext && "Implementation has no class interface!");
11693212904Sdim    }
11694212904Sdim    else
11695212904Sdim      EnclosingContext = EnclosingDecl;
11696207619Srdivacky  } else {
11697207619Srdivacky    if (ObjCCategoryDecl *CDecl =
11698207619Srdivacky        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11699239462Sdim      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11700207619Srdivacky        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11701212904Sdim        return 0;
11702207619Srdivacky      }
11703207619Srdivacky    }
11704206125Srdivacky    EnclosingContext = EnclosingDecl;
11705207619Srdivacky  }
11706198092Srdivacky
11707193326Sed  // Construct the decl.
11708221345Sdim  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11709221345Sdim                                             DeclStart, Loc, II, T,
11710200583Srdivacky                                             TInfo, ac, (Expr *)BitfieldWidth);
11711198092Srdivacky
11712193326Sed  if (II) {
11713207619Srdivacky    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11714199482Srdivacky                                           ForRedeclaration);
11715193576Sed    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11716193326Sed        && !isa<TagDecl>(PrevDecl)) {
11717193326Sed      Diag(Loc, diag::err_duplicate_member) << II;
11718193326Sed      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11719193326Sed      NewID->setInvalidDecl();
11720193326Sed    }
11721193326Sed  }
11722193326Sed
11723193326Sed  // Process attributes attached to the ivar.
11724194613Sed  ProcessDeclAttributes(S, NewID, D);
11725198092Srdivacky
11726193326Sed  if (D.isInvalidType())
11727193326Sed    NewID->setInvalidDecl();
11728193326Sed
11729224145Sdim  // In ARC, infer 'retaining' for ivars of retainable type.
11730234353Sdim  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11731224145Sdim    NewID->setInvalidDecl();
11732224145Sdim
11733226633Sdim  if (D.getDeclSpec().isModulePrivateSpecified())
11734226633Sdim    NewID->setModulePrivate();
11735226633Sdim
11736193326Sed  if (II) {
11737193326Sed    // FIXME: When interfaces are DeclContexts, we'll need to add
11738193326Sed    // these to the interface.
11739212904Sdim    S->AddDecl(NewID);
11740193326Sed    IdResolver.AddDecl(NewID);
11741193326Sed  }
11742239462Sdim
11743239462Sdim  if (LangOpts.ObjCRuntime.isNonFragile() &&
11744239462Sdim      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11745239462Sdim    Diag(Loc, diag::warn_ivars_in_interface);
11746239462Sdim
11747212904Sdim  return NewID;
11748193326Sed}
11749193326Sed
11750212904Sdim/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11751249423Sdim/// class and class extensions. For every class \@interface and class
11752249423Sdim/// extension \@interface, if the last ivar is a bitfield of any type,
11753212904Sdim/// then add an implicit `char :0` ivar to the end of that interface.
11754226633Sdimvoid Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11755226633Sdim                             SmallVectorImpl<Decl *> &AllIvarDecls) {
11756239462Sdim  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11757212904Sdim    return;
11758212904Sdim
11759212904Sdim  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11760212904Sdim  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11761212904Sdim
11762226633Sdim  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11763212904Sdim    return;
11764226633Sdim  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11765212904Sdim  if (!ID) {
11766226633Sdim    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11767212904Sdim      if (!CD->IsClassExtension())
11768212904Sdim        return;
11769212904Sdim    }
11770212904Sdim    // No need to add this to end of @implementation.
11771212904Sdim    else
11772212904Sdim      return;
11773212904Sdim  }
11774212904Sdim  // All conditions are met. Add a new bitfield to the tail end of ivars.
11775226633Sdim  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11776226633Sdim  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11777212904Sdim
11778226633Sdim  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11779221345Sdim                              DeclLoc, DeclLoc, 0,
11780212904Sdim                              Context.CharTy,
11781226633Sdim                              Context.getTrivialTypeSourceInfo(Context.CharTy,
11782226633Sdim                                                               DeclLoc),
11783212904Sdim                              ObjCIvarDecl::Private, BW,
11784212904Sdim                              true);
11785212904Sdim  AllIvarDecls.push_back(Ivar);
11786212904Sdim}
11787212904Sdim
11788263508Sdimvoid Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11789263508Sdim                       ArrayRef<Decl *> Fields, SourceLocation LBrac,
11790263508Sdim                       SourceLocation RBrac, AttributeList *Attr) {
11791193326Sed  assert(EnclosingDecl && "missing record or interface decl");
11792198092Srdivacky
11793239462Sdim  // If this is an Objective-C @implementation or category and we have
11794239462Sdim  // new fields here we should reset the layout of the interface since
11795239462Sdim  // it will now change.
11796239462Sdim  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11797239462Sdim    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11798239462Sdim    switch (DC->getKind()) {
11799239462Sdim    default: break;
11800239462Sdim    case Decl::ObjCCategory:
11801239462Sdim      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11802239462Sdim      break;
11803239462Sdim    case Decl::ObjCImplementation:
11804239462Sdim      Context.
11805239462Sdim        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11806239462Sdim      break;
11807239462Sdim    }
11808239462Sdim  }
11809239462Sdim
11810234353Sdim  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11811234353Sdim
11812234353Sdim  // Start counting up the number of named members; make sure to include
11813234353Sdim  // members of anonymous structs and unions in the total.
11814234353Sdim  unsigned NumNamedMembers = 0;
11815234353Sdim  if (Record) {
11816234353Sdim    for (RecordDecl::decl_iterator i = Record->decls_begin(),
11817234353Sdim                                   e = Record->decls_end(); i != e; i++) {
11818234353Sdim      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11819234353Sdim        if (IFD->getDeclName())
11820234353Sdim          ++NumNamedMembers;
11821234353Sdim    }
11822234353Sdim  }
11823234353Sdim
11824193326Sed  // Verify that all the fields are okay.
11825226633Sdim  SmallVector<FieldDecl*, 32> RecFields;
11826193326Sed
11827224145Sdim  bool ARCErrReported = false;
11828263508Sdim  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11829226633Sdim       i != end; ++i) {
11830226633Sdim    FieldDecl *FD = cast<FieldDecl>(*i);
11831198092Srdivacky
11832193326Sed    // Get the type for the field.
11833218893Sdim    const Type *FDTy = FD->getType().getTypePtr();
11834193326Sed
11835193326Sed    if (!FD->isAnonymousStructOrUnion()) {
11836193326Sed      // Remember all fields written by the user.
11837193326Sed      RecFields.push_back(FD);
11838193326Sed    }
11839198092Srdivacky
11840193326Sed    // If the field is already invalid for some reason, don't emit more
11841193326Sed    // diagnostics about it.
11842200583Srdivacky    if (FD->isInvalidDecl()) {
11843200583Srdivacky      EnclosingDecl->setInvalidDecl();
11844193326Sed      continue;
11845200583Srdivacky    }
11846198092Srdivacky
11847193326Sed    // C99 6.7.2.1p2:
11848193326Sed    //   A structure or union shall not contain a member with
11849193326Sed    //   incomplete or function type (hence, a structure shall not
11850193326Sed    //   contain an instance of itself, but may contain a pointer to
11851193326Sed    //   an instance of itself), except that the last member of a
11852193326Sed    //   structure with more than one named member may have incomplete
11853193326Sed    //   array type; such a structure (and any union containing,
11854193326Sed    //   possibly recursively, a member that is such a structure)
11855193326Sed    //   shall not be a member of a structure or an element of an
11856193326Sed    //   array.
11857193326Sed    if (FDTy->isFunctionType()) {
11858193326Sed      // Field declared as a function.
11859193326Sed      Diag(FD->getLocation(), diag::err_field_declared_as_function)
11860193326Sed        << FD->getDeclName();
11861193326Sed      FD->setInvalidDecl();
11862193326Sed      EnclosingDecl->setInvalidDecl();
11863193326Sed      continue;
11864218893Sdim    } else if (FDTy->isIncompleteArrayType() && Record &&
11865226633Sdim               ((i + 1 == Fields.end() && !Record->isUnion()) ||
11866234353Sdim                ((getLangOpts().MicrosoftExt ||
11867234353Sdim                  getLangOpts().CPlusPlus) &&
11868226633Sdim                 (i + 1 == Fields.end() || Record->isUnion())))) {
11869193326Sed      // Flexible array member.
11870221345Sdim      // Microsoft and g++ is more permissive regarding flexible array.
11871218893Sdim      // It will accept flexible array in union and also
11872218893Sdim      // as the sole element of a struct/class.
11873263508Sdim      unsigned DiagID = 0;
11874263508Sdim      if (Record->isUnion())
11875263508Sdim        DiagID = getLangOpts().MicrosoftExt
11876263508Sdim                     ? diag::ext_flexible_array_union_ms
11877263508Sdim                     : getLangOpts().CPlusPlus
11878263508Sdim                           ? diag::ext_flexible_array_union_gnu
11879263508Sdim                           : diag::err_flexible_array_union;
11880263508Sdim      else if (Fields.size() == 1)
11881263508Sdim        DiagID = getLangOpts().MicrosoftExt
11882263508Sdim                     ? diag::ext_flexible_array_empty_aggregate_ms
11883263508Sdim                     : getLangOpts().CPlusPlus
11884263508Sdim                           ? diag::ext_flexible_array_empty_aggregate_gnu
11885263508Sdim                           : NumNamedMembers < 1
11886263508Sdim                                 ? diag::err_flexible_array_empty_aggregate
11887263508Sdim                                 : 0;
11888263508Sdim
11889263508Sdim      if (DiagID)
11890263508Sdim        Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11891263508Sdim                                        << Record->getTagKind();
11892263508Sdim      // While the layout of types that contain virtual bases is not specified
11893263508Sdim      // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11894263508Sdim      // virtual bases after the derived members.  This would make a flexible
11895263508Sdim      // array member declared at the end of an object not adjacent to the end
11896263508Sdim      // of the type.
11897263508Sdim      if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11898263508Sdim        if (RD->getNumVBases() != 0)
11899263508Sdim          Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11900218893Sdim            << FD->getDeclName() << Record->getTagKind();
11901263508Sdim      if (!getLangOpts().C99)
11902234353Sdim        Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11903234353Sdim          << FD->getDeclName() << Record->getTagKind();
11904263508Sdim
11905208600Srdivacky      if (!FD->getType()->isDependentType() &&
11906224145Sdim          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
11907208600Srdivacky        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
11908208600Srdivacky          << FD->getDeclName() << FD->getType();
11909208600Srdivacky        FD->setInvalidDecl();
11910208600Srdivacky        EnclosingDecl->setInvalidDecl();
11911208600Srdivacky        continue;
11912208600Srdivacky      }
11913193326Sed      // Okay, we have a legal flexible array member at the end of the struct.
11914193326Sed      if (Record)
11915193326Sed        Record->setHasFlexibleArrayMember(true);
11916193326Sed    } else if (!FDTy->isDependentType() &&
11917198092Srdivacky               RequireCompleteType(FD->getLocation(), FD->getType(),
11918193326Sed                                   diag::err_field_incomplete)) {
11919193326Sed      // Incomplete type
11920193326Sed      FD->setInvalidDecl();
11921193326Sed      EnclosingDecl->setInvalidDecl();
11922193326Sed      continue;
11923198092Srdivacky    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11924193326Sed      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11925193326Sed        // If this is a member of a union, then entire union becomes "flexible".
11926193326Sed        if (Record && Record->isUnion()) {
11927193326Sed          Record->setHasFlexibleArrayMember(true);
11928193326Sed        } else {
11929193326Sed          // If this is a struct/class and this is not the last element, reject
11930193326Sed          // it.  Note that GCC supports variable sized arrays in the middle of
11931193326Sed          // structures.
11932226633Sdim          if (i + 1 != Fields.end())
11933193326Sed            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11934193326Sed              << FD->getDeclName() << FD->getType();
11935193326Sed          else {
11936193326Sed            // We support flexible arrays at the end of structs in
11937193326Sed            // other structs as an extension.
11938193326Sed            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11939193326Sed              << FD->getDeclName();
11940193326Sed            if (Record)
11941193326Sed              Record->setHasFlexibleArrayMember(true);
11942193326Sed          }
11943193326Sed        }
11944193326Sed      }
11945239462Sdim      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11946239462Sdim          RequireNonAbstractType(FD->getLocation(), FD->getType(),
11947239462Sdim                                 diag::err_abstract_type_in_decl,
11948239462Sdim                                 AbstractIvarType)) {
11949239462Sdim        // Ivars can not have abstract class types
11950239462Sdim        FD->setInvalidDecl();
11951239462Sdim      }
11952198092Srdivacky      if (Record && FDTTy->getDecl()->hasObjectMember())
11953198092Srdivacky        Record->setHasObjectMember(true);
11954249423Sdim      if (Record && FDTTy->getDecl()->hasVolatileMember())
11955249423Sdim        Record->setHasVolatileMember(true);
11956208600Srdivacky    } else if (FDTy->isObjCObjectType()) {
11957193326Sed      /// A field cannot be an Objective-c object
11958226633Sdim      Diag(FD->getLocation(), diag::err_statically_allocated_object)
11959226633Sdim        << FixItHint::CreateInsertion(FD->getLocation(), "*");
11960226633Sdim      QualType T = Context.getObjCObjectPointerType(FD->getType());
11961226633Sdim      FD->setType(T);
11962249423Sdim    } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11963249423Sdim               (!getLangOpts().CPlusPlus || Record->isUnion())) {
11964249423Sdim      // It's an error in ARC if a field has lifetime.
11965249423Sdim      // We don't want to report this in a system header, though,
11966249423Sdim      // so we just make the field unavailable.
11967249423Sdim      // FIXME: that's really not sufficient; we need to make the type
11968249423Sdim      // itself invalid to, say, initialize or copy.
11969249423Sdim      QualType T = FD->getType();
11970249423Sdim      Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11971249423Sdim      if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11972249423Sdim        SourceLocation loc = FD->getLocation();
11973249423Sdim        if (getSourceManager().isInSystemHeader(loc)) {
11974249423Sdim          if (!FD->hasAttr<UnavailableAttr>()) {
11975249423Sdim            FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11976249423Sdim                              "this system field has retaining ownership"));
11977224145Sdim          }
11978249423Sdim        } else {
11979249423Sdim          Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
11980249423Sdim            << T->isBlockPointerType() << Record->getTagKind();
11981224145Sdim        }
11982249423Sdim        ARCErrReported = true;
11983224145Sdim      }
11984249423Sdim    } else if (getLangOpts().ObjC1 &&
11985234353Sdim               getLangOpts().getGC() != LangOptions::NonGC &&
11986224145Sdim               Record && !Record->hasObjectMember()) {
11987249423Sdim      if (FD->getType()->isObjCObjectPointerType() ||
11988249423Sdim          FD->getType().isObjCGCStrong())
11989249423Sdim        Record->setHasObjectMember(true);
11990249423Sdim      else if (Context.getAsArrayType(FD->getType())) {
11991249423Sdim        QualType BaseType = Context.getBaseElementType(FD->getType());
11992249423Sdim        if (BaseType->isRecordType() &&
11993249423Sdim            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
11994224145Sdim          Record->setHasObjectMember(true);
11995249423Sdim        else if (BaseType->isObjCObjectPointerType() ||
11996249423Sdim                 BaseType.isObjCGCStrong())
11997249423Sdim               Record->setHasObjectMember(true);
11998224145Sdim      }
11999210299Sed    }
12000249423Sdim    if (Record && FD->getType().isVolatileQualified())
12001249423Sdim      Record->setHasVolatileMember(true);
12002193326Sed    // Keep track of the number of named members.
12003193326Sed    if (FD->getIdentifier())
12004193326Sed      ++NumNamedMembers;
12005193326Sed  }
12006193326Sed
12007193326Sed  // Okay, we successfully defined 'Record'.
12008193326Sed  if (Record) {
12009218893Sdim    bool Completed = false;
12010218893Sdim    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12011218893Sdim      if (!CXXRecord->isInvalidDecl()) {
12012218893Sdim        // Set access bits correctly on the directly-declared conversions.
12013249423Sdim        for (CXXRecordDecl::conversion_iterator
12014249423Sdim               I = CXXRecord->conversion_begin(),
12015249423Sdim               E = CXXRecord->conversion_end(); I != E; ++I)
12016249423Sdim          I.setAccess((*I)->getAccess());
12017218893Sdim
12018218893Sdim        if (!CXXRecord->isDependentType()) {
12019263508Sdim          if (CXXRecord->hasUserDeclaredDestructor()) {
12020263508Sdim            // Adjust user-defined destructor exception spec.
12021263508Sdim            if (getLangOpts().CPlusPlus11)
12022263508Sdim              AdjustDestructorExceptionSpec(CXXRecord,
12023263508Sdim                                            CXXRecord->getDestructor());
12024223017Sdim
12025263508Sdim            // The Microsoft ABI requires that we perform the destructor body
12026263508Sdim            // checks (i.e. operator delete() lookup) at every declaration, as
12027263508Sdim            // any translation unit may need to emit a deleting destructor.
12028263508Sdim            if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12029263508Sdim              CheckDestructor(CXXRecord->getDestructor());
12030263508Sdim          }
12031263508Sdim
12032218893Sdim          // Add any implicitly-declared members to this class.
12033218893Sdim          AddImplicitlyDeclaredMembersToClass(CXXRecord);
12034218893Sdim
12035218893Sdim          // If we have virtual base classes, we may end up finding multiple
12036218893Sdim          // final overriders for a given virtual function. Check for this
12037218893Sdim          // problem now.
12038218893Sdim          if (CXXRecord->getNumVBases()) {
12039218893Sdim            CXXFinalOverriderMap FinalOverriders;
12040218893Sdim            CXXRecord->getFinalOverriders(FinalOverriders);
12041218893Sdim
12042218893Sdim            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12043218893Sdim                                             MEnd = FinalOverriders.end();
12044218893Sdim                 M != MEnd; ++M) {
12045218893Sdim              for (OverridingMethods::iterator SO = M->second.begin(),
12046218893Sdim                                            SOEnd = M->second.end();
12047218893Sdim                   SO != SOEnd; ++SO) {
12048218893Sdim                assert(SO->second.size() > 0 &&
12049218893Sdim                       "Virtual function without overridding functions?");
12050218893Sdim                if (SO->second.size() == 1)
12051218893Sdim                  continue;
12052218893Sdim
12053218893Sdim                // C++ [class.virtual]p2:
12054218893Sdim                //   In a derived class, if a virtual member function of a base
12055218893Sdim                //   class subobject has more than one final overrider the
12056218893Sdim                //   program is ill-formed.
12057218893Sdim                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12058243830Sdim                  << (const NamedDecl *)M->first << Record;
12059218893Sdim                Diag(M->first->getLocation(),
12060218893Sdim                     diag::note_overridden_virtual_function);
12061218893Sdim                for (OverridingMethods::overriding_iterator
12062218893Sdim                          OM = SO->second.begin(),
12063218893Sdim                       OMEnd = SO->second.end();
12064218893Sdim                     OM != OMEnd; ++OM)
12065218893Sdim                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
12066243830Sdim                    << (const NamedDecl *)M->first << OM->Method->getParent();
12067218893Sdim
12068218893Sdim                Record->setInvalidDecl();
12069218893Sdim              }
12070218893Sdim            }
12071218893Sdim            CXXRecord->completeDefinition(&FinalOverriders);
12072218893Sdim            Completed = true;
12073218893Sdim          }
12074218893Sdim        }
12075218893Sdim      }
12076218893Sdim    }
12077218893Sdim
12078218893Sdim    if (!Completed)
12079218893Sdim      Record->completeDefinition();
12080223017Sdim
12081249423Sdim    if (Record->hasAttrs())
12082249423Sdim      CheckAlignasUnderalignment(Record);
12083263508Sdim
12084263508Sdim    // Check if the structure/union declaration is a type that can have zero
12085263508Sdim    // size in C. For C this is a language extension, for C++ it may cause
12086263508Sdim    // compatibility problems.
12087263508Sdim    bool CheckForZeroSize;
12088263508Sdim    if (!getLangOpts().CPlusPlus) {
12089263508Sdim      CheckForZeroSize = true;
12090263508Sdim    } else {
12091263508Sdim      // For C++ filter out types that cannot be referenced in C code.
12092263508Sdim      CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12093263508Sdim      CheckForZeroSize =
12094263508Sdim          CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12095263508Sdim          !CXXRecord->isDependentType() &&
12096263508Sdim          CXXRecord->isCLike();
12097263508Sdim    }
12098263508Sdim    if (CheckForZeroSize) {
12099263508Sdim      bool ZeroSize = true;
12100263508Sdim      bool IsEmpty = true;
12101263508Sdim      unsigned NonBitFields = 0;
12102263508Sdim      for (RecordDecl::field_iterator I = Record->field_begin(),
12103263508Sdim                                      E = Record->field_end();
12104263508Sdim           (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12105263508Sdim        IsEmpty = false;
12106263508Sdim        if (I->isUnnamedBitfield()) {
12107263508Sdim          if (I->getBitWidthValue(Context) > 0)
12108263508Sdim            ZeroSize = false;
12109263508Sdim        } else {
12110263508Sdim          ++NonBitFields;
12111263508Sdim          QualType FieldType = I->getType();
12112263508Sdim          if (FieldType->isIncompleteType() ||
12113263508Sdim              !Context.getTypeSizeInChars(FieldType).isZero())
12114263508Sdim            ZeroSize = false;
12115263508Sdim        }
12116263508Sdim      }
12117263508Sdim
12118263508Sdim      // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12119263508Sdim      // allowed in C++, but warn if its declaration is inside
12120263508Sdim      // extern "C" block.
12121263508Sdim      if (ZeroSize) {
12122263508Sdim        Diag(RecLoc, getLangOpts().CPlusPlus ?
12123263508Sdim                         diag::warn_zero_size_struct_union_in_extern_c :
12124263508Sdim                         diag::warn_zero_size_struct_union_compat)
12125263508Sdim          << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12126263508Sdim      }
12127263508Sdim
12128263508Sdim      // Structs without named members are extension in C (C99 6.7.2.1p7),
12129263508Sdim      // but are accepted by GCC.
12130263508Sdim      if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12131263508Sdim        Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12132263508Sdim                               diag::ext_no_named_members_in_struct_union)
12133263508Sdim          << Record->isUnion();
12134263508Sdim      }
12135263508Sdim    }
12136193326Sed  } else {
12137193326Sed    ObjCIvarDecl **ClsFields =
12138193326Sed      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12139193326Sed    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12140234353Sdim      ID->setEndOfDefinitionLoc(RBrac);
12141193576Sed      // Add ivar's to class's DeclContext.
12142193576Sed      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12143193576Sed        ClsFields[i]->setLexicalDeclContext(ID);
12144195341Sed        ID->addDecl(ClsFields[i]);
12145193576Sed      }
12146193326Sed      // Must enforce the rule that ivars in the base classes may not be
12147193326Sed      // duplicates.
12148204643Srdivacky      if (ID->getSuperClass())
12149204643Srdivacky        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12150198092Srdivacky    } else if (ObjCImplementationDecl *IMPDecl =
12151193326Sed                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12152193326Sed      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12153193576Sed      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12154193576Sed        // Ivar declared in @implementation never belongs to the implementation.
12155193576Sed        // Only it is in implementation's lexical context.
12156193326Sed        ClsFields[I]->setLexicalDeclContext(IMPDecl);
12157193326Sed      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12158234353Sdim      IMPDecl->setIvarLBraceLoc(LBrac);
12159234353Sdim      IMPDecl->setIvarRBraceLoc(RBrac);
12160204643Srdivacky    } else if (ObjCCategoryDecl *CDecl =
12161204643Srdivacky                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12162207619Srdivacky      // case of ivars in class extension; all other cases have been
12163207619Srdivacky      // reported as errors elsewhere.
12164207619Srdivacky      // FIXME. Class extension does not have a LocEnd field.
12165207619Srdivacky      // CDecl->setLocEnd(RBrac);
12166207619Srdivacky      // Add ivar's to class extension's DeclContext.
12167234353Sdim      // Diagnose redeclaration of private ivars.
12168234353Sdim      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12169207619Srdivacky      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12170234353Sdim        if (IDecl) {
12171234353Sdim          if (const ObjCIvarDecl *ClsIvar =
12172234353Sdim              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12173234353Sdim            Diag(ClsFields[i]->getLocation(),
12174234353Sdim                 diag::err_duplicate_ivar_declaration);
12175234353Sdim            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12176234353Sdim            continue;
12177234353Sdim          }
12178249423Sdim          for (ObjCInterfaceDecl::known_extensions_iterator
12179249423Sdim                 Ext = IDecl->known_extensions_begin(),
12180249423Sdim                 ExtEnd = IDecl->known_extensions_end();
12181249423Sdim               Ext != ExtEnd; ++Ext) {
12182249423Sdim            if (const ObjCIvarDecl *ClsExtIvar
12183249423Sdim                  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12184234353Sdim              Diag(ClsFields[i]->getLocation(),
12185234353Sdim                   diag::err_duplicate_ivar_declaration);
12186234353Sdim              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12187234353Sdim              continue;
12188234353Sdim            }
12189234353Sdim          }
12190234353Sdim        }
12191207619Srdivacky        ClsFields[i]->setLexicalDeclContext(CDecl);
12192207619Srdivacky        CDecl->addDecl(ClsFields[i]);
12193204643Srdivacky      }
12194234353Sdim      CDecl->setIvarLBraceLoc(LBrac);
12195234353Sdim      CDecl->setIvarRBraceLoc(RBrac);
12196193326Sed    }
12197193326Sed  }
12198193326Sed
12199193326Sed  if (Attr)
12200194613Sed    ProcessDeclAttributeList(S, Record, Attr);
12201193326Sed}
12202193326Sed
12203203955Srdivacky/// \brief Determine whether the given integral value is representable within
12204203955Srdivacky/// the given type T.
12205203955Srdivackystatic bool isRepresentableIntegerValue(ASTContext &Context,
12206203955Srdivacky                                        llvm::APSInt &Value,
12207203955Srdivacky                                        QualType T) {
12208210299Sed  assert(T->isIntegralType(Context) && "Integral type required!");
12209207619Srdivacky  unsigned BitWidth = Context.getIntWidth(T);
12210203955Srdivacky
12211218893Sdim  if (Value.isUnsigned() || Value.isNonNegative()) {
12212223017Sdim    if (T->isSignedIntegerOrEnumerationType())
12213218893Sdim      --BitWidth;
12214218893Sdim    return Value.getActiveBits() <= BitWidth;
12215218893Sdim  }
12216203955Srdivacky  return Value.getMinSignedBits() <= BitWidth;
12217203955Srdivacky}
12218203955Srdivacky
12219203955Srdivacky// \brief Given an integral type, return the next larger integral type
12220203955Srdivacky// (or a NULL type of no such type exists).
12221203955Srdivackystatic QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12222203955Srdivacky  // FIXME: Int128/UInt128 support, which also needs to be introduced into
12223203955Srdivacky  // enum checking below.
12224210299Sed  assert(T->isIntegralType(Context) && "Integral type required!");
12225203955Srdivacky  const unsigned NumTypes = 4;
12226203955Srdivacky  QualType SignedIntegralTypes[NumTypes] = {
12227203955Srdivacky    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12228203955Srdivacky  };
12229203955Srdivacky  QualType UnsignedIntegralTypes[NumTypes] = {
12230203955Srdivacky    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12231203955Srdivacky    Context.UnsignedLongLongTy
12232203955Srdivacky  };
12233203955Srdivacky
12234203955Srdivacky  unsigned BitWidth = Context.getTypeSize(T);
12235223017Sdim  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12236223017Sdim                                                        : UnsignedIntegralTypes;
12237203955Srdivacky  for (unsigned I = 0; I != NumTypes; ++I)
12238203955Srdivacky    if (Context.getTypeSize(Types[I]) > BitWidth)
12239203955Srdivacky      return Types[I];
12240203955Srdivacky
12241203955Srdivacky  return QualType();
12242203955Srdivacky}
12243203955Srdivacky
12244193326SedEnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12245193326Sed                                          EnumConstantDecl *LastEnumConst,
12246193326Sed                                          SourceLocation IdLoc,
12247193326Sed                                          IdentifierInfo *Id,
12248212904Sdim                                          Expr *Val) {
12249226633Sdim  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12250203955Srdivacky  llvm::APSInt EnumVal(IntWidth);
12251193326Sed  QualType EltTy;
12252218893Sdim
12253218893Sdim  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12254218893Sdim    Val = 0;
12255218893Sdim
12256234353Sdim  if (Val)
12257234353Sdim    Val = DefaultLvalueConversion(Val).take();
12258234353Sdim
12259199482Srdivacky  if (Val) {
12260204643Srdivacky    if (Enum->isDependentType() || Val->isTypeDependent())
12261199482Srdivacky      EltTy = Context.DependentTy;
12262199482Srdivacky    else {
12263199482Srdivacky      SourceLocation ExpLoc;
12264249423Sdim      if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12265234353Sdim          !getLangOpts().MicrosoftMode) {
12266234353Sdim        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12267234353Sdim        // constant-expression in the enumerator-definition shall be a converted
12268234353Sdim        // constant expression of the underlying type.
12269234353Sdim        EltTy = Enum->getIntegerType();
12270234353Sdim        ExprResult Converted =
12271234353Sdim          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12272234353Sdim                                           CCEK_Enumerator);
12273234353Sdim        if (Converted.isInvalid())
12274234353Sdim          Val = 0;
12275234353Sdim        else
12276234353Sdim          Val = Converted.take();
12277234353Sdim      } else if (!Val->isValueDependent() &&
12278234353Sdim                 !(Val = VerifyIntegerConstantExpression(Val,
12279234353Sdim                                                         &EnumVal).take())) {
12280234353Sdim        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12281234353Sdim      } else {
12282218893Sdim        if (Enum->isFixed()) {
12283218893Sdim          EltTy = Enum->getIntegerType();
12284218893Sdim
12285234353Sdim          // In Obj-C and Microsoft mode, require the enumeration value to be
12286234353Sdim          // representable in the underlying type of the enumeration. In C++11,
12287234353Sdim          // we perform a non-narrowing conversion as part of converted constant
12288234353Sdim          // expression checking.
12289218893Sdim          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12290234353Sdim            if (getLangOpts().MicrosoftMode) {
12291218893Sdim              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12292221345Sdim              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12293234353Sdim            } else
12294234353Sdim              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12295218893Sdim          } else
12296221345Sdim            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12297234353Sdim        } else if (getLangOpts().CPlusPlus) {
12298234353Sdim          // C++11 [dcl.enum]p5:
12299218893Sdim          //   If the underlying type is not fixed, the type of each enumerator
12300218893Sdim          //   is the type of its initializing value:
12301218893Sdim          //     - If an initializer is specified for an enumerator, the
12302218893Sdim          //       initializing value has the same type as the expression.
12303218893Sdim          EltTy = Val->getType();
12304234353Sdim        } else {
12305234353Sdim          // C99 6.7.2.2p2:
12306234353Sdim          //   The expression that defines the value of an enumeration constant
12307234353Sdim          //   shall be an integer constant expression that has a value
12308234353Sdim          //   representable as an int.
12309234353Sdim
12310234353Sdim          // Complain if the value is not representable in an int.
12311234353Sdim          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12312234353Sdim            Diag(IdLoc, diag::ext_enum_value_not_int)
12313234353Sdim              << EnumVal.toString(10) << Val->getSourceRange()
12314234353Sdim              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12315234353Sdim          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12316234353Sdim            // Force the type of the expression to 'int'.
12317234353Sdim            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12318234353Sdim          }
12319234353Sdim          EltTy = Val->getType();
12320218893Sdim        }
12321199482Srdivacky      }
12322193326Sed    }
12323193326Sed  }
12324198092Srdivacky
12325193326Sed  if (!Val) {
12326200583Srdivacky    if (Enum->isDependentType())
12327200583Srdivacky      EltTy = Context.DependentTy;
12328203955Srdivacky    else if (!LastEnumConst) {
12329203955Srdivacky      // C++0x [dcl.enum]p5:
12330203955Srdivacky      //   If the underlying type is not fixed, the type of each enumerator
12331203955Srdivacky      //   is the type of its initializing value:
12332203955Srdivacky      //     - If no initializer is specified for the first enumerator, the
12333203955Srdivacky      //       initializing value has an unspecified integral type.
12334203955Srdivacky      //
12335203955Srdivacky      // GCC uses 'int' for its unspecified integral type, as does
12336203955Srdivacky      // C99 6.7.2.2p3.
12337218893Sdim      if (Enum->isFixed()) {
12338218893Sdim        EltTy = Enum->getIntegerType();
12339218893Sdim      }
12340218893Sdim      else {
12341218893Sdim        EltTy = Context.IntTy;
12342218893Sdim      }
12343203955Srdivacky    } else {
12344193326Sed      // Assign the last value + 1.
12345193326Sed      EnumVal = LastEnumConst->getInitVal();
12346193326Sed      ++EnumVal;
12347203955Srdivacky      EltTy = LastEnumConst->getType();
12348193326Sed
12349193326Sed      // Check for overflow on increment.
12350203955Srdivacky      if (EnumVal < LastEnumConst->getInitVal()) {
12351203955Srdivacky        // C++0x [dcl.enum]p5:
12352203955Srdivacky        //   If the underlying type is not fixed, the type of each enumerator
12353203955Srdivacky        //   is the type of its initializing value:
12354203955Srdivacky        //
12355203955Srdivacky        //     - Otherwise the type of the initializing value is the same as
12356203955Srdivacky        //       the type of the initializing value of the preceding enumerator
12357203955Srdivacky        //       unless the incremented value is not representable in that type,
12358203955Srdivacky        //       in which case the type is an unspecified integral type
12359203955Srdivacky        //       sufficient to contain the incremented value. If no such type
12360203955Srdivacky        //       exists, the program is ill-formed.
12361203955Srdivacky        QualType T = getNextLargerIntegralType(Context, EltTy);
12362218893Sdim        if (T.isNull() || Enum->isFixed()) {
12363203955Srdivacky          // There is no integral type larger enough to represent this
12364203955Srdivacky          // value. Complain, then allow the value to wrap around.
12365203955Srdivacky          EnumVal = LastEnumConst->getInitVal();
12366218893Sdim          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12367218893Sdim          ++EnumVal;
12368218893Sdim          if (Enum->isFixed())
12369218893Sdim            // When the underlying type is fixed, this is ill-formed.
12370218893Sdim            Diag(IdLoc, diag::err_enumerator_wrapped)
12371218893Sdim              << EnumVal.toString(10)
12372218893Sdim              << EltTy;
12373218893Sdim          else
12374218893Sdim            Diag(IdLoc, diag::warn_enumerator_too_large)
12375218893Sdim              << EnumVal.toString(10);
12376203955Srdivacky        } else {
12377203955Srdivacky          EltTy = T;
12378203955Srdivacky        }
12379203955Srdivacky
12380203955Srdivacky        // Retrieve the last enumerator's value, extent that type to the
12381203955Srdivacky        // type that is supposed to be large enough to represent the incremented
12382203955Srdivacky        // value, then increment.
12383203955Srdivacky        EnumVal = LastEnumConst->getInitVal();
12384223017Sdim        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12385218893Sdim        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12386203955Srdivacky        ++EnumVal;
12387203955Srdivacky
12388203955Srdivacky        // If we're not in C++, diagnose the overflow of enumerator values,
12389203955Srdivacky        // which in C99 means that the enumerator value is not representable in
12390203955Srdivacky        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12391203955Srdivacky        // permits enumerator values that are representable in some larger
12392203955Srdivacky        // integral type.
12393234353Sdim        if (!getLangOpts().CPlusPlus && !T.isNull())
12394203955Srdivacky          Diag(IdLoc, diag::warn_enum_value_overflow);
12395234353Sdim      } else if (!getLangOpts().CPlusPlus &&
12396203955Srdivacky                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12397203955Srdivacky        // Enforce C99 6.7.2.2p2 even when we compute the next value.
12398203955Srdivacky        Diag(IdLoc, diag::ext_enum_value_not_int)
12399203955Srdivacky          << EnumVal.toString(10) << 1;
12400203955Srdivacky      }
12401193326Sed    }
12402193326Sed  }
12403198092Srdivacky
12404204643Srdivacky  if (!EltTy->isDependentType()) {
12405203955Srdivacky    // Make the enumerator value match the signedness and size of the
12406203955Srdivacky    // enumerator's type.
12407234353Sdim    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12408223017Sdim    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12409203955Srdivacky  }
12410199482Srdivacky
12411193326Sed  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12412198092Srdivacky                                  Val, EnumVal);
12413193326Sed}
12414193326Sed
12415193326Sed
12416218893SdimDecl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12417218893Sdim                              SourceLocation IdLoc, IdentifierInfo *Id,
12418218893Sdim                              AttributeList *Attr,
12419234353Sdim                              SourceLocation EqualLoc, Expr *Val) {
12420212904Sdim  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12421193326Sed  EnumConstantDecl *LastEnumConst =
12422212904Sdim    cast_or_null<EnumConstantDecl>(lastEnumConst);
12423193326Sed
12424193326Sed  // The scope passed in may not be a decl scope.  Zip up the scope tree until
12425193326Sed  // we find one that is.
12426193326Sed  S = getNonFieldDeclScope(S);
12427198092Srdivacky
12428193326Sed  // Verify that there isn't already something declared with this name in this
12429193326Sed  // scope.
12430207619Srdivacky  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12431202879Srdivacky                                         ForRedeclaration);
12432193326Sed  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12433193326Sed    // Maybe we will complain about the shadowed template parameter.
12434193326Sed    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12435193326Sed    // Just pretend that we didn't see the previous declaration.
12436193326Sed    PrevDecl = 0;
12437193326Sed  }
12438193326Sed
12439193326Sed  if (PrevDecl) {
12440193326Sed    // When in C++, we may get a TagDecl with the same name; in this case the
12441193326Sed    // enum constant will 'hide' the tag.
12442234353Sdim    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12443193326Sed           "Received TagDecl when not in C++!");
12444193326Sed    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12445193326Sed      if (isa<EnumConstantDecl>(PrevDecl))
12446193326Sed        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12447193326Sed      else
12448193326Sed        Diag(IdLoc, diag::err_redefinition) << Id;
12449193326Sed      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12450212904Sdim      return 0;
12451193326Sed    }
12452193326Sed  }
12453193326Sed
12454239462Sdim  // C++ [class.mem]p15:
12455239462Sdim  // If T is the name of a class, then each of the following shall have a name
12456239462Sdim  // different from T:
12457239462Sdim  // - every enumerator of every member of class T that is an unscoped
12458239462Sdim  // enumerated type
12459218893Sdim  if (CXXRecordDecl *Record
12460218893Sdim                      = dyn_cast<CXXRecordDecl>(
12461218893Sdim                             TheEnumDecl->getDeclContext()->getRedeclContext()))
12462239462Sdim    if (!TheEnumDecl->isScoped() &&
12463239462Sdim        Record->getIdentifier() && Record->getIdentifier() == Id)
12464218893Sdim      Diag(IdLoc, diag::err_member_name_of_class) << Id;
12465218893Sdim
12466218893Sdim  EnumConstantDecl *New =
12467218893Sdim    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12468193326Sed
12469202879Srdivacky  if (New) {
12470218893Sdim    // Process attributes.
12471218893Sdim    if (Attr) ProcessDeclAttributeList(S, New, Attr);
12472218893Sdim
12473218893Sdim    // Register this decl in the current scope stack.
12474202879Srdivacky    New->setAccess(TheEnumDecl->getAccess());
12475193326Sed    PushOnScopeChains(New, S);
12476202879Srdivacky  }
12477193326Sed
12478239462Sdim  ActOnDocumentableDecl(New);
12479239462Sdim
12480212904Sdim  return New;
12481193326Sed}
12482193326Sed
12483249423Sdim// Returns true when the enum initial expression does not trigger the
12484249423Sdim// duplicate enum warning.  A few common cases are exempted as follows:
12485249423Sdim// Element2 = Element1
12486249423Sdim// Element2 = Element1 + 1
12487249423Sdim// Element2 = Element1 - 1
12488249423Sdim// Where Element2 and Element1 are from the same enum.
12489249423Sdimstatic bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12490249423Sdim  Expr *InitExpr = ECD->getInitExpr();
12491249423Sdim  if (!InitExpr)
12492249423Sdim    return true;
12493249423Sdim  InitExpr = InitExpr->IgnoreImpCasts();
12494249423Sdim
12495249423Sdim  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12496249423Sdim    if (!BO->isAdditiveOp())
12497249423Sdim      return true;
12498249423Sdim    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12499249423Sdim    if (!IL)
12500249423Sdim      return true;
12501249423Sdim    if (IL->getValue() != 1)
12502249423Sdim      return true;
12503249423Sdim
12504249423Sdim    InitExpr = BO->getLHS();
12505249423Sdim  }
12506249423Sdim
12507249423Sdim  // This checks if the elements are from the same enum.
12508249423Sdim  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12509249423Sdim  if (!DRE)
12510249423Sdim    return true;
12511249423Sdim
12512249423Sdim  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12513249423Sdim  if (!EnumConstant)
12514249423Sdim    return true;
12515249423Sdim
12516249423Sdim  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12517249423Sdim      Enum)
12518249423Sdim    return true;
12519249423Sdim
12520249423Sdim  return false;
12521249423Sdim}
12522249423Sdim
12523249423Sdimstruct DupKey {
12524249423Sdim  int64_t val;
12525249423Sdim  bool isTombstoneOrEmptyKey;
12526249423Sdim  DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12527249423Sdim    : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12528249423Sdim};
12529249423Sdim
12530249423Sdimstatic DupKey GetDupKey(const llvm::APSInt& Val) {
12531249423Sdim  return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12532249423Sdim                false);
12533249423Sdim}
12534249423Sdim
12535249423Sdimstruct DenseMapInfoDupKey {
12536249423Sdim  static DupKey getEmptyKey() { return DupKey(0, true); }
12537249423Sdim  static DupKey getTombstoneKey() { return DupKey(1, true); }
12538249423Sdim  static unsigned getHashValue(const DupKey Key) {
12539249423Sdim    return (unsigned)(Key.val * 37);
12540249423Sdim  }
12541249423Sdim  static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12542249423Sdim    return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12543249423Sdim           LHS.val == RHS.val;
12544249423Sdim  }
12545249423Sdim};
12546249423Sdim
12547249423Sdim// Emits a warning when an element is implicitly set a value that
12548249423Sdim// a previous element has already been set to.
12549251662Sdimstatic void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12550251662Sdim                                        EnumDecl *Enum,
12551249423Sdim                                        QualType EnumType) {
12552249423Sdim  if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12553249423Sdim                                 Enum->getLocation()) ==
12554249423Sdim      DiagnosticsEngine::Ignored)
12555249423Sdim    return;
12556249423Sdim  // Avoid anonymous enums
12557249423Sdim  if (!Enum->getIdentifier())
12558249423Sdim    return;
12559249423Sdim
12560249423Sdim  // Only check for small enums.
12561249423Sdim  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12562249423Sdim    return;
12563249423Sdim
12564249423Sdim  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12565249423Sdim  typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12566249423Sdim
12567249423Sdim  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12568249423Sdim  typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12569249423Sdim          ValueToVectorMap;
12570249423Sdim
12571249423Sdim  DuplicatesVector DupVector;
12572249423Sdim  ValueToVectorMap EnumMap;
12573249423Sdim
12574249423Sdim  // Populate the EnumMap with all values represented by enum constants without
12575249423Sdim  // an initialier.
12576251662Sdim  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12577251662Sdim    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12578249423Sdim
12579249423Sdim    // Null EnumConstantDecl means a previous diagnostic has been emitted for
12580249423Sdim    // this constant.  Skip this enum since it may be ill-formed.
12581249423Sdim    if (!ECD) {
12582249423Sdim      return;
12583249423Sdim    }
12584249423Sdim
12585249423Sdim    if (ECD->getInitExpr())
12586249423Sdim      continue;
12587249423Sdim
12588249423Sdim    DupKey Key = GetDupKey(ECD->getInitVal());
12589249423Sdim    DeclOrVector &Entry = EnumMap[Key];
12590249423Sdim
12591249423Sdim    // First time encountering this value.
12592249423Sdim    if (Entry.isNull())
12593249423Sdim      Entry = ECD;
12594249423Sdim  }
12595249423Sdim
12596249423Sdim  // Create vectors for any values that has duplicates.
12597251662Sdim  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12598249423Sdim    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12599249423Sdim    if (!ValidDuplicateEnum(ECD, Enum))
12600249423Sdim      continue;
12601249423Sdim
12602249423Sdim    DupKey Key = GetDupKey(ECD->getInitVal());
12603249423Sdim
12604249423Sdim    DeclOrVector& Entry = EnumMap[Key];
12605249423Sdim    if (Entry.isNull())
12606249423Sdim      continue;
12607249423Sdim
12608249423Sdim    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12609249423Sdim      // Ensure constants are different.
12610249423Sdim      if (D == ECD)
12611249423Sdim        continue;
12612249423Sdim
12613249423Sdim      // Create new vector and push values onto it.
12614249423Sdim      ECDVector *Vec = new ECDVector();
12615249423Sdim      Vec->push_back(D);
12616249423Sdim      Vec->push_back(ECD);
12617249423Sdim
12618249423Sdim      // Update entry to point to the duplicates vector.
12619249423Sdim      Entry = Vec;
12620249423Sdim
12621249423Sdim      // Store the vector somewhere we can consult later for quick emission of
12622249423Sdim      // diagnostics.
12623249423Sdim      DupVector.push_back(Vec);
12624249423Sdim      continue;
12625249423Sdim    }
12626249423Sdim
12627249423Sdim    ECDVector *Vec = Entry.get<ECDVector*>();
12628249423Sdim    // Make sure constants are not added more than once.
12629249423Sdim    if (*Vec->begin() == ECD)
12630249423Sdim      continue;
12631249423Sdim
12632249423Sdim    Vec->push_back(ECD);
12633249423Sdim  }
12634249423Sdim
12635249423Sdim  // Emit diagnostics.
12636249423Sdim  for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12637249423Sdim                                  DupVectorEnd = DupVector.end();
12638249423Sdim       DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12639249423Sdim    ECDVector *Vec = *DupVectorIter;
12640249423Sdim    assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12641249423Sdim
12642249423Sdim    // Emit warning for one enum constant.
12643249423Sdim    ECDVector::iterator I = Vec->begin();
12644249423Sdim    S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12645249423Sdim      << (*I)->getName() << (*I)->getInitVal().toString(10)
12646249423Sdim      << (*I)->getSourceRange();
12647249423Sdim    ++I;
12648249423Sdim
12649249423Sdim    // Emit one note for each of the remaining enum constants with
12650249423Sdim    // the same value.
12651249423Sdim    for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12652249423Sdim      S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12653249423Sdim        << (*I)->getName() << (*I)->getInitVal().toString(10)
12654249423Sdim        << (*I)->getSourceRange();
12655249423Sdim    delete Vec;
12656249423Sdim  }
12657249423Sdim}
12658249423Sdim
12659193326Sedvoid Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12660212904Sdim                         SourceLocation RBraceLoc, Decl *EnumDeclX,
12661251662Sdim                         ArrayRef<Decl *> Elements,
12662198092Srdivacky                         Scope *S, AttributeList *Attr) {
12663212904Sdim  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12664193326Sed  QualType EnumType = Context.getTypeDeclType(Enum);
12665198092Srdivacky
12666198092Srdivacky  if (Attr)
12667198092Srdivacky    ProcessDeclAttributeList(S, Enum, Attr);
12668198092Srdivacky
12669200583Srdivacky  if (Enum->isDependentType()) {
12670251662Sdim    for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12671200583Srdivacky      EnumConstantDecl *ECD =
12672212904Sdim        cast_or_null<EnumConstantDecl>(Elements[i]);
12673200583Srdivacky      if (!ECD) continue;
12674200583Srdivacky
12675200583Srdivacky      ECD->setType(EnumType);
12676200583Srdivacky    }
12677200583Srdivacky
12678208600Srdivacky    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12679200583Srdivacky    return;
12680200583Srdivacky  }
12681200583Srdivacky
12682193326Sed  // TODO: If the result value doesn't fit in an int, it must be a long or long
12683193326Sed  // long value.  ISO C does not support this, but GCC does as an extension,
12684193326Sed  // emit a warning.
12685226633Sdim  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12686226633Sdim  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12687226633Sdim  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12688198092Srdivacky
12689193326Sed  // Verify that all the values are okay, compute the size of the values, and
12690193326Sed  // reverse the list.
12691193326Sed  unsigned NumNegativeBits = 0;
12692193326Sed  unsigned NumPositiveBits = 0;
12693198092Srdivacky
12694193326Sed  // Keep track of whether all elements have type int.
12695193326Sed  bool AllElementsInt = true;
12696198092Srdivacky
12697251662Sdim  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12698193326Sed    EnumConstantDecl *ECD =
12699212904Sdim      cast_or_null<EnumConstantDecl>(Elements[i]);
12700193326Sed    if (!ECD) continue;  // Already issued a diagnostic.
12701198092Srdivacky
12702193326Sed    const llvm::APSInt &InitVal = ECD->getInitVal();
12703198092Srdivacky
12704193326Sed    // Keep track of the size of positive and negative values.
12705193326Sed    if (InitVal.isUnsigned() || InitVal.isNonNegative())
12706193326Sed      NumPositiveBits = std::max(NumPositiveBits,
12707193326Sed                                 (unsigned)InitVal.getActiveBits());
12708193326Sed    else
12709193326Sed      NumNegativeBits = std::max(NumNegativeBits,
12710193326Sed                                 (unsigned)InitVal.getMinSignedBits());
12711193326Sed
12712193326Sed    // Keep track of whether every enum element has type int (very commmon).
12713193326Sed    if (AllElementsInt)
12714198092Srdivacky      AllElementsInt = ECD->getType() == Context.IntTy;
12715193326Sed  }
12716198092Srdivacky
12717193326Sed  // Figure out the type that should be used for this enum.
12718193326Sed  QualType BestType;
12719193326Sed  unsigned BestWidth;
12720198092Srdivacky
12721200583Srdivacky  // C++0x N3000 [conv.prom]p3:
12722200583Srdivacky  //   An rvalue of an unscoped enumeration type whose underlying
12723200583Srdivacky  //   type is not fixed can be converted to an rvalue of the first
12724200583Srdivacky  //   of the following types that can represent all the values of
12725200583Srdivacky  //   the enumeration: int, unsigned int, long int, unsigned long
12726200583Srdivacky  //   int, long long int, or unsigned long long int.
12727200583Srdivacky  // C99 6.4.4.3p2:
12728200583Srdivacky  //   An identifier declared as an enumeration constant has type int.
12729200583Srdivacky  // The C99 rule is modified by a gcc extension
12730200583Srdivacky  QualType BestPromotionType;
12731200583Srdivacky
12732198092Srdivacky  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
12733218893Sdim  // -fshort-enums is the equivalent to specifying the packed attribute on all
12734218893Sdim  // enum definitions.
12735218893Sdim  if (LangOpts.ShortEnums)
12736218893Sdim    Packed = true;
12737198092Srdivacky
12738218893Sdim  if (Enum->isFixed()) {
12739234353Sdim    BestType = Enum->getIntegerType();
12740234353Sdim    if (BestType->isPromotableIntegerType())
12741234353Sdim      BestPromotionType = Context.getPromotedIntegerType(BestType);
12742234353Sdim    else
12743234353Sdim      BestPromotionType = BestType;
12744218893Sdim    // We don't need to set BestWidth, because BestType is going to be the type
12745218893Sdim    // of the enumerators, but we do anyway because otherwise some compilers
12746218893Sdim    // warn that it might be used uninitialized.
12747218893Sdim    BestWidth = CharWidth;
12748218893Sdim  }
12749218893Sdim  else if (NumNegativeBits) {
12750198092Srdivacky    // If there is a negative value, figure out the smallest integer type (of
12751193326Sed    // int/long/longlong) that fits.
12752198092Srdivacky    // If it's packed, check also if it fits a char or a short.
12753198092Srdivacky    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12754200583Srdivacky      BestType = Context.SignedCharTy;
12755200583Srdivacky      BestWidth = CharWidth;
12756198092Srdivacky    } else if (Packed && NumNegativeBits <= ShortWidth &&
12757198092Srdivacky               NumPositiveBits < ShortWidth) {
12758200583Srdivacky      BestType = Context.ShortTy;
12759200583Srdivacky      BestWidth = ShortWidth;
12760200583Srdivacky    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12761193326Sed      BestType = Context.IntTy;
12762193326Sed      BestWidth = IntWidth;
12763193326Sed    } else {
12764226633Sdim      BestWidth = Context.getTargetInfo().getLongWidth();
12765198092Srdivacky
12766200583Srdivacky      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12767193326Sed        BestType = Context.LongTy;
12768200583Srdivacky      } else {
12769226633Sdim        BestWidth = Context.getTargetInfo().getLongLongWidth();
12770198092Srdivacky
12771193326Sed        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12772193326Sed          Diag(Enum->getLocation(), diag::warn_enum_too_large);
12773193326Sed        BestType = Context.LongLongTy;
12774193326Sed      }
12775193326Sed    }
12776200583Srdivacky    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12777193326Sed  } else {
12778203955Srdivacky    // If there is no negative value, figure out the smallest type that fits
12779203955Srdivacky    // all of the enumerator values.
12780198092Srdivacky    // If it's packed, check also if it fits a char or a short.
12781198092Srdivacky    if (Packed && NumPositiveBits <= CharWidth) {
12782200583Srdivacky      BestType = Context.UnsignedCharTy;
12783200583Srdivacky      BestPromotionType = Context.IntTy;
12784200583Srdivacky      BestWidth = CharWidth;
12785198092Srdivacky    } else if (Packed && NumPositiveBits <= ShortWidth) {
12786200583Srdivacky      BestType = Context.UnsignedShortTy;
12787200583Srdivacky      BestPromotionType = Context.IntTy;
12788200583Srdivacky      BestWidth = ShortWidth;
12789200583Srdivacky    } else if (NumPositiveBits <= IntWidth) {
12790193326Sed      BestType = Context.UnsignedIntTy;
12791193326Sed      BestWidth = IntWidth;
12792203955Srdivacky      BestPromotionType
12793234353Sdim        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12794203955Srdivacky                           ? Context.UnsignedIntTy : Context.IntTy;
12795193326Sed    } else if (NumPositiveBits <=
12796226633Sdim               (BestWidth = Context.getTargetInfo().getLongWidth())) {
12797193326Sed      BestType = Context.UnsignedLongTy;
12798203955Srdivacky      BestPromotionType
12799234353Sdim        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12800203955Srdivacky                           ? Context.UnsignedLongTy : Context.LongTy;
12801193326Sed    } else {
12802226633Sdim      BestWidth = Context.getTargetInfo().getLongLongWidth();
12803193326Sed      assert(NumPositiveBits <= BestWidth &&
12804193326Sed             "How could an initializer get larger than ULL?");
12805193326Sed      BestType = Context.UnsignedLongLongTy;
12806203955Srdivacky      BestPromotionType
12807234353Sdim        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12808203955Srdivacky                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
12809193326Sed    }
12810193326Sed  }
12811198092Srdivacky
12812193326Sed  // Loop over all of the enumerator constants, changing their types to match
12813193326Sed  // the type of the enum if needed.
12814251662Sdim  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12815212904Sdim    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12816193326Sed    if (!ECD) continue;  // Already issued a diagnostic.
12817193326Sed
12818193326Sed    // Standard C says the enumerators have int type, but we allow, as an
12819193326Sed    // extension, the enumerators to be larger than int size.  If each
12820193326Sed    // enumerator value fits in an int, type it as an int, otherwise type it the
12821193326Sed    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12822193326Sed    // that X has type 'int', not 'unsigned'.
12823193326Sed
12824193326Sed    // Determine whether the value fits into an int.
12825193326Sed    llvm::APSInt InitVal = ECD->getInitVal();
12826193326Sed
12827193326Sed    // If it fits into an integer type, force it.  Otherwise force it to match
12828193326Sed    // the enum decl type.
12829193326Sed    QualType NewTy;
12830193326Sed    unsigned NewWidth;
12831193326Sed    bool NewSign;
12832234353Sdim    if (!getLangOpts().CPlusPlus &&
12833234353Sdim        !Enum->isFixed() &&
12834203955Srdivacky        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12835193326Sed      NewTy = Context.IntTy;
12836193326Sed      NewWidth = IntWidth;
12837193326Sed      NewSign = true;
12838193326Sed    } else if (ECD->getType() == BestType) {
12839193326Sed      // Already the right type!
12840234353Sdim      if (getLangOpts().CPlusPlus)
12841193326Sed        // C++ [dcl.enum]p4: Following the closing brace of an
12842193326Sed        // enum-specifier, each enumerator has the type of its
12843198092Srdivacky        // enumeration.
12844193326Sed        ECD->setType(EnumType);
12845193326Sed      continue;
12846193326Sed    } else {
12847193326Sed      NewTy = BestType;
12848193326Sed      NewWidth = BestWidth;
12849223017Sdim      NewSign = BestType->isSignedIntegerOrEnumerationType();
12850193326Sed    }
12851193326Sed
12852193326Sed    // Adjust the APSInt value.
12853218893Sdim    InitVal = InitVal.extOrTrunc(NewWidth);
12854193326Sed    InitVal.setIsSigned(NewSign);
12855193326Sed    ECD->setInitVal(InitVal);
12856198092Srdivacky
12857193326Sed    // Adjust the Expr initializer and type.
12858218893Sdim    if (ECD->getInitExpr() &&
12859224145Sdim        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12860212904Sdim      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12861212904Sdim                                                CK_IntegralCast,
12862212904Sdim                                                ECD->getInitExpr(),
12863212904Sdim                                                /*base paths*/ 0,
12864212904Sdim                                                VK_RValue));
12865234353Sdim    if (getLangOpts().CPlusPlus)
12866193326Sed      // C++ [dcl.enum]p4: Following the closing brace of an
12867193326Sed      // enum-specifier, each enumerator has the type of its
12868198092Srdivacky      // enumeration.
12869193326Sed      ECD->setType(EnumType);
12870193326Sed    else
12871193326Sed      ECD->setType(NewTy);
12872193326Sed  }
12873198092Srdivacky
12874208600Srdivacky  Enum->completeDefinition(BestType, BestPromotionType,
12875208600Srdivacky                           NumPositiveBits, NumNegativeBits);
12876234353Sdim
12877234353Sdim  // If we're declaring a function, ensure this decl isn't forgotten about -
12878234353Sdim  // it needs to go into the function scope.
12879234353Sdim  if (InFunctionDeclarator)
12880234353Sdim    DeclsInPrototypeScope.push_back(Enum);
12881249423Sdim
12882251662Sdim  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12883249423Sdim
12884249423Sdim  // Now that the enum type is defined, ensure it's not been underaligned.
12885249423Sdim  if (Enum->hasAttrs())
12886249423Sdim    CheckAlignasUnderalignment(Enum);
12887193326Sed}
12888193326Sed
12889221345SdimDecl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12890221345Sdim                                  SourceLocation StartLoc,
12891221345Sdim                                  SourceLocation EndLoc) {
12892212904Sdim  StringLiteral *AsmString = cast<StringLiteral>(expr);
12893193326Sed
12894193326Sed  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12895221345Sdim                                                   AsmString, StartLoc,
12896221345Sdim                                                   EndLoc);
12897195341Sed  CurContext->addDecl(New);
12898212904Sdim  return New;
12899193326Sed}
12900193576Sed
12901234353SdimDeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12902234353Sdim                                   SourceLocation ImportLoc,
12903234353Sdim                                   ModuleIdPath Path) {
12904234353Sdim  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12905234353Sdim                                                Module::AllVisible,
12906234353Sdim                                                /*IsIncludeDirective=*/false);
12907234353Sdim  if (!Mod)
12908226633Sdim    return true;
12909226633Sdim
12910249423Sdim  SmallVector<SourceLocation, 2> IdentifierLocs;
12911234353Sdim  Module *ModCheck = Mod;
12912234353Sdim  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12913234353Sdim    // If we've run out of module parents, just drop the remaining identifiers.
12914234353Sdim    // We need the length to be consistent.
12915234353Sdim    if (!ModCheck)
12916234353Sdim      break;
12917234353Sdim    ModCheck = ModCheck->Parent;
12918234353Sdim
12919234353Sdim    IdentifierLocs.push_back(Path[I].second);
12920234353Sdim  }
12921234353Sdim
12922234353Sdim  ImportDecl *Import = ImportDecl::Create(Context,
12923234353Sdim                                          Context.getTranslationUnitDecl(),
12924234353Sdim                                          AtLoc.isValid()? AtLoc : ImportLoc,
12925234353Sdim                                          Mod, IdentifierLocs);
12926234353Sdim  Context.getTranslationUnitDecl()->addDecl(Import);
12927234353Sdim  return Import;
12928226633Sdim}
12929226633Sdim
12930263508Sdimvoid Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12931263508Sdim  // FIXME: Should we synthesize an ImportDecl here?
12932263508Sdim  PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12933263508Sdim                                         /*Complain=*/true);
12934263508Sdim}
12935263508Sdim
12936249423Sdimvoid Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12937249423Sdim  // Create the implicit import declaration.
12938249423Sdim  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12939249423Sdim  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12940249423Sdim                                                   Loc, Mod, Loc);
12941249423Sdim  TU->addDecl(ImportD);
12942249423Sdim  Consumer.HandleImplicitImportDecl(ImportD);
12943249423Sdim
12944249423Sdim  // Make the module visible.
12945249423Sdim  PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12946249423Sdim                                         /*Complain=*/false);
12947249423Sdim}
12948249423Sdim
12949234353Sdimvoid Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12950234353Sdim                                      IdentifierInfo* AliasName,
12951234353Sdim                                      SourceLocation PragmaLoc,
12952234353Sdim                                      SourceLocation NameLoc,
12953234353Sdim                                      SourceLocation AliasNameLoc) {
12954234353Sdim  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12955234353Sdim                                    LookupOrdinaryName);
12956234353Sdim  AsmLabelAttr *Attr =
12957234353Sdim     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
12958234353Sdim
12959234353Sdim  if (PrevDecl)
12960234353Sdim    PrevDecl->addAttr(Attr);
12961234353Sdim  else
12962234353Sdim    (void)ExtnameUndeclaredIdentifiers.insert(
12963234353Sdim      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12964226633Sdim}
12965226633Sdim
12966193576Sedvoid Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12967193576Sed                             SourceLocation PragmaLoc,
12968193576Sed                             SourceLocation NameLoc) {
12969207619Srdivacky  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
12970193576Sed
12971193576Sed  if (PrevDecl) {
12972212904Sdim    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
12973198092Srdivacky  } else {
12974198092Srdivacky    (void)WeakUndeclaredIdentifiers.insert(
12975198092Srdivacky      std::pair<IdentifierInfo*,WeakInfo>
12976198092Srdivacky        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
12977193576Sed  }
12978193576Sed}
12979193576Sed
12980193576Sedvoid Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12981193576Sed                                IdentifierInfo* AliasName,
12982193576Sed                                SourceLocation PragmaLoc,
12983193576Sed                                SourceLocation NameLoc,
12984193576Sed                                SourceLocation AliasNameLoc) {
12985207619Srdivacky  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12986207619Srdivacky                                    LookupOrdinaryName);
12987198092Srdivacky  WeakInfo W = WeakInfo(Name, NameLoc);
12988193576Sed
12989193576Sed  if (PrevDecl) {
12990198092Srdivacky    if (!PrevDecl->hasAttr<AliasAttr>())
12991198092Srdivacky      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
12992198092Srdivacky        DeclApplyPragmaWeak(TUScope, ND, W);
12993198092Srdivacky  } else {
12994198092Srdivacky    (void)WeakUndeclaredIdentifiers.insert(
12995198092Srdivacky      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
12996193576Sed  }
12997193576Sed}
12998226633Sdim
12999226633SdimDecl *Sema::getObjCDeclContext() const {
13000226633Sdim  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13001226633Sdim}
13002226633Sdim
13003226633SdimAvailabilityResult Sema::getCurContextAvailability() const {
13004243830Sdim  const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13005226633Sdim  return D->getAvailability();
13006226633Sdim}
13007