SemaDecl.cpp revision 5ea6ef490547917426d5e2ed14c9f36521bbeacf
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CommentDiagnostic.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33#include "clang/Parse/ParseDiagnostic.h"
34#include "clang/Sema/CXXFieldCollector.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/DelayedDiagnostic.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/Triple.h"
44#include <algorithm>
45#include <cstring>
46#include <functional>
47using namespace clang;
48using namespace sema;
49
50Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51  if (OwnedType) {
52    Decl *Group[2] = { OwnedType, Ptr };
53    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54  }
55
56  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57}
58
59namespace {
60
61class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62 public:
63  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64      : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
65    WantExpressionKeywords = false;
66    WantCXXNamedCasts = false;
67    WantRemainingKeywords = false;
68  }
69
70  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71    if (NamedDecl *ND = candidate.getCorrectionDecl())
72      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73          (AllowInvalidDecl || !ND->isInvalidDecl());
74    else
75      return !WantClassName && candidate.isKeyword();
76  }
77
78 private:
79  bool AllowInvalidDecl;
80  bool WantClassName;
81};
82
83}
84
85/// \brief Determine whether the token kind starts a simple-type-specifier.
86bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87  switch (Kind) {
88  // FIXME: Take into account the current language when deciding whether a
89  // token kind is a valid type specifier
90  case tok::kw_short:
91  case tok::kw_long:
92  case tok::kw___int64:
93  case tok::kw___int128:
94  case tok::kw_signed:
95  case tok::kw_unsigned:
96  case tok::kw_void:
97  case tok::kw_char:
98  case tok::kw_int:
99  case tok::kw_half:
100  case tok::kw_float:
101  case tok::kw_double:
102  case tok::kw_wchar_t:
103  case tok::kw_bool:
104  case tok::kw___underlying_type:
105    return true;
106
107  case tok::annot_typename:
108  case tok::kw_char16_t:
109  case tok::kw_char32_t:
110  case tok::kw_typeof:
111  case tok::kw_decltype:
112    return getLangOpts().CPlusPlus;
113
114  default:
115    break;
116  }
117
118  return false;
119}
120
121/// \brief If the identifier refers to a type name within this scope,
122/// return the declaration of that type.
123///
124/// This routine performs ordinary name lookup of the identifier II
125/// within the given scope, with optional C++ scope specifier SS, to
126/// determine whether the name refers to a type. If so, returns an
127/// opaque pointer (actually a QualType) corresponding to that
128/// type. Otherwise, returns NULL.
129///
130/// If name lookup results in an ambiguity, this routine will complain
131/// and then return NULL.
132ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
133                             Scope *S, CXXScopeSpec *SS,
134                             bool isClassName, bool HasTrailingDot,
135                             ParsedType ObjectTypePtr,
136                             bool IsCtorOrDtorName,
137                             bool WantNontrivialTypeSourceInfo,
138                             IdentifierInfo **CorrectedII) {
139  // Determine where we will perform name lookup.
140  DeclContext *LookupCtx = 0;
141  if (ObjectTypePtr) {
142    QualType ObjectType = ObjectTypePtr.get();
143    if (ObjectType->isRecordType())
144      LookupCtx = computeDeclContext(ObjectType);
145  } else if (SS && SS->isNotEmpty()) {
146    LookupCtx = computeDeclContext(*SS, false);
147
148    if (!LookupCtx) {
149      if (isDependentScopeSpecifier(*SS)) {
150        // C++ [temp.res]p3:
151        //   A qualified-id that refers to a type and in which the
152        //   nested-name-specifier depends on a template-parameter (14.6.2)
153        //   shall be prefixed by the keyword typename to indicate that the
154        //   qualified-id denotes a type, forming an
155        //   elaborated-type-specifier (7.1.5.3).
156        //
157        // We therefore do not perform any name lookup if the result would
158        // refer to a member of an unknown specialization.
159        if (!isClassName && !IsCtorOrDtorName)
160          return ParsedType();
161
162        // We know from the grammar that this name refers to a type,
163        // so build a dependent node to describe the type.
164        if (WantNontrivialTypeSourceInfo)
165          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166
167        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168        QualType T =
169          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170                            II, NameLoc);
171
172          return ParsedType::make(T);
173      }
174
175      return ParsedType();
176    }
177
178    if (!LookupCtx->isDependentContext() &&
179        RequireCompleteDeclContext(*SS, LookupCtx))
180      return ParsedType();
181  }
182
183  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184  // lookup for class-names.
185  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186                                      LookupOrdinaryName;
187  LookupResult Result(*this, &II, NameLoc, Kind);
188  if (LookupCtx) {
189    // Perform "qualified" name lookup into the declaration context we
190    // computed, which is either the type of the base of a member access
191    // expression or the declaration context associated with a prior
192    // nested-name-specifier.
193    LookupQualifiedName(Result, LookupCtx);
194
195    if (ObjectTypePtr && Result.empty()) {
196      // C++ [basic.lookup.classref]p3:
197      //   If the unqualified-id is ~type-name, the type-name is looked up
198      //   in the context of the entire postfix-expression. If the type T of
199      //   the object expression is of a class type C, the type-name is also
200      //   looked up in the scope of class C. At least one of the lookups shall
201      //   find a name that refers to (possibly cv-qualified) T.
202      LookupName(Result, S);
203    }
204  } else {
205    // Perform unqualified name lookup.
206    LookupName(Result, S);
207  }
208
209  NamedDecl *IIDecl = 0;
210  switch (Result.getResultKind()) {
211  case LookupResult::NotFound:
212  case LookupResult::NotFoundInCurrentInstantiation:
213    if (CorrectedII) {
214      TypeNameValidatorCCC Validator(true, isClassName);
215      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216                                              Kind, S, SS, Validator);
217      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218      TemplateTy Template;
219      bool MemberOfUnknownSpecialization;
220      UnqualifiedId TemplateName;
221      TemplateName.setIdentifier(NewII, NameLoc);
222      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223      CXXScopeSpec NewSS, *NewSSPtr = SS;
224      if (SS && NNS) {
225        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226        NewSSPtr = &NewSS;
227      }
228      if (Correction && (NNS || NewII != &II) &&
229          // Ignore a correction to a template type as the to-be-corrected
230          // identifier is not a template (typo correction for template names
231          // is handled elsewhere).
232          !(getLangOpts().CPlusPlus && NewSSPtr &&
233            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234                           false, Template, MemberOfUnknownSpecialization))) {
235        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236                                    isClassName, HasTrailingDot, ObjectTypePtr,
237                                    IsCtorOrDtorName,
238                                    WantNontrivialTypeSourceInfo);
239        if (Ty) {
240          std::string CorrectedStr(Correction.getAsString(getLangOpts()));
241          std::string CorrectedQuotedStr(
242              Correction.getQuoted(getLangOpts()));
243          Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
244              << Result.getLookupName() << CorrectedQuotedStr << isClassName
245              << FixItHint::CreateReplacement(SourceRange(NameLoc),
246                                              CorrectedStr);
247          if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
248            Diag(FirstDecl->getLocation(), diag::note_previous_decl)
249              << CorrectedQuotedStr;
250
251          if (SS && NNS)
252            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
253          *CorrectedII = NewII;
254          return Ty;
255        }
256      }
257    }
258    // If typo correction failed or was not performed, fall through
259  case LookupResult::FoundOverloaded:
260  case LookupResult::FoundUnresolvedValue:
261    Result.suppressDiagnostics();
262    return ParsedType();
263
264  case LookupResult::Ambiguous:
265    // Recover from type-hiding ambiguities by hiding the type.  We'll
266    // do the lookup again when looking for an object, and we can
267    // diagnose the error then.  If we don't do this, then the error
268    // about hiding the type will be immediately followed by an error
269    // that only makes sense if the identifier was treated like a type.
270    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
271      Result.suppressDiagnostics();
272      return ParsedType();
273    }
274
275    // Look to see if we have a type anywhere in the list of results.
276    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
277         Res != ResEnd; ++Res) {
278      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
279        if (!IIDecl ||
280            (*Res)->getLocation().getRawEncoding() <
281              IIDecl->getLocation().getRawEncoding())
282          IIDecl = *Res;
283      }
284    }
285
286    if (!IIDecl) {
287      // None of the entities we found is a type, so there is no way
288      // to even assume that the result is a type. In this case, don't
289      // complain about the ambiguity. The parser will either try to
290      // perform this lookup again (e.g., as an object name), which
291      // will produce the ambiguity, or will complain that it expected
292      // a type name.
293      Result.suppressDiagnostics();
294      return ParsedType();
295    }
296
297    // We found a type within the ambiguous lookup; diagnose the
298    // ambiguity and then return that type. This might be the right
299    // answer, or it might not be, but it suppresses any attempt to
300    // perform the name lookup again.
301    break;
302
303  case LookupResult::Found:
304    IIDecl = Result.getFoundDecl();
305    break;
306  }
307
308  assert(IIDecl && "Didn't find decl");
309
310  QualType T;
311  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
312    DiagnoseUseOfDecl(IIDecl, NameLoc);
313
314    if (T.isNull())
315      T = Context.getTypeDeclType(TD);
316
317    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
318    // constructor or destructor name (in such a case, the scope specifier
319    // will be attached to the enclosing Expr or Decl node).
320    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
321      if (WantNontrivialTypeSourceInfo) {
322        // Construct a type with type-source information.
323        TypeLocBuilder Builder;
324        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
325
326        T = getElaboratedType(ETK_None, *SS, T);
327        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
328        ElabTL.setElaboratedKeywordLoc(SourceLocation());
329        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
330        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
331      } else {
332        T = getElaboratedType(ETK_None, *SS, T);
333      }
334    }
335  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
336    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
337    if (!HasTrailingDot)
338      T = Context.getObjCInterfaceType(IDecl);
339  }
340
341  if (T.isNull()) {
342    // If it's not plausibly a type, suppress diagnostics.
343    Result.suppressDiagnostics();
344    return ParsedType();
345  }
346  return ParsedType::make(T);
347}
348
349/// isTagName() - This method is called *for error recovery purposes only*
350/// to determine if the specified name is a valid tag name ("struct foo").  If
351/// so, this returns the TST for the tag corresponding to it (TST_enum,
352/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
353/// cases in C where the user forgot to specify the tag.
354DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
355  // Do a tag name lookup in this scope.
356  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
357  LookupName(R, S, false);
358  R.suppressDiagnostics();
359  if (R.getResultKind() == LookupResult::Found)
360    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
361      switch (TD->getTagKind()) {
362      case TTK_Struct: return DeclSpec::TST_struct;
363      case TTK_Interface: return DeclSpec::TST_interface;
364      case TTK_Union:  return DeclSpec::TST_union;
365      case TTK_Class:  return DeclSpec::TST_class;
366      case TTK_Enum:   return DeclSpec::TST_enum;
367      }
368    }
369
370  return DeclSpec::TST_unspecified;
371}
372
373/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
374/// if a CXXScopeSpec's type is equal to the type of one of the base classes
375/// then downgrade the missing typename error to a warning.
376/// This is needed for MSVC compatibility; Example:
377/// @code
378/// template<class T> class A {
379/// public:
380///   typedef int TYPE;
381/// };
382/// template<class T> class B : public A<T> {
383/// public:
384///   A<T>::TYPE a; // no typename required because A<T> is a base class.
385/// };
386/// @endcode
387bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
388  if (CurContext->isRecord()) {
389    const Type *Ty = SS->getScopeRep()->getAsType();
390
391    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
392    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
393          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
394      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
395        return true;
396    return S->isFunctionPrototypeScope();
397  }
398  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
399}
400
401bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
402                                   SourceLocation IILoc,
403                                   Scope *S,
404                                   CXXScopeSpec *SS,
405                                   ParsedType &SuggestedType) {
406  // We don't have anything to suggest (yet).
407  SuggestedType = ParsedType();
408
409  // There may have been a typo in the name of the type. Look up typo
410  // results, in case we have something that we can suggest.
411  TypeNameValidatorCCC Validator(false);
412  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
413                                             LookupOrdinaryName, S, SS,
414                                             Validator)) {
415    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
416    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
417
418    if (Corrected.isKeyword()) {
419      // We corrected to a keyword.
420      IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
421      if (!isSimpleTypeSpecifier(NewII->getTokenID()))
422        CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
423      Diag(IILoc, diag::err_unknown_typename_suggest)
424        << II << CorrectedQuotedStr
425        << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
426      II = NewII;
427    } else {
428      NamedDecl *Result = Corrected.getCorrectionDecl();
429      // We found a similarly-named type or interface; suggest that.
430      if (!SS || !SS->isSet())
431        Diag(IILoc, diag::err_unknown_typename_suggest)
432          << II << CorrectedQuotedStr
433          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
434      else if (DeclContext *DC = computeDeclContext(*SS, false))
435        Diag(IILoc, diag::err_unknown_nested_typename_suggest)
436          << II << DC << CorrectedQuotedStr << SS->getRange()
437          << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
438                                          CorrectedStr);
439      else
440        llvm_unreachable("could not have corrected a typo here");
441
442      Diag(Result->getLocation(), diag::note_previous_decl)
443        << CorrectedQuotedStr;
444
445      SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
446                                  false, false, ParsedType(),
447                                  /*IsCtorOrDtorName=*/false,
448                                  /*NonTrivialTypeSourceInfo=*/true);
449    }
450    return true;
451  }
452
453  if (getLangOpts().CPlusPlus) {
454    // See if II is a class template that the user forgot to pass arguments to.
455    UnqualifiedId Name;
456    Name.setIdentifier(II, IILoc);
457    CXXScopeSpec EmptySS;
458    TemplateTy TemplateResult;
459    bool MemberOfUnknownSpecialization;
460    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
461                       Name, ParsedType(), true, TemplateResult,
462                       MemberOfUnknownSpecialization) == TNK_Type_template) {
463      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
464      Diag(IILoc, diag::err_template_missing_args) << TplName;
465      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
466        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
467          << TplDecl->getTemplateParameters()->getSourceRange();
468      }
469      return true;
470    }
471  }
472
473  // FIXME: Should we move the logic that tries to recover from a missing tag
474  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
475
476  if (!SS || (!SS->isSet() && !SS->isInvalid()))
477    Diag(IILoc, diag::err_unknown_typename) << II;
478  else if (DeclContext *DC = computeDeclContext(*SS, false))
479    Diag(IILoc, diag::err_typename_nested_not_found)
480      << II << DC << SS->getRange();
481  else if (isDependentScopeSpecifier(*SS)) {
482    unsigned DiagID = diag::err_typename_missing;
483    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
484      DiagID = diag::warn_typename_missing;
485
486    Diag(SS->getRange().getBegin(), DiagID)
487      << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
488      << SourceRange(SS->getRange().getBegin(), IILoc)
489      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
490    SuggestedType = ActOnTypenameType(S, SourceLocation(),
491                                      *SS, *II, IILoc).get();
492  } else {
493    assert(SS && SS->isInvalid() &&
494           "Invalid scope specifier has already been diagnosed");
495  }
496
497  return true;
498}
499
500/// \brief Determine whether the given result set contains either a type name
501/// or
502static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
503  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
504                       NextToken.is(tok::less);
505
506  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
507    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
508      return true;
509
510    if (CheckTemplate && isa<TemplateDecl>(*I))
511      return true;
512  }
513
514  return false;
515}
516
517static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
518                                    Scope *S, CXXScopeSpec &SS,
519                                    IdentifierInfo *&Name,
520                                    SourceLocation NameLoc) {
521  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
522  SemaRef.LookupParsedName(R, S, &SS);
523  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
524    const char *TagName = 0;
525    const char *FixItTagName = 0;
526    switch (Tag->getTagKind()) {
527      case TTK_Class:
528        TagName = "class";
529        FixItTagName = "class ";
530        break;
531
532      case TTK_Enum:
533        TagName = "enum";
534        FixItTagName = "enum ";
535        break;
536
537      case TTK_Struct:
538        TagName = "struct";
539        FixItTagName = "struct ";
540        break;
541
542      case TTK_Interface:
543        TagName = "__interface";
544        FixItTagName = "__interface ";
545        break;
546
547      case TTK_Union:
548        TagName = "union";
549        FixItTagName = "union ";
550        break;
551    }
552
553    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
554      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
555      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
556
557    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
558         I != IEnd; ++I)
559      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
560        << Name << TagName;
561
562    // Replace lookup results with just the tag decl.
563    Result.clear(Sema::LookupTagName);
564    SemaRef.LookupParsedName(Result, S, &SS);
565    return true;
566  }
567
568  return false;
569}
570
571/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
572static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
573                                  QualType T, SourceLocation NameLoc) {
574  ASTContext &Context = S.Context;
575
576  TypeLocBuilder Builder;
577  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
578
579  T = S.getElaboratedType(ETK_None, SS, T);
580  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
581  ElabTL.setElaboratedKeywordLoc(SourceLocation());
582  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
583  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
584}
585
586Sema::NameClassification Sema::ClassifyName(Scope *S,
587                                            CXXScopeSpec &SS,
588                                            IdentifierInfo *&Name,
589                                            SourceLocation NameLoc,
590                                            const Token &NextToken,
591                                            bool IsAddressOfOperand,
592                                            CorrectionCandidateCallback *CCC) {
593  DeclarationNameInfo NameInfo(Name, NameLoc);
594  ObjCMethodDecl *CurMethod = getCurMethodDecl();
595
596  if (NextToken.is(tok::coloncolon)) {
597    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
598                                QualType(), false, SS, 0, false);
599
600  }
601
602  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
603  LookupParsedName(Result, S, &SS, !CurMethod);
604
605  // Perform lookup for Objective-C instance variables (including automatically
606  // synthesized instance variables), if we're in an Objective-C method.
607  // FIXME: This lookup really, really needs to be folded in to the normal
608  // unqualified lookup mechanism.
609  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
610    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
611    if (E.get() || E.isInvalid())
612      return E;
613  }
614
615  bool SecondTry = false;
616  bool IsFilteredTemplateName = false;
617
618Corrected:
619  switch (Result.getResultKind()) {
620  case LookupResult::NotFound:
621    // If an unqualified-id is followed by a '(', then we have a function
622    // call.
623    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
624      // In C++, this is an ADL-only call.
625      // FIXME: Reference?
626      if (getLangOpts().CPlusPlus)
627        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
628
629      // C90 6.3.2.2:
630      //   If the expression that precedes the parenthesized argument list in a
631      //   function call consists solely of an identifier, and if no
632      //   declaration is visible for this identifier, the identifier is
633      //   implicitly declared exactly as if, in the innermost block containing
634      //   the function call, the declaration
635      //
636      //     extern int identifier ();
637      //
638      //   appeared.
639      //
640      // We also allow this in C99 as an extension.
641      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
642        Result.addDecl(D);
643        Result.resolveKind();
644        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
645      }
646    }
647
648    // In C, we first see whether there is a tag type by the same name, in
649    // which case it's likely that the user just forget to write "enum",
650    // "struct", or "union".
651    if (!getLangOpts().CPlusPlus && !SecondTry &&
652        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
653      break;
654    }
655
656    // Perform typo correction to determine if there is another name that is
657    // close to this name.
658    if (!SecondTry && CCC) {
659      SecondTry = true;
660      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
661                                                 Result.getLookupKind(), S,
662                                                 &SS, *CCC)) {
663        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
664        unsigned QualifiedDiag = diag::err_no_member_suggest;
665        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
666        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
667
668        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
669        NamedDecl *UnderlyingFirstDecl
670          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
671        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
673          UnqualifiedDiag = diag::err_no_template_suggest;
674          QualifiedDiag = diag::err_no_member_template_suggest;
675        } else if (UnderlyingFirstDecl &&
676                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
677                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
678                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
679           UnqualifiedDiag = diag::err_unknown_typename_suggest;
680           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
681         }
682
683        if (SS.isEmpty())
684          Diag(NameLoc, UnqualifiedDiag)
685            << Name << CorrectedQuotedStr
686            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
687        else // FIXME: is this even reachable? Test it.
688          Diag(NameLoc, QualifiedDiag)
689            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
690            << SS.getRange()
691            << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
692                                            CorrectedStr);
693
694        // Update the name, so that the caller has the new name.
695        Name = Corrected.getCorrectionAsIdentifierInfo();
696
697        // Typo correction corrected to a keyword.
698        if (Corrected.isKeyword())
699          return Corrected.getCorrectionAsIdentifierInfo();
700
701        // Also update the LookupResult...
702        // FIXME: This should probably go away at some point
703        Result.clear();
704        Result.setLookupName(Corrected.getCorrection());
705        if (FirstDecl) {
706          Result.addDecl(FirstDecl);
707          Diag(FirstDecl->getLocation(), diag::note_previous_decl)
708            << CorrectedQuotedStr;
709        }
710
711        // If we found an Objective-C instance variable, let
712        // LookupInObjCMethod build the appropriate expression to
713        // reference the ivar.
714        // FIXME: This is a gross hack.
715        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
716          Result.clear();
717          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
718          return E;
719        }
720
721        goto Corrected;
722      }
723    }
724
725    // We failed to correct; just fall through and let the parser deal with it.
726    Result.suppressDiagnostics();
727    return NameClassification::Unknown();
728
729  case LookupResult::NotFoundInCurrentInstantiation: {
730    // We performed name lookup into the current instantiation, and there were
731    // dependent bases, so we treat this result the same way as any other
732    // dependent nested-name-specifier.
733
734    // C++ [temp.res]p2:
735    //   A name used in a template declaration or definition and that is
736    //   dependent on a template-parameter is assumed not to name a type
737    //   unless the applicable name lookup finds a type name or the name is
738    //   qualified by the keyword typename.
739    //
740    // FIXME: If the next token is '<', we might want to ask the parser to
741    // perform some heroics to see if we actually have a
742    // template-argument-list, which would indicate a missing 'template'
743    // keyword here.
744    return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
745                                      NameInfo, IsAddressOfOperand,
746                                      /*TemplateArgs=*/0);
747  }
748
749  case LookupResult::Found:
750  case LookupResult::FoundOverloaded:
751  case LookupResult::FoundUnresolvedValue:
752    break;
753
754  case LookupResult::Ambiguous:
755    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
756        hasAnyAcceptableTemplateNames(Result)) {
757      // C++ [temp.local]p3:
758      //   A lookup that finds an injected-class-name (10.2) can result in an
759      //   ambiguity in certain cases (for example, if it is found in more than
760      //   one base class). If all of the injected-class-names that are found
761      //   refer to specializations of the same class template, and if the name
762      //   is followed by a template-argument-list, the reference refers to the
763      //   class template itself and not a specialization thereof, and is not
764      //   ambiguous.
765      //
766      // This filtering can make an ambiguous result into an unambiguous one,
767      // so try again after filtering out template names.
768      FilterAcceptableTemplateNames(Result);
769      if (!Result.isAmbiguous()) {
770        IsFilteredTemplateName = true;
771        break;
772      }
773    }
774
775    // Diagnose the ambiguity and return an error.
776    return NameClassification::Error();
777  }
778
779  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
780      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
781    // C++ [temp.names]p3:
782    //   After name lookup (3.4) finds that a name is a template-name or that
783    //   an operator-function-id or a literal- operator-id refers to a set of
784    //   overloaded functions any member of which is a function template if
785    //   this is followed by a <, the < is always taken as the delimiter of a
786    //   template-argument-list and never as the less-than operator.
787    if (!IsFilteredTemplateName)
788      FilterAcceptableTemplateNames(Result);
789
790    if (!Result.empty()) {
791      bool IsFunctionTemplate;
792      TemplateName Template;
793      if (Result.end() - Result.begin() > 1) {
794        IsFunctionTemplate = true;
795        Template = Context.getOverloadedTemplateName(Result.begin(),
796                                                     Result.end());
797      } else {
798        TemplateDecl *TD
799          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
800        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
801
802        if (SS.isSet() && !SS.isInvalid())
803          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
804                                                    /*TemplateKeyword=*/false,
805                                                      TD);
806        else
807          Template = TemplateName(TD);
808      }
809
810      if (IsFunctionTemplate) {
811        // Function templates always go through overload resolution, at which
812        // point we'll perform the various checks (e.g., accessibility) we need
813        // to based on which function we selected.
814        Result.suppressDiagnostics();
815
816        return NameClassification::FunctionTemplate(Template);
817      }
818
819      return NameClassification::TypeTemplate(Template);
820    }
821  }
822
823  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
824  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
825    DiagnoseUseOfDecl(Type, NameLoc);
826    QualType T = Context.getTypeDeclType(Type);
827    if (SS.isNotEmpty())
828      return buildNestedType(*this, SS, T, NameLoc);
829    return ParsedType::make(T);
830  }
831
832  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
833  if (!Class) {
834    // FIXME: It's unfortunate that we don't have a Type node for handling this.
835    if (ObjCCompatibleAliasDecl *Alias
836                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
837      Class = Alias->getClassInterface();
838  }
839
840  if (Class) {
841    DiagnoseUseOfDecl(Class, NameLoc);
842
843    if (NextToken.is(tok::period)) {
844      // Interface. <something> is parsed as a property reference expression.
845      // Just return "unknown" as a fall-through for now.
846      Result.suppressDiagnostics();
847      return NameClassification::Unknown();
848    }
849
850    QualType T = Context.getObjCInterfaceType(Class);
851    return ParsedType::make(T);
852  }
853
854  // We can have a type template here if we're classifying a template argument.
855  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
856    return NameClassification::TypeTemplate(
857        TemplateName(cast<TemplateDecl>(FirstDecl)));
858
859  // Check for a tag type hidden by a non-type decl in a few cases where it
860  // seems likely a type is wanted instead of the non-type that was found.
861  if (!getLangOpts().ObjC1) {
862    bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
863    if ((NextToken.is(tok::identifier) ||
864         (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
865        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
866      TypeDecl *Type = Result.getAsSingle<TypeDecl>();
867      DiagnoseUseOfDecl(Type, NameLoc);
868      QualType T = Context.getTypeDeclType(Type);
869      if (SS.isNotEmpty())
870        return buildNestedType(*this, SS, T, NameLoc);
871      return ParsedType::make(T);
872    }
873  }
874
875  if (FirstDecl->isCXXClassMember())
876    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
877
878  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
879  return BuildDeclarationNameExpr(SS, Result, ADL);
880}
881
882// Determines the context to return to after temporarily entering a
883// context.  This depends in an unnecessarily complicated way on the
884// exact ordering of callbacks from the parser.
885DeclContext *Sema::getContainingDC(DeclContext *DC) {
886
887  // Functions defined inline within classes aren't parsed until we've
888  // finished parsing the top-level class, so the top-level class is
889  // the context we'll need to return to.
890  if (isa<FunctionDecl>(DC)) {
891    DC = DC->getLexicalParent();
892
893    // A function not defined within a class will always return to its
894    // lexical context.
895    if (!isa<CXXRecordDecl>(DC))
896      return DC;
897
898    // A C++ inline method/friend is parsed *after* the topmost class
899    // it was declared in is fully parsed ("complete");  the topmost
900    // class is the context we need to return to.
901    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
902      DC = RD;
903
904    // Return the declaration context of the topmost class the inline method is
905    // declared in.
906    return DC;
907  }
908
909  return DC->getLexicalParent();
910}
911
912void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
913  assert(getContainingDC(DC) == CurContext &&
914      "The next DeclContext should be lexically contained in the current one.");
915  CurContext = DC;
916  S->setEntity(DC);
917}
918
919void Sema::PopDeclContext() {
920  assert(CurContext && "DeclContext imbalance!");
921
922  CurContext = getContainingDC(CurContext);
923  assert(CurContext && "Popped translation unit!");
924}
925
926/// EnterDeclaratorContext - Used when we must lookup names in the context
927/// of a declarator's nested name specifier.
928///
929void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
930  // C++0x [basic.lookup.unqual]p13:
931  //   A name used in the definition of a static data member of class
932  //   X (after the qualified-id of the static member) is looked up as
933  //   if the name was used in a member function of X.
934  // C++0x [basic.lookup.unqual]p14:
935  //   If a variable member of a namespace is defined outside of the
936  //   scope of its namespace then any name used in the definition of
937  //   the variable member (after the declarator-id) is looked up as
938  //   if the definition of the variable member occurred in its
939  //   namespace.
940  // Both of these imply that we should push a scope whose context
941  // is the semantic context of the declaration.  We can't use
942  // PushDeclContext here because that context is not necessarily
943  // lexically contained in the current context.  Fortunately,
944  // the containing scope should have the appropriate information.
945
946  assert(!S->getEntity() && "scope already has entity");
947
948#ifndef NDEBUG
949  Scope *Ancestor = S->getParent();
950  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
951  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
952#endif
953
954  CurContext = DC;
955  S->setEntity(DC);
956}
957
958void Sema::ExitDeclaratorContext(Scope *S) {
959  assert(S->getEntity() == CurContext && "Context imbalance!");
960
961  // Switch back to the lexical context.  The safety of this is
962  // enforced by an assert in EnterDeclaratorContext.
963  Scope *Ancestor = S->getParent();
964  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
965  CurContext = (DeclContext*) Ancestor->getEntity();
966
967  // We don't need to do anything with the scope, which is going to
968  // disappear.
969}
970
971
972void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
973  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
974  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
975    // We assume that the caller has already called
976    // ActOnReenterTemplateScope
977    FD = TFD->getTemplatedDecl();
978  }
979  if (!FD)
980    return;
981
982  // Same implementation as PushDeclContext, but enters the context
983  // from the lexical parent, rather than the top-level class.
984  assert(CurContext == FD->getLexicalParent() &&
985    "The next DeclContext should be lexically contained in the current one.");
986  CurContext = FD;
987  S->setEntity(CurContext);
988
989  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
990    ParmVarDecl *Param = FD->getParamDecl(P);
991    // If the parameter has an identifier, then add it to the scope
992    if (Param->getIdentifier()) {
993      S->AddDecl(Param);
994      IdResolver.AddDecl(Param);
995    }
996  }
997}
998
999
1000void Sema::ActOnExitFunctionContext() {
1001  // Same implementation as PopDeclContext, but returns to the lexical parent,
1002  // rather than the top-level class.
1003  assert(CurContext && "DeclContext imbalance!");
1004  CurContext = CurContext->getLexicalParent();
1005  assert(CurContext && "Popped translation unit!");
1006}
1007
1008
1009/// \brief Determine whether we allow overloading of the function
1010/// PrevDecl with another declaration.
1011///
1012/// This routine determines whether overloading is possible, not
1013/// whether some new function is actually an overload. It will return
1014/// true in C++ (where we can always provide overloads) or, as an
1015/// extension, in C when the previous function is already an
1016/// overloaded function declaration or has the "overloadable"
1017/// attribute.
1018static bool AllowOverloadingOfFunction(LookupResult &Previous,
1019                                       ASTContext &Context) {
1020  if (Context.getLangOpts().CPlusPlus)
1021    return true;
1022
1023  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1024    return true;
1025
1026  return (Previous.getResultKind() == LookupResult::Found
1027          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1028}
1029
1030/// Add this decl to the scope shadowed decl chains.
1031void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1032  // Move up the scope chain until we find the nearest enclosing
1033  // non-transparent context. The declaration will be introduced into this
1034  // scope.
1035  while (S->getEntity() &&
1036         ((DeclContext *)S->getEntity())->isTransparentContext())
1037    S = S->getParent();
1038
1039  // Add scoped declarations into their context, so that they can be
1040  // found later. Declarations without a context won't be inserted
1041  // into any context.
1042  if (AddToContext)
1043    CurContext->addDecl(D);
1044
1045  // Out-of-line definitions shouldn't be pushed into scope in C++.
1046  // Out-of-line variable and function definitions shouldn't even in C.
1047  if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
1048      D->isOutOfLine() &&
1049      !D->getDeclContext()->getRedeclContext()->Equals(
1050        D->getLexicalDeclContext()->getRedeclContext()))
1051    return;
1052
1053  // Template instantiations should also not be pushed into scope.
1054  if (isa<FunctionDecl>(D) &&
1055      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1056    return;
1057
1058  // If this replaces anything in the current scope,
1059  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1060                               IEnd = IdResolver.end();
1061  for (; I != IEnd; ++I) {
1062    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1063      S->RemoveDecl(*I);
1064      IdResolver.RemoveDecl(*I);
1065
1066      // Should only need to replace one decl.
1067      break;
1068    }
1069  }
1070
1071  S->AddDecl(D);
1072
1073  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1074    // Implicitly-generated labels may end up getting generated in an order that
1075    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1076    // the label at the appropriate place in the identifier chain.
1077    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1078      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1079      if (IDC == CurContext) {
1080        if (!S->isDeclScope(*I))
1081          continue;
1082      } else if (IDC->Encloses(CurContext))
1083        break;
1084    }
1085
1086    IdResolver.InsertDeclAfter(I, D);
1087  } else {
1088    IdResolver.AddDecl(D);
1089  }
1090}
1091
1092void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1093  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1094    TUScope->AddDecl(D);
1095}
1096
1097bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1098                         bool ExplicitInstantiationOrSpecialization) {
1099  return IdResolver.isDeclInScope(D, Ctx, S,
1100                                  ExplicitInstantiationOrSpecialization);
1101}
1102
1103Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1104  DeclContext *TargetDC = DC->getPrimaryContext();
1105  do {
1106    if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1107      if (ScopeDC->getPrimaryContext() == TargetDC)
1108        return S;
1109  } while ((S = S->getParent()));
1110
1111  return 0;
1112}
1113
1114static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1115                                            DeclContext*,
1116                                            ASTContext&);
1117
1118/// Filters out lookup results that don't fall within the given scope
1119/// as determined by isDeclInScope.
1120void Sema::FilterLookupForScope(LookupResult &R,
1121                                DeclContext *Ctx, Scope *S,
1122                                bool ConsiderLinkage,
1123                                bool ExplicitInstantiationOrSpecialization) {
1124  LookupResult::Filter F = R.makeFilter();
1125  while (F.hasNext()) {
1126    NamedDecl *D = F.next();
1127
1128    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1129      continue;
1130
1131    if (ConsiderLinkage &&
1132        isOutOfScopePreviousDeclaration(D, Ctx, Context))
1133      continue;
1134
1135    F.erase();
1136  }
1137
1138  F.done();
1139}
1140
1141static bool isUsingDecl(NamedDecl *D) {
1142  return isa<UsingShadowDecl>(D) ||
1143         isa<UnresolvedUsingTypenameDecl>(D) ||
1144         isa<UnresolvedUsingValueDecl>(D);
1145}
1146
1147/// Removes using shadow declarations from the lookup results.
1148static void RemoveUsingDecls(LookupResult &R) {
1149  LookupResult::Filter F = R.makeFilter();
1150  while (F.hasNext())
1151    if (isUsingDecl(F.next()))
1152      F.erase();
1153
1154  F.done();
1155}
1156
1157/// \brief Check for this common pattern:
1158/// @code
1159/// class S {
1160///   S(const S&); // DO NOT IMPLEMENT
1161///   void operator=(const S&); // DO NOT IMPLEMENT
1162/// };
1163/// @endcode
1164static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1165  // FIXME: Should check for private access too but access is set after we get
1166  // the decl here.
1167  if (D->doesThisDeclarationHaveABody())
1168    return false;
1169
1170  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1171    return CD->isCopyConstructor();
1172  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1173    return Method->isCopyAssignmentOperator();
1174  return false;
1175}
1176
1177bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1178  assert(D);
1179
1180  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1181    return false;
1182
1183  // Ignore class templates.
1184  if (D->getDeclContext()->isDependentContext() ||
1185      D->getLexicalDeclContext()->isDependentContext())
1186    return false;
1187
1188  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1189    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1190      return false;
1191
1192    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1193      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1194        return false;
1195    } else {
1196      // 'static inline' functions are used in headers; don't warn.
1197      if (FD->getStorageClass() == SC_Static &&
1198          FD->isInlineSpecified())
1199        return false;
1200    }
1201
1202    if (FD->doesThisDeclarationHaveABody() &&
1203        Context.DeclMustBeEmitted(FD))
1204      return false;
1205  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1206    // Don't warn on variables of const-qualified or reference type, since their
1207    // values can be used even if though they're not odr-used, and because const
1208    // qualified variables can appear in headers in contexts where they're not
1209    // intended to be used.
1210    // FIXME: Use more principled rules for these exemptions.
1211    if (!VD->isFileVarDecl() ||
1212        VD->getType().isConstQualified() ||
1213        VD->getType()->isReferenceType() ||
1214        Context.DeclMustBeEmitted(VD))
1215      return false;
1216
1217    if (VD->isStaticDataMember() &&
1218        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1219      return false;
1220
1221  } else {
1222    return false;
1223  }
1224
1225  // Only warn for unused decls internal to the translation unit.
1226  if (D->getLinkage() == ExternalLinkage)
1227    return false;
1228
1229  return true;
1230}
1231
1232void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1233  if (!D)
1234    return;
1235
1236  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1237    const FunctionDecl *First = FD->getFirstDeclaration();
1238    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1239      return; // First should already be in the vector.
1240  }
1241
1242  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1243    const VarDecl *First = VD->getFirstDeclaration();
1244    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1245      return; // First should already be in the vector.
1246  }
1247
1248  if (ShouldWarnIfUnusedFileScopedDecl(D))
1249    UnusedFileScopedDecls.push_back(D);
1250}
1251
1252static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1253  if (D->isInvalidDecl())
1254    return false;
1255
1256  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1257    return false;
1258
1259  if (isa<LabelDecl>(D))
1260    return true;
1261
1262  // White-list anything that isn't a local variable.
1263  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1264      !D->getDeclContext()->isFunctionOrMethod())
1265    return false;
1266
1267  // Types of valid local variables should be complete, so this should succeed.
1268  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1269
1270    // White-list anything with an __attribute__((unused)) type.
1271    QualType Ty = VD->getType();
1272
1273    // Only look at the outermost level of typedef.
1274    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1275      if (TT->getDecl()->hasAttr<UnusedAttr>())
1276        return false;
1277    }
1278
1279    // If we failed to complete the type for some reason, or if the type is
1280    // dependent, don't diagnose the variable.
1281    if (Ty->isIncompleteType() || Ty->isDependentType())
1282      return false;
1283
1284    if (const TagType *TT = Ty->getAs<TagType>()) {
1285      const TagDecl *Tag = TT->getDecl();
1286      if (Tag->hasAttr<UnusedAttr>())
1287        return false;
1288
1289      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1290        if (!RD->hasTrivialDestructor())
1291          return false;
1292
1293        if (const Expr *Init = VD->getInit()) {
1294          if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1295            Init = Cleanups->getSubExpr();
1296          const CXXConstructExpr *Construct =
1297            dyn_cast<CXXConstructExpr>(Init);
1298          if (Construct && !Construct->isElidable()) {
1299            CXXConstructorDecl *CD = Construct->getConstructor();
1300            if (!CD->isTrivial())
1301              return false;
1302          }
1303        }
1304      }
1305    }
1306
1307    // TODO: __attribute__((unused)) templates?
1308  }
1309
1310  return true;
1311}
1312
1313static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1314                                     FixItHint &Hint) {
1315  if (isa<LabelDecl>(D)) {
1316    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1317                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1318    if (AfterColon.isInvalid())
1319      return;
1320    Hint = FixItHint::CreateRemoval(CharSourceRange::
1321                                    getCharRange(D->getLocStart(), AfterColon));
1322  }
1323  return;
1324}
1325
1326/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1327/// unless they are marked attr(unused).
1328void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1329  FixItHint Hint;
1330  if (!ShouldDiagnoseUnusedDecl(D))
1331    return;
1332
1333  GenerateFixForUnusedDecl(D, Context, Hint);
1334
1335  unsigned DiagID;
1336  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1337    DiagID = diag::warn_unused_exception_param;
1338  else if (isa<LabelDecl>(D))
1339    DiagID = diag::warn_unused_label;
1340  else
1341    DiagID = diag::warn_unused_variable;
1342
1343  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1344}
1345
1346static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1347  // Verify that we have no forward references left.  If so, there was a goto
1348  // or address of a label taken, but no definition of it.  Label fwd
1349  // definitions are indicated with a null substmt.
1350  if (L->getStmt() == 0)
1351    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1352}
1353
1354void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1355  if (S->decl_empty()) return;
1356  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1357         "Scope shouldn't contain decls!");
1358
1359  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1360       I != E; ++I) {
1361    Decl *TmpD = (*I);
1362    assert(TmpD && "This decl didn't get pushed??");
1363
1364    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1365    NamedDecl *D = cast<NamedDecl>(TmpD);
1366
1367    if (!D->getDeclName()) continue;
1368
1369    // Diagnose unused variables in this scope.
1370    if (!S->hasErrorOccurred())
1371      DiagnoseUnusedDecl(D);
1372
1373    // If this was a forward reference to a label, verify it was defined.
1374    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1375      CheckPoppedLabel(LD, *this);
1376
1377    // Remove this name from our lexical scope.
1378    IdResolver.RemoveDecl(D);
1379  }
1380}
1381
1382void Sema::ActOnStartFunctionDeclarator() {
1383  ++InFunctionDeclarator;
1384}
1385
1386void Sema::ActOnEndFunctionDeclarator() {
1387  assert(InFunctionDeclarator);
1388  --InFunctionDeclarator;
1389}
1390
1391/// \brief Look for an Objective-C class in the translation unit.
1392///
1393/// \param Id The name of the Objective-C class we're looking for. If
1394/// typo-correction fixes this name, the Id will be updated
1395/// to the fixed name.
1396///
1397/// \param IdLoc The location of the name in the translation unit.
1398///
1399/// \param DoTypoCorrection If true, this routine will attempt typo correction
1400/// if there is no class with the given name.
1401///
1402/// \returns The declaration of the named Objective-C class, or NULL if the
1403/// class could not be found.
1404ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1405                                              SourceLocation IdLoc,
1406                                              bool DoTypoCorrection) {
1407  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1408  // creation from this context.
1409  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1410
1411  if (!IDecl && DoTypoCorrection) {
1412    // Perform typo correction at the given location, but only if we
1413    // find an Objective-C class name.
1414    DeclFilterCCC<ObjCInterfaceDecl> Validator;
1415    if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1416                                       LookupOrdinaryName, TUScope, NULL,
1417                                       Validator)) {
1418      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1419      Diag(IdLoc, diag::err_undef_interface_suggest)
1420        << Id << IDecl->getDeclName()
1421        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1422      Diag(IDecl->getLocation(), diag::note_previous_decl)
1423        << IDecl->getDeclName();
1424
1425      Id = IDecl->getIdentifier();
1426    }
1427  }
1428  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1429  // This routine must always return a class definition, if any.
1430  if (Def && Def->getDefinition())
1431      Def = Def->getDefinition();
1432  return Def;
1433}
1434
1435/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1436/// from S, where a non-field would be declared. This routine copes
1437/// with the difference between C and C++ scoping rules in structs and
1438/// unions. For example, the following code is well-formed in C but
1439/// ill-formed in C++:
1440/// @code
1441/// struct S6 {
1442///   enum { BAR } e;
1443/// };
1444///
1445/// void test_S6() {
1446///   struct S6 a;
1447///   a.e = BAR;
1448/// }
1449/// @endcode
1450/// For the declaration of BAR, this routine will return a different
1451/// scope. The scope S will be the scope of the unnamed enumeration
1452/// within S6. In C++, this routine will return the scope associated
1453/// with S6, because the enumeration's scope is a transparent
1454/// context but structures can contain non-field names. In C, this
1455/// routine will return the translation unit scope, since the
1456/// enumeration's scope is a transparent context and structures cannot
1457/// contain non-field names.
1458Scope *Sema::getNonFieldDeclScope(Scope *S) {
1459  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1460         (S->getEntity() &&
1461          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1462         (S->isClassScope() && !getLangOpts().CPlusPlus))
1463    S = S->getParent();
1464  return S;
1465}
1466
1467/// \brief Looks up the declaration of "struct objc_super" and
1468/// saves it for later use in building builtin declaration of
1469/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1470/// pre-existing declaration exists no action takes place.
1471static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1472                                        IdentifierInfo *II) {
1473  if (!II->isStr("objc_msgSendSuper"))
1474    return;
1475  ASTContext &Context = ThisSema.Context;
1476
1477  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1478                      SourceLocation(), Sema::LookupTagName);
1479  ThisSema.LookupName(Result, S);
1480  if (Result.getResultKind() == LookupResult::Found)
1481    if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1482      Context.setObjCSuperType(Context.getTagDeclType(TD));
1483}
1484
1485/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1486/// file scope.  lazily create a decl for it. ForRedeclaration is true
1487/// if we're creating this built-in in anticipation of redeclaring the
1488/// built-in.
1489NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1490                                     Scope *S, bool ForRedeclaration,
1491                                     SourceLocation Loc) {
1492  LookupPredefedObjCSuperType(*this, S, II);
1493
1494  Builtin::ID BID = (Builtin::ID)bid;
1495
1496  ASTContext::GetBuiltinTypeError Error;
1497  QualType R = Context.GetBuiltinType(BID, Error);
1498  switch (Error) {
1499  case ASTContext::GE_None:
1500    // Okay
1501    break;
1502
1503  case ASTContext::GE_Missing_stdio:
1504    if (ForRedeclaration)
1505      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1506        << Context.BuiltinInfo.GetName(BID);
1507    return 0;
1508
1509  case ASTContext::GE_Missing_setjmp:
1510    if (ForRedeclaration)
1511      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1512        << Context.BuiltinInfo.GetName(BID);
1513    return 0;
1514
1515  case ASTContext::GE_Missing_ucontext:
1516    if (ForRedeclaration)
1517      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1518        << Context.BuiltinInfo.GetName(BID);
1519    return 0;
1520  }
1521
1522  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1523    Diag(Loc, diag::ext_implicit_lib_function_decl)
1524      << Context.BuiltinInfo.GetName(BID)
1525      << R;
1526    if (Context.BuiltinInfo.getHeaderName(BID) &&
1527        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1528          != DiagnosticsEngine::Ignored)
1529      Diag(Loc, diag::note_please_include_header)
1530        << Context.BuiltinInfo.getHeaderName(BID)
1531        << Context.BuiltinInfo.GetName(BID);
1532  }
1533
1534  FunctionDecl *New = FunctionDecl::Create(Context,
1535                                           Context.getTranslationUnitDecl(),
1536                                           Loc, Loc, II, R, /*TInfo=*/0,
1537                                           SC_Extern,
1538                                           SC_None, false,
1539                                           /*hasPrototype=*/true);
1540  New->setImplicit();
1541
1542  // Create Decl objects for each parameter, adding them to the
1543  // FunctionDecl.
1544  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1545    SmallVector<ParmVarDecl*, 16> Params;
1546    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1547      ParmVarDecl *parm =
1548        ParmVarDecl::Create(Context, New, SourceLocation(),
1549                            SourceLocation(), 0,
1550                            FT->getArgType(i), /*TInfo=*/0,
1551                            SC_None, SC_None, 0);
1552      parm->setScopeInfo(0, i);
1553      Params.push_back(parm);
1554    }
1555    New->setParams(Params);
1556  }
1557
1558  AddKnownFunctionAttributes(New);
1559
1560  // TUScope is the translation-unit scope to insert this function into.
1561  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1562  // relate Scopes to DeclContexts, and probably eliminate CurContext
1563  // entirely, but we're not there yet.
1564  DeclContext *SavedContext = CurContext;
1565  CurContext = Context.getTranslationUnitDecl();
1566  PushOnScopeChains(New, TUScope);
1567  CurContext = SavedContext;
1568  return New;
1569}
1570
1571/// \brief Filter out any previous declarations that the given declaration
1572/// should not consider because they are not permitted to conflict, e.g.,
1573/// because they come from hidden sub-modules and do not refer to the same
1574/// entity.
1575static void filterNonConflictingPreviousDecls(ASTContext &context,
1576                                              NamedDecl *decl,
1577                                              LookupResult &previous){
1578  // This is only interesting when modules are enabled.
1579  if (!context.getLangOpts().Modules)
1580    return;
1581
1582  // Empty sets are uninteresting.
1583  if (previous.empty())
1584    return;
1585
1586  // If this declaration has external
1587  bool hasExternalLinkage = (decl->getLinkage() == ExternalLinkage);
1588
1589  LookupResult::Filter filter = previous.makeFilter();
1590  while (filter.hasNext()) {
1591    NamedDecl *old = filter.next();
1592
1593    // Non-hidden declarations are never ignored.
1594    if (!old->isHidden())
1595      continue;
1596
1597    // If either has no-external linkage, ignore the old declaration.
1598    if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage)
1599      filter.erase();
1600  }
1601
1602  filter.done();
1603}
1604
1605bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1606  QualType OldType;
1607  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1608    OldType = OldTypedef->getUnderlyingType();
1609  else
1610    OldType = Context.getTypeDeclType(Old);
1611  QualType NewType = New->getUnderlyingType();
1612
1613  if (NewType->isVariablyModifiedType()) {
1614    // Must not redefine a typedef with a variably-modified type.
1615    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1616    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1617      << Kind << NewType;
1618    if (Old->getLocation().isValid())
1619      Diag(Old->getLocation(), diag::note_previous_definition);
1620    New->setInvalidDecl();
1621    return true;
1622  }
1623
1624  if (OldType != NewType &&
1625      !OldType->isDependentType() &&
1626      !NewType->isDependentType() &&
1627      !Context.hasSameType(OldType, NewType)) {
1628    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1629    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1630      << Kind << NewType << OldType;
1631    if (Old->getLocation().isValid())
1632      Diag(Old->getLocation(), diag::note_previous_definition);
1633    New->setInvalidDecl();
1634    return true;
1635  }
1636  return false;
1637}
1638
1639/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1640/// same name and scope as a previous declaration 'Old'.  Figure out
1641/// how to resolve this situation, merging decls or emitting
1642/// diagnostics as appropriate. If there was an error, set New to be invalid.
1643///
1644void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1645  // If the new decl is known invalid already, don't bother doing any
1646  // merging checks.
1647  if (New->isInvalidDecl()) return;
1648
1649  // Allow multiple definitions for ObjC built-in typedefs.
1650  // FIXME: Verify the underlying types are equivalent!
1651  if (getLangOpts().ObjC1) {
1652    const IdentifierInfo *TypeID = New->getIdentifier();
1653    switch (TypeID->getLength()) {
1654    default: break;
1655    case 2:
1656      {
1657        if (!TypeID->isStr("id"))
1658          break;
1659        QualType T = New->getUnderlyingType();
1660        if (!T->isPointerType())
1661          break;
1662        if (!T->isVoidPointerType()) {
1663          QualType PT = T->getAs<PointerType>()->getPointeeType();
1664          if (!PT->isStructureType())
1665            break;
1666        }
1667        Context.setObjCIdRedefinitionType(T);
1668        // Install the built-in type for 'id', ignoring the current definition.
1669        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1670        return;
1671      }
1672    case 5:
1673      if (!TypeID->isStr("Class"))
1674        break;
1675      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1676      // Install the built-in type for 'Class', ignoring the current definition.
1677      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1678      return;
1679    case 3:
1680      if (!TypeID->isStr("SEL"))
1681        break;
1682      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1683      // Install the built-in type for 'SEL', ignoring the current definition.
1684      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1685      return;
1686    }
1687    // Fall through - the typedef name was not a builtin type.
1688  }
1689
1690  // Verify the old decl was also a type.
1691  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1692  if (!Old) {
1693    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1694      << New->getDeclName();
1695
1696    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1697    if (OldD->getLocation().isValid())
1698      Diag(OldD->getLocation(), diag::note_previous_definition);
1699
1700    return New->setInvalidDecl();
1701  }
1702
1703  // If the old declaration is invalid, just give up here.
1704  if (Old->isInvalidDecl())
1705    return New->setInvalidDecl();
1706
1707  // If the typedef types are not identical, reject them in all languages and
1708  // with any extensions enabled.
1709  if (isIncompatibleTypedef(Old, New))
1710    return;
1711
1712  // The types match.  Link up the redeclaration chain if the old
1713  // declaration was a typedef.
1714  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1715    New->setPreviousDeclaration(Typedef);
1716
1717  if (getLangOpts().MicrosoftExt)
1718    return;
1719
1720  if (getLangOpts().CPlusPlus) {
1721    // C++ [dcl.typedef]p2:
1722    //   In a given non-class scope, a typedef specifier can be used to
1723    //   redefine the name of any type declared in that scope to refer
1724    //   to the type to which it already refers.
1725    if (!isa<CXXRecordDecl>(CurContext))
1726      return;
1727
1728    // C++0x [dcl.typedef]p4:
1729    //   In a given class scope, a typedef specifier can be used to redefine
1730    //   any class-name declared in that scope that is not also a typedef-name
1731    //   to refer to the type to which it already refers.
1732    //
1733    // This wording came in via DR424, which was a correction to the
1734    // wording in DR56, which accidentally banned code like:
1735    //
1736    //   struct S {
1737    //     typedef struct A { } A;
1738    //   };
1739    //
1740    // in the C++03 standard. We implement the C++0x semantics, which
1741    // allow the above but disallow
1742    //
1743    //   struct S {
1744    //     typedef int I;
1745    //     typedef int I;
1746    //   };
1747    //
1748    // since that was the intent of DR56.
1749    if (!isa<TypedefNameDecl>(Old))
1750      return;
1751
1752    Diag(New->getLocation(), diag::err_redefinition)
1753      << New->getDeclName();
1754    Diag(Old->getLocation(), diag::note_previous_definition);
1755    return New->setInvalidDecl();
1756  }
1757
1758  // Modules always permit redefinition of typedefs, as does C11.
1759  if (getLangOpts().Modules || getLangOpts().C11)
1760    return;
1761
1762  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1763  // is normally mapped to an error, but can be controlled with
1764  // -Wtypedef-redefinition.  If either the original or the redefinition is
1765  // in a system header, don't emit this for compatibility with GCC.
1766  if (getDiagnostics().getSuppressSystemWarnings() &&
1767      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1768       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1769    return;
1770
1771  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1772    << New->getDeclName();
1773  Diag(Old->getLocation(), diag::note_previous_definition);
1774  return;
1775}
1776
1777/// DeclhasAttr - returns true if decl Declaration already has the target
1778/// attribute.
1779static bool
1780DeclHasAttr(const Decl *D, const Attr *A) {
1781  // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1782  // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1783  // responsible for making sure they are consistent.
1784  const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1785  if (AA)
1786    return false;
1787
1788  // The following thread safety attributes can also be duplicated.
1789  switch (A->getKind()) {
1790    case attr::ExclusiveLocksRequired:
1791    case attr::SharedLocksRequired:
1792    case attr::LocksExcluded:
1793    case attr::ExclusiveLockFunction:
1794    case attr::SharedLockFunction:
1795    case attr::UnlockFunction:
1796    case attr::ExclusiveTrylockFunction:
1797    case attr::SharedTrylockFunction:
1798    case attr::GuardedBy:
1799    case attr::PtGuardedBy:
1800    case attr::AcquiredBefore:
1801    case attr::AcquiredAfter:
1802      return false;
1803    default:
1804      ;
1805  }
1806
1807  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1808  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1809  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1810    if ((*i)->getKind() == A->getKind()) {
1811      if (Ann) {
1812        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1813          return true;
1814        continue;
1815      }
1816      // FIXME: Don't hardcode this check
1817      if (OA && isa<OwnershipAttr>(*i))
1818        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1819      return true;
1820    }
1821
1822  return false;
1823}
1824
1825bool Sema::mergeDeclAttribute(NamedDecl *D, InheritableAttr *Attr) {
1826  InheritableAttr *NewAttr = NULL;
1827  if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) {
1828    NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1829                                    AA->getIntroduced(), AA->getDeprecated(),
1830                                    AA->getObsoleted(), AA->getUnavailable(),
1831                                    AA->getMessage());
1832    if (NewAttr)
1833      D->ClearLVCache();
1834  } else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) {
1835    NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1836    if (NewAttr)
1837      D->ClearLVCache();
1838  } else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1839    NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1840  else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1841    NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1842  else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1843    NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1844                              FA->getFormatIdx(), FA->getFirstArg());
1845  else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1846    NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1847  else if (!DeclHasAttr(D, Attr))
1848    NewAttr = cast<InheritableAttr>(Attr->clone(Context));
1849
1850  if (NewAttr) {
1851    NewAttr->setInherited(true);
1852    D->addAttr(NewAttr);
1853    return true;
1854  }
1855
1856  return false;
1857}
1858
1859static const Decl *getDefinition(const Decl *D) {
1860  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1861    return TD->getDefinition();
1862  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1863    return VD->getDefinition();
1864  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1865    const FunctionDecl* Def;
1866    if (FD->hasBody(Def))
1867      return Def;
1868  }
1869  return NULL;
1870}
1871
1872static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1873  for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
1874       I != E; ++I) {
1875    Attr *Attribute = *I;
1876    if (Attribute->getKind() == Kind)
1877      return true;
1878  }
1879  return false;
1880}
1881
1882/// checkNewAttributesAfterDef - If we already have a definition, check that
1883/// there are no new attributes in this declaration.
1884static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
1885  if (!New->hasAttrs())
1886    return;
1887
1888  const Decl *Def = getDefinition(Old);
1889  if (!Def || Def == New)
1890    return;
1891
1892  AttrVec &NewAttributes = New->getAttrs();
1893  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
1894    const Attr *NewAttribute = NewAttributes[I];
1895    if (hasAttribute(Def, NewAttribute->getKind())) {
1896      ++I;
1897      continue; // regular attr merging will take care of validating this.
1898    }
1899    S.Diag(NewAttribute->getLocation(),
1900           diag::warn_attribute_precede_definition);
1901    S.Diag(Def->getLocation(), diag::note_previous_definition);
1902    NewAttributes.erase(NewAttributes.begin() + I);
1903    --E;
1904  }
1905}
1906
1907/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1908void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
1909                               bool MergeDeprecation) {
1910  // attributes declared post-definition are currently ignored
1911  checkNewAttributesAfterDef(*this, New, Old);
1912
1913  if (!Old->hasAttrs())
1914    return;
1915
1916  bool foundAny = New->hasAttrs();
1917
1918  // Ensure that any moving of objects within the allocated map is done before
1919  // we process them.
1920  if (!foundAny) New->setAttrs(AttrVec());
1921
1922  for (specific_attr_iterator<InheritableAttr>
1923         i = Old->specific_attr_begin<InheritableAttr>(),
1924         e = Old->specific_attr_end<InheritableAttr>();
1925       i != e; ++i) {
1926    // Ignore deprecated/unavailable/availability attributes if requested.
1927    if (!MergeDeprecation &&
1928        (isa<DeprecatedAttr>(*i) ||
1929         isa<UnavailableAttr>(*i) ||
1930         isa<AvailabilityAttr>(*i)))
1931      continue;
1932
1933    if (mergeDeclAttribute(New, *i))
1934      foundAny = true;
1935  }
1936
1937  if (!foundAny) New->dropAttrs();
1938}
1939
1940/// mergeParamDeclAttributes - Copy attributes from the old parameter
1941/// to the new one.
1942static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1943                                     const ParmVarDecl *oldDecl,
1944                                     ASTContext &C) {
1945  if (!oldDecl->hasAttrs())
1946    return;
1947
1948  bool foundAny = newDecl->hasAttrs();
1949
1950  // Ensure that any moving of objects within the allocated map is
1951  // done before we process them.
1952  if (!foundAny) newDecl->setAttrs(AttrVec());
1953
1954  for (specific_attr_iterator<InheritableParamAttr>
1955       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1956       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1957    if (!DeclHasAttr(newDecl, *i)) {
1958      InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1959      newAttr->setInherited(true);
1960      newDecl->addAttr(newAttr);
1961      foundAny = true;
1962    }
1963  }
1964
1965  if (!foundAny) newDecl->dropAttrs();
1966}
1967
1968namespace {
1969
1970/// Used in MergeFunctionDecl to keep track of function parameters in
1971/// C.
1972struct GNUCompatibleParamWarning {
1973  ParmVarDecl *OldParm;
1974  ParmVarDecl *NewParm;
1975  QualType PromotedType;
1976};
1977
1978}
1979
1980/// getSpecialMember - get the special member enum for a method.
1981Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1982  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1983    if (Ctor->isDefaultConstructor())
1984      return Sema::CXXDefaultConstructor;
1985
1986    if (Ctor->isCopyConstructor())
1987      return Sema::CXXCopyConstructor;
1988
1989    if (Ctor->isMoveConstructor())
1990      return Sema::CXXMoveConstructor;
1991  } else if (isa<CXXDestructorDecl>(MD)) {
1992    return Sema::CXXDestructor;
1993  } else if (MD->isCopyAssignmentOperator()) {
1994    return Sema::CXXCopyAssignment;
1995  } else if (MD->isMoveAssignmentOperator()) {
1996    return Sema::CXXMoveAssignment;
1997  }
1998
1999  return Sema::CXXInvalid;
2000}
2001
2002/// canRedefineFunction - checks if a function can be redefined. Currently,
2003/// only extern inline functions can be redefined, and even then only in
2004/// GNU89 mode.
2005static bool canRedefineFunction(const FunctionDecl *FD,
2006                                const LangOptions& LangOpts) {
2007  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2008          !LangOpts.CPlusPlus &&
2009          FD->isInlineSpecified() &&
2010          FD->getStorageClass() == SC_Extern);
2011}
2012
2013/// Is the given calling convention the ABI default for the given
2014/// declaration?
2015static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
2016  CallingConv ABIDefaultCC;
2017  if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
2018    ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
2019  } else {
2020    // Free C function or a static method.
2021    ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
2022  }
2023  return ABIDefaultCC == CC;
2024}
2025
2026/// MergeFunctionDecl - We just parsed a function 'New' from
2027/// declarator D which has the same name and scope as a previous
2028/// declaration 'Old'.  Figure out how to resolve this situation,
2029/// merging decls or emitting diagnostics as appropriate.
2030///
2031/// In C++, New and Old must be declarations that are not
2032/// overloaded. Use IsOverload to determine whether New and Old are
2033/// overloaded, and to select the Old declaration that New should be
2034/// merged with.
2035///
2036/// Returns true if there was an error, false otherwise.
2037bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
2038  // Verify the old decl was also a function.
2039  FunctionDecl *Old = 0;
2040  if (FunctionTemplateDecl *OldFunctionTemplate
2041        = dyn_cast<FunctionTemplateDecl>(OldD))
2042    Old = OldFunctionTemplate->getTemplatedDecl();
2043  else
2044    Old = dyn_cast<FunctionDecl>(OldD);
2045  if (!Old) {
2046    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2047      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2048      Diag(Shadow->getTargetDecl()->getLocation(),
2049           diag::note_using_decl_target);
2050      Diag(Shadow->getUsingDecl()->getLocation(),
2051           diag::note_using_decl) << 0;
2052      return true;
2053    }
2054
2055    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2056      << New->getDeclName();
2057    Diag(OldD->getLocation(), diag::note_previous_definition);
2058    return true;
2059  }
2060
2061  // Determine whether the previous declaration was a definition,
2062  // implicit declaration, or a declaration.
2063  diag::kind PrevDiag;
2064  if (Old->isThisDeclarationADefinition())
2065    PrevDiag = diag::note_previous_definition;
2066  else if (Old->isImplicit())
2067    PrevDiag = diag::note_previous_implicit_declaration;
2068  else
2069    PrevDiag = diag::note_previous_declaration;
2070
2071  QualType OldQType = Context.getCanonicalType(Old->getType());
2072  QualType NewQType = Context.getCanonicalType(New->getType());
2073
2074  // Don't complain about this if we're in GNU89 mode and the old function
2075  // is an extern inline function.
2076  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2077      New->getStorageClass() == SC_Static &&
2078      Old->getStorageClass() != SC_Static &&
2079      !canRedefineFunction(Old, getLangOpts())) {
2080    if (getLangOpts().MicrosoftExt) {
2081      Diag(New->getLocation(), diag::warn_static_non_static) << New;
2082      Diag(Old->getLocation(), PrevDiag);
2083    } else {
2084      Diag(New->getLocation(), diag::err_static_non_static) << New;
2085      Diag(Old->getLocation(), PrevDiag);
2086      return true;
2087    }
2088  }
2089
2090  // If a function is first declared with a calling convention, but is
2091  // later declared or defined without one, the second decl assumes the
2092  // calling convention of the first.
2093  //
2094  // It's OK if a function is first declared without a calling convention,
2095  // but is later declared or defined with the default calling convention.
2096  //
2097  // For the new decl, we have to look at the NON-canonical type to tell the
2098  // difference between a function that really doesn't have a calling
2099  // convention and one that is declared cdecl. That's because in
2100  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2101  // because it is the default calling convention.
2102  //
2103  // Note also that we DO NOT return at this point, because we still have
2104  // other tests to run.
2105  const FunctionType *OldType = cast<FunctionType>(OldQType);
2106  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
2107  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2108  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2109  bool RequiresAdjustment = false;
2110  if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2111    // Fast path: nothing to do.
2112
2113  // Inherit the CC from the previous declaration if it was specified
2114  // there but not here.
2115  } else if (NewTypeInfo.getCC() == CC_Default) {
2116    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2117    RequiresAdjustment = true;
2118
2119  // Don't complain about mismatches when the default CC is
2120  // effectively the same as the explict one.
2121  } else if (OldTypeInfo.getCC() == CC_Default &&
2122             isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
2123    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2124    RequiresAdjustment = true;
2125
2126  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2127                                     NewTypeInfo.getCC())) {
2128    // Calling conventions really aren't compatible, so complain.
2129    Diag(New->getLocation(), diag::err_cconv_change)
2130      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2131      << (OldTypeInfo.getCC() == CC_Default)
2132      << (OldTypeInfo.getCC() == CC_Default ? "" :
2133          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
2134    Diag(Old->getLocation(), diag::note_previous_declaration);
2135    return true;
2136  }
2137
2138  // FIXME: diagnose the other way around?
2139  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2140    NewTypeInfo = NewTypeInfo.withNoReturn(true);
2141    RequiresAdjustment = true;
2142  }
2143
2144  // Merge regparm attribute.
2145  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2146      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2147    if (NewTypeInfo.getHasRegParm()) {
2148      Diag(New->getLocation(), diag::err_regparm_mismatch)
2149        << NewType->getRegParmType()
2150        << OldType->getRegParmType();
2151      Diag(Old->getLocation(), diag::note_previous_declaration);
2152      return true;
2153    }
2154
2155    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2156    RequiresAdjustment = true;
2157  }
2158
2159  // Merge ns_returns_retained attribute.
2160  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2161    if (NewTypeInfo.getProducesResult()) {
2162      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2163      Diag(Old->getLocation(), diag::note_previous_declaration);
2164      return true;
2165    }
2166
2167    NewTypeInfo = NewTypeInfo.withProducesResult(true);
2168    RequiresAdjustment = true;
2169  }
2170
2171  if (RequiresAdjustment) {
2172    NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2173    New->setType(QualType(NewType, 0));
2174    NewQType = Context.getCanonicalType(New->getType());
2175  }
2176
2177  if (getLangOpts().CPlusPlus) {
2178    // (C++98 13.1p2):
2179    //   Certain function declarations cannot be overloaded:
2180    //     -- Function declarations that differ only in the return type
2181    //        cannot be overloaded.
2182    QualType OldReturnType = OldType->getResultType();
2183    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2184    QualType ResQT;
2185    if (OldReturnType != NewReturnType) {
2186      if (NewReturnType->isObjCObjectPointerType()
2187          && OldReturnType->isObjCObjectPointerType())
2188        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2189      if (ResQT.isNull()) {
2190        if (New->isCXXClassMember() && New->isOutOfLine())
2191          Diag(New->getLocation(),
2192               diag::err_member_def_does_not_match_ret_type) << New;
2193        else
2194          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2195        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2196        return true;
2197      }
2198      else
2199        NewQType = ResQT;
2200    }
2201
2202    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2203    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2204    if (OldMethod && NewMethod) {
2205      // Preserve triviality.
2206      NewMethod->setTrivial(OldMethod->isTrivial());
2207
2208      // MSVC allows explicit template specialization at class scope:
2209      // 2 CXMethodDecls referring to the same function will be injected.
2210      // We don't want a redeclartion error.
2211      bool IsClassScopeExplicitSpecialization =
2212                              OldMethod->isFunctionTemplateSpecialization() &&
2213                              NewMethod->isFunctionTemplateSpecialization();
2214      bool isFriend = NewMethod->getFriendObjectKind();
2215
2216      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2217          !IsClassScopeExplicitSpecialization) {
2218        //    -- Member function declarations with the same name and the
2219        //       same parameter types cannot be overloaded if any of them
2220        //       is a static member function declaration.
2221        if (OldMethod->isStatic() || NewMethod->isStatic()) {
2222          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2223          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2224          return true;
2225        }
2226
2227        // C++ [class.mem]p1:
2228        //   [...] A member shall not be declared twice in the
2229        //   member-specification, except that a nested class or member
2230        //   class template can be declared and then later defined.
2231        if (ActiveTemplateInstantiations.empty()) {
2232          unsigned NewDiag;
2233          if (isa<CXXConstructorDecl>(OldMethod))
2234            NewDiag = diag::err_constructor_redeclared;
2235          else if (isa<CXXDestructorDecl>(NewMethod))
2236            NewDiag = diag::err_destructor_redeclared;
2237          else if (isa<CXXConversionDecl>(NewMethod))
2238            NewDiag = diag::err_conv_function_redeclared;
2239          else
2240            NewDiag = diag::err_member_redeclared;
2241
2242          Diag(New->getLocation(), NewDiag);
2243        } else {
2244          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2245            << New << New->getType();
2246        }
2247        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2248
2249      // Complain if this is an explicit declaration of a special
2250      // member that was initially declared implicitly.
2251      //
2252      // As an exception, it's okay to befriend such methods in order
2253      // to permit the implicit constructor/destructor/operator calls.
2254      } else if (OldMethod->isImplicit()) {
2255        if (isFriend) {
2256          NewMethod->setImplicit();
2257        } else {
2258          Diag(NewMethod->getLocation(),
2259               diag::err_definition_of_implicitly_declared_member)
2260            << New << getSpecialMember(OldMethod);
2261          return true;
2262        }
2263      } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2264        Diag(NewMethod->getLocation(),
2265             diag::err_definition_of_explicitly_defaulted_member)
2266          << getSpecialMember(OldMethod);
2267        return true;
2268      }
2269    }
2270
2271    // (C++98 8.3.5p3):
2272    //   All declarations for a function shall agree exactly in both the
2273    //   return type and the parameter-type-list.
2274    // We also want to respect all the extended bits except noreturn.
2275
2276    // noreturn should now match unless the old type info didn't have it.
2277    QualType OldQTypeForComparison = OldQType;
2278    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2279      assert(OldQType == QualType(OldType, 0));
2280      const FunctionType *OldTypeForComparison
2281        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2282      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2283      assert(OldQTypeForComparison.isCanonical());
2284    }
2285
2286    if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) {
2287      Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2288      Diag(Old->getLocation(), PrevDiag);
2289      return true;
2290    }
2291
2292    if (OldQTypeForComparison == NewQType)
2293      return MergeCompatibleFunctionDecls(New, Old, S);
2294
2295    // Fall through for conflicting redeclarations and redefinitions.
2296  }
2297
2298  // C: Function types need to be compatible, not identical. This handles
2299  // duplicate function decls like "void f(int); void f(enum X);" properly.
2300  if (!getLangOpts().CPlusPlus &&
2301      Context.typesAreCompatible(OldQType, NewQType)) {
2302    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2303    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2304    const FunctionProtoType *OldProto = 0;
2305    if (isa<FunctionNoProtoType>(NewFuncType) &&
2306        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2307      // The old declaration provided a function prototype, but the
2308      // new declaration does not. Merge in the prototype.
2309      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2310      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2311                                                 OldProto->arg_type_end());
2312      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2313                                         ParamTypes.data(), ParamTypes.size(),
2314                                         OldProto->getExtProtoInfo());
2315      New->setType(NewQType);
2316      New->setHasInheritedPrototype();
2317
2318      // Synthesize a parameter for each argument type.
2319      SmallVector<ParmVarDecl*, 16> Params;
2320      for (FunctionProtoType::arg_type_iterator
2321             ParamType = OldProto->arg_type_begin(),
2322             ParamEnd = OldProto->arg_type_end();
2323           ParamType != ParamEnd; ++ParamType) {
2324        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2325                                                 SourceLocation(),
2326                                                 SourceLocation(), 0,
2327                                                 *ParamType, /*TInfo=*/0,
2328                                                 SC_None, SC_None,
2329                                                 0);
2330        Param->setScopeInfo(0, Params.size());
2331        Param->setImplicit();
2332        Params.push_back(Param);
2333      }
2334
2335      New->setParams(Params);
2336    }
2337
2338    return MergeCompatibleFunctionDecls(New, Old, S);
2339  }
2340
2341  // GNU C permits a K&R definition to follow a prototype declaration
2342  // if the declared types of the parameters in the K&R definition
2343  // match the types in the prototype declaration, even when the
2344  // promoted types of the parameters from the K&R definition differ
2345  // from the types in the prototype. GCC then keeps the types from
2346  // the prototype.
2347  //
2348  // If a variadic prototype is followed by a non-variadic K&R definition,
2349  // the K&R definition becomes variadic.  This is sort of an edge case, but
2350  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2351  // C99 6.9.1p8.
2352  if (!getLangOpts().CPlusPlus &&
2353      Old->hasPrototype() && !New->hasPrototype() &&
2354      New->getType()->getAs<FunctionProtoType>() &&
2355      Old->getNumParams() == New->getNumParams()) {
2356    SmallVector<QualType, 16> ArgTypes;
2357    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2358    const FunctionProtoType *OldProto
2359      = Old->getType()->getAs<FunctionProtoType>();
2360    const FunctionProtoType *NewProto
2361      = New->getType()->getAs<FunctionProtoType>();
2362
2363    // Determine whether this is the GNU C extension.
2364    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2365                                               NewProto->getResultType());
2366    bool LooseCompatible = !MergedReturn.isNull();
2367    for (unsigned Idx = 0, End = Old->getNumParams();
2368         LooseCompatible && Idx != End; ++Idx) {
2369      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2370      ParmVarDecl *NewParm = New->getParamDecl(Idx);
2371      if (Context.typesAreCompatible(OldParm->getType(),
2372                                     NewProto->getArgType(Idx))) {
2373        ArgTypes.push_back(NewParm->getType());
2374      } else if (Context.typesAreCompatible(OldParm->getType(),
2375                                            NewParm->getType(),
2376                                            /*CompareUnqualified=*/true)) {
2377        GNUCompatibleParamWarning Warn
2378          = { OldParm, NewParm, NewProto->getArgType(Idx) };
2379        Warnings.push_back(Warn);
2380        ArgTypes.push_back(NewParm->getType());
2381      } else
2382        LooseCompatible = false;
2383    }
2384
2385    if (LooseCompatible) {
2386      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2387        Diag(Warnings[Warn].NewParm->getLocation(),
2388             diag::ext_param_promoted_not_compatible_with_prototype)
2389          << Warnings[Warn].PromotedType
2390          << Warnings[Warn].OldParm->getType();
2391        if (Warnings[Warn].OldParm->getLocation().isValid())
2392          Diag(Warnings[Warn].OldParm->getLocation(),
2393               diag::note_previous_declaration);
2394      }
2395
2396      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2397                                           ArgTypes.size(),
2398                                           OldProto->getExtProtoInfo()));
2399      return MergeCompatibleFunctionDecls(New, Old, S);
2400    }
2401
2402    // Fall through to diagnose conflicting types.
2403  }
2404
2405  // A function that has already been declared has been redeclared or defined
2406  // with a different type- show appropriate diagnostic
2407  if (unsigned BuiltinID = Old->getBuiltinID()) {
2408    // The user has declared a builtin function with an incompatible
2409    // signature.
2410    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2411      // The function the user is redeclaring is a library-defined
2412      // function like 'malloc' or 'printf'. Warn about the
2413      // redeclaration, then pretend that we don't know about this
2414      // library built-in.
2415      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2416      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2417        << Old << Old->getType();
2418      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2419      Old->setInvalidDecl();
2420      return false;
2421    }
2422
2423    PrevDiag = diag::note_previous_builtin_declaration;
2424  }
2425
2426  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2427  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2428  return true;
2429}
2430
2431/// \brief Completes the merge of two function declarations that are
2432/// known to be compatible.
2433///
2434/// This routine handles the merging of attributes and other
2435/// properties of function declarations form the old declaration to
2436/// the new declaration, once we know that New is in fact a
2437/// redeclaration of Old.
2438///
2439/// \returns false
2440bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2441                                        Scope *S) {
2442  // Merge the attributes
2443  mergeDeclAttributes(New, Old);
2444
2445  // Merge the storage class.
2446  if (Old->getStorageClass() != SC_Extern &&
2447      Old->getStorageClass() != SC_None)
2448    New->setStorageClass(Old->getStorageClass());
2449
2450  // Merge "pure" flag.
2451  if (Old->isPure())
2452    New->setPure();
2453
2454  // Merge "used" flag.
2455  if (Old->isUsed(false))
2456    New->setUsed();
2457
2458  // Merge attributes from the parameters.  These can mismatch with K&R
2459  // declarations.
2460  if (New->getNumParams() == Old->getNumParams())
2461    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2462      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2463                               Context);
2464
2465  if (getLangOpts().CPlusPlus)
2466    return MergeCXXFunctionDecl(New, Old, S);
2467
2468  // Merge the function types so the we get the composite types for the return
2469  // and argument types.
2470  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2471  if (!Merged.isNull())
2472    New->setType(Merged);
2473
2474  return false;
2475}
2476
2477
2478void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2479                                ObjCMethodDecl *oldMethod) {
2480
2481  // Merge the attributes, including deprecated/unavailable
2482  mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
2483
2484  // Merge attributes from the parameters.
2485  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2486                                       oe = oldMethod->param_end();
2487  for (ObjCMethodDecl::param_iterator
2488         ni = newMethod->param_begin(), ne = newMethod->param_end();
2489       ni != ne && oi != oe; ++ni, ++oi)
2490    mergeParamDeclAttributes(*ni, *oi, Context);
2491
2492  CheckObjCMethodOverride(newMethod, oldMethod, true);
2493}
2494
2495/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2496/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2497/// emitting diagnostics as appropriate.
2498///
2499/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2500/// to here in AddInitializerToDecl. We can't check them before the initializer
2501/// is attached.
2502void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2503  if (New->isInvalidDecl() || Old->isInvalidDecl())
2504    return;
2505
2506  QualType MergedT;
2507  if (getLangOpts().CPlusPlus) {
2508    AutoType *AT = New->getType()->getContainedAutoType();
2509    if (AT && !AT->isDeduced()) {
2510      // We don't know what the new type is until the initializer is attached.
2511      return;
2512    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2513      // These could still be something that needs exception specs checked.
2514      return MergeVarDeclExceptionSpecs(New, Old);
2515    }
2516    // C++ [basic.link]p10:
2517    //   [...] the types specified by all declarations referring to a given
2518    //   object or function shall be identical, except that declarations for an
2519    //   array object can specify array types that differ by the presence or
2520    //   absence of a major array bound (8.3.4).
2521    else if (Old->getType()->isIncompleteArrayType() &&
2522             New->getType()->isArrayType()) {
2523      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2524      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2525      if (Context.hasSameType(OldArray->getElementType(),
2526                              NewArray->getElementType()))
2527        MergedT = New->getType();
2528    } else if (Old->getType()->isArrayType() &&
2529             New->getType()->isIncompleteArrayType()) {
2530      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2531      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2532      if (Context.hasSameType(OldArray->getElementType(),
2533                              NewArray->getElementType()))
2534        MergedT = Old->getType();
2535    } else if (New->getType()->isObjCObjectPointerType()
2536               && Old->getType()->isObjCObjectPointerType()) {
2537        MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2538                                                        Old->getType());
2539    }
2540  } else {
2541    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2542  }
2543  if (MergedT.isNull()) {
2544    Diag(New->getLocation(), diag::err_redefinition_different_type)
2545      << New->getDeclName() << New->getType() << Old->getType();
2546    Diag(Old->getLocation(), diag::note_previous_definition);
2547    return New->setInvalidDecl();
2548  }
2549  New->setType(MergedT);
2550}
2551
2552/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2553/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2554/// situation, merging decls or emitting diagnostics as appropriate.
2555///
2556/// Tentative definition rules (C99 6.9.2p2) are checked by
2557/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2558/// definitions here, since the initializer hasn't been attached.
2559///
2560void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2561  // If the new decl is already invalid, don't do any other checking.
2562  if (New->isInvalidDecl())
2563    return;
2564
2565  // Verify the old decl was also a variable.
2566  VarDecl *Old = 0;
2567  if (!Previous.isSingleResult() ||
2568      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2569    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2570      << New->getDeclName();
2571    Diag(Previous.getRepresentativeDecl()->getLocation(),
2572         diag::note_previous_definition);
2573    return New->setInvalidDecl();
2574  }
2575
2576  // C++ [class.mem]p1:
2577  //   A member shall not be declared twice in the member-specification [...]
2578  //
2579  // Here, we need only consider static data members.
2580  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2581    Diag(New->getLocation(), diag::err_duplicate_member)
2582      << New->getIdentifier();
2583    Diag(Old->getLocation(), diag::note_previous_declaration);
2584    New->setInvalidDecl();
2585  }
2586
2587  mergeDeclAttributes(New, Old);
2588  // Warn if an already-declared variable is made a weak_import in a subsequent
2589  // declaration
2590  if (New->getAttr<WeakImportAttr>() &&
2591      Old->getStorageClass() == SC_None &&
2592      !Old->getAttr<WeakImportAttr>()) {
2593    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2594    Diag(Old->getLocation(), diag::note_previous_definition);
2595    // Remove weak_import attribute on new declaration.
2596    New->dropAttr<WeakImportAttr>();
2597  }
2598
2599  // Merge the types.
2600  MergeVarDeclTypes(New, Old);
2601  if (New->isInvalidDecl())
2602    return;
2603
2604  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2605  if (New->getStorageClass() == SC_Static &&
2606      (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2607    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2608    Diag(Old->getLocation(), diag::note_previous_definition);
2609    return New->setInvalidDecl();
2610  }
2611  // C99 6.2.2p4:
2612  //   For an identifier declared with the storage-class specifier
2613  //   extern in a scope in which a prior declaration of that
2614  //   identifier is visible,23) if the prior declaration specifies
2615  //   internal or external linkage, the linkage of the identifier at
2616  //   the later declaration is the same as the linkage specified at
2617  //   the prior declaration. If no prior declaration is visible, or
2618  //   if the prior declaration specifies no linkage, then the
2619  //   identifier has external linkage.
2620  if (New->hasExternalStorage() && Old->hasLinkage())
2621    /* Okay */;
2622  else if (New->getStorageClass() != SC_Static &&
2623           Old->getStorageClass() == SC_Static) {
2624    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2625    Diag(Old->getLocation(), diag::note_previous_definition);
2626    return New->setInvalidDecl();
2627  }
2628
2629  // Check if extern is followed by non-extern and vice-versa.
2630  if (New->hasExternalStorage() &&
2631      !Old->hasLinkage() && Old->isLocalVarDecl()) {
2632    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2633    Diag(Old->getLocation(), diag::note_previous_definition);
2634    return New->setInvalidDecl();
2635  }
2636  if (Old->hasExternalStorage() &&
2637      !New->hasLinkage() && New->isLocalVarDecl()) {
2638    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2639    Diag(Old->getLocation(), diag::note_previous_definition);
2640    return New->setInvalidDecl();
2641  }
2642
2643  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2644
2645  // FIXME: The test for external storage here seems wrong? We still
2646  // need to check for mismatches.
2647  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2648      // Don't complain about out-of-line definitions of static members.
2649      !(Old->getLexicalDeclContext()->isRecord() &&
2650        !New->getLexicalDeclContext()->isRecord())) {
2651    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2652    Diag(Old->getLocation(), diag::note_previous_definition);
2653    return New->setInvalidDecl();
2654  }
2655
2656  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2657    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2658    Diag(Old->getLocation(), diag::note_previous_definition);
2659  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2660    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2661    Diag(Old->getLocation(), diag::note_previous_definition);
2662  }
2663
2664  // C++ doesn't have tentative definitions, so go right ahead and check here.
2665  const VarDecl *Def;
2666  if (getLangOpts().CPlusPlus &&
2667      New->isThisDeclarationADefinition() == VarDecl::Definition &&
2668      (Def = Old->getDefinition())) {
2669    Diag(New->getLocation(), diag::err_redefinition)
2670      << New->getDeclName();
2671    Diag(Def->getLocation(), diag::note_previous_definition);
2672    New->setInvalidDecl();
2673    return;
2674  }
2675
2676  if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) {
2677    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2678    Diag(Old->getLocation(), diag::note_previous_definition);
2679    New->setInvalidDecl();
2680    return;
2681  }
2682
2683  // c99 6.2.2 P4.
2684  // For an identifier declared with the storage-class specifier extern in a
2685  // scope in which a prior declaration of that identifier is visible, if
2686  // the prior declaration specifies internal or external linkage, the linkage
2687  // of the identifier at the later declaration is the same as the linkage
2688  // specified at the prior declaration.
2689  // FIXME. revisit this code.
2690  if (New->hasExternalStorage() &&
2691      Old->getLinkage() == InternalLinkage)
2692    New->setStorageClass(Old->getStorageClass());
2693
2694  // Merge "used" flag.
2695  if (Old->isUsed(false))
2696    New->setUsed();
2697
2698  // Keep a chain of previous declarations.
2699  New->setPreviousDeclaration(Old);
2700
2701  // Inherit access appropriately.
2702  New->setAccess(Old->getAccess());
2703}
2704
2705/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2706/// no declarator (e.g. "struct foo;") is parsed.
2707Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2708                                       DeclSpec &DS) {
2709  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
2710}
2711
2712/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2713/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2714/// parameters to cope with template friend declarations.
2715Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2716                                       DeclSpec &DS,
2717                                       MultiTemplateParamsArg TemplateParams) {
2718  Decl *TagD = 0;
2719  TagDecl *Tag = 0;
2720  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2721      DS.getTypeSpecType() == DeclSpec::TST_struct ||
2722      DS.getTypeSpecType() == DeclSpec::TST_interface ||
2723      DS.getTypeSpecType() == DeclSpec::TST_union ||
2724      DS.getTypeSpecType() == DeclSpec::TST_enum) {
2725    TagD = DS.getRepAsDecl();
2726
2727    if (!TagD) // We probably had an error
2728      return 0;
2729
2730    // Note that the above type specs guarantee that the
2731    // type rep is a Decl, whereas in many of the others
2732    // it's a Type.
2733    if (isa<TagDecl>(TagD))
2734      Tag = cast<TagDecl>(TagD);
2735    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2736      Tag = CTD->getTemplatedDecl();
2737  }
2738
2739  if (Tag) {
2740    getASTContext().addUnnamedTag(Tag);
2741    Tag->setFreeStanding();
2742    if (Tag->isInvalidDecl())
2743      return Tag;
2744  }
2745
2746  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2747    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2748    // or incomplete types shall not be restrict-qualified."
2749    if (TypeQuals & DeclSpec::TQ_restrict)
2750      Diag(DS.getRestrictSpecLoc(),
2751           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2752           << DS.getSourceRange();
2753  }
2754
2755  if (DS.isConstexprSpecified()) {
2756    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2757    // and definitions of functions and variables.
2758    if (Tag)
2759      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2760        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2761            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2762            DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
2763            DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
2764    else
2765      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2766    // Don't emit warnings after this error.
2767    return TagD;
2768  }
2769
2770  if (DS.isFriendSpecified()) {
2771    // If we're dealing with a decl but not a TagDecl, assume that
2772    // whatever routines created it handled the friendship aspect.
2773    if (TagD && !Tag)
2774      return 0;
2775    return ActOnFriendTypeDecl(S, DS, TemplateParams);
2776  }
2777
2778  // Track whether we warned about the fact that there aren't any
2779  // declarators.
2780  bool emittedWarning = false;
2781
2782  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2783    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2784        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2785      if (getLangOpts().CPlusPlus ||
2786          Record->getDeclContext()->isRecord())
2787        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2788
2789      Diag(DS.getLocStart(), diag::ext_no_declarators)
2790        << DS.getSourceRange();
2791      emittedWarning = true;
2792    }
2793  }
2794
2795  // Check for Microsoft C extension: anonymous struct.
2796  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2797      CurContext->isRecord() &&
2798      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2799    // Handle 2 kinds of anonymous struct:
2800    //   struct STRUCT;
2801    // and
2802    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2803    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2804    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2805        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2806         DS.getRepAsType().get()->isStructureType())) {
2807      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2808        << DS.getSourceRange();
2809      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2810    }
2811  }
2812
2813  if (getLangOpts().CPlusPlus &&
2814      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2815    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2816      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2817          !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2818        Diag(Enum->getLocation(), diag::ext_no_declarators)
2819          << DS.getSourceRange();
2820        emittedWarning = true;
2821      }
2822
2823  // Skip all the checks below if we have a type error.
2824  if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2825
2826  if (!DS.isMissingDeclaratorOk()) {
2827    // Warn about typedefs of enums without names, since this is an
2828    // extension in both Microsoft and GNU.
2829    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2830        Tag && isa<EnumDecl>(Tag)) {
2831      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2832        << DS.getSourceRange();
2833      return Tag;
2834    }
2835
2836    Diag(DS.getLocStart(), diag::ext_no_declarators)
2837      << DS.getSourceRange();
2838    emittedWarning = true;
2839  }
2840
2841  // We're going to complain about a bunch of spurious specifiers;
2842  // only do this if we're declaring a tag, because otherwise we
2843  // should be getting diag::ext_no_declarators.
2844  if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2845    return TagD;
2846
2847  // Note that a linkage-specification sets a storage class, but
2848  // 'extern "C" struct foo;' is actually valid and not theoretically
2849  // useless.
2850  if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2851    if (!DS.isExternInLinkageSpec())
2852      Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2853        << DeclSpec::getSpecifierName(scs);
2854
2855  if (DS.isThreadSpecified())
2856    Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2857  if (DS.getTypeQualifiers()) {
2858    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2859      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2860    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2861      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2862    // Restrict is covered above.
2863  }
2864  if (DS.isInlineSpecified())
2865    Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2866  if (DS.isVirtualSpecified())
2867    Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2868  if (DS.isExplicitSpecified())
2869    Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2870
2871  if (DS.isModulePrivateSpecified() &&
2872      Tag && Tag->getDeclContext()->isFunctionOrMethod())
2873    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2874      << Tag->getTagKind()
2875      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2876
2877  // Warn about ignored type attributes, for example:
2878  // __attribute__((aligned)) struct A;
2879  // Attributes should be placed after tag to apply to type declaration.
2880  if (!DS.getAttributes().empty()) {
2881    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2882    if (TypeSpecType == DeclSpec::TST_class ||
2883        TypeSpecType == DeclSpec::TST_struct ||
2884        TypeSpecType == DeclSpec::TST_interface ||
2885        TypeSpecType == DeclSpec::TST_union ||
2886        TypeSpecType == DeclSpec::TST_enum) {
2887      AttributeList* attrs = DS.getAttributes().getList();
2888      while (attrs) {
2889        Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
2890        << attrs->getName()
2891        << (TypeSpecType == DeclSpec::TST_class ? 0 :
2892            TypeSpecType == DeclSpec::TST_struct ? 1 :
2893            TypeSpecType == DeclSpec::TST_union ? 2 :
2894            TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
2895        attrs = attrs->getNext();
2896      }
2897    }
2898  }
2899
2900  ActOnDocumentableDecl(TagD);
2901
2902  return TagD;
2903}
2904
2905/// We are trying to inject an anonymous member into the given scope;
2906/// check if there's an existing declaration that can't be overloaded.
2907///
2908/// \return true if this is a forbidden redeclaration
2909static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2910                                         Scope *S,
2911                                         DeclContext *Owner,
2912                                         DeclarationName Name,
2913                                         SourceLocation NameLoc,
2914                                         unsigned diagnostic) {
2915  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2916                 Sema::ForRedeclaration);
2917  if (!SemaRef.LookupName(R, S)) return false;
2918
2919  if (R.getAsSingle<TagDecl>())
2920    return false;
2921
2922  // Pick a representative declaration.
2923  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2924  assert(PrevDecl && "Expected a non-null Decl");
2925
2926  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2927    return false;
2928
2929  SemaRef.Diag(NameLoc, diagnostic) << Name;
2930  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2931
2932  return true;
2933}
2934
2935/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2936/// anonymous struct or union AnonRecord into the owning context Owner
2937/// and scope S. This routine will be invoked just after we realize
2938/// that an unnamed union or struct is actually an anonymous union or
2939/// struct, e.g.,
2940///
2941/// @code
2942/// union {
2943///   int i;
2944///   float f;
2945/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2946///    // f into the surrounding scope.x
2947/// @endcode
2948///
2949/// This routine is recursive, injecting the names of nested anonymous
2950/// structs/unions into the owning context and scope as well.
2951static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2952                                                DeclContext *Owner,
2953                                                RecordDecl *AnonRecord,
2954                                                AccessSpecifier AS,
2955                              SmallVector<NamedDecl*, 2> &Chaining,
2956                                                      bool MSAnonStruct) {
2957  unsigned diagKind
2958    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2959                            : diag::err_anonymous_struct_member_redecl;
2960
2961  bool Invalid = false;
2962
2963  // Look every FieldDecl and IndirectFieldDecl with a name.
2964  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2965                               DEnd = AnonRecord->decls_end();
2966       D != DEnd; ++D) {
2967    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2968        cast<NamedDecl>(*D)->getDeclName()) {
2969      ValueDecl *VD = cast<ValueDecl>(*D);
2970      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2971                                       VD->getLocation(), diagKind)) {
2972        // C++ [class.union]p2:
2973        //   The names of the members of an anonymous union shall be
2974        //   distinct from the names of any other entity in the
2975        //   scope in which the anonymous union is declared.
2976        Invalid = true;
2977      } else {
2978        // C++ [class.union]p2:
2979        //   For the purpose of name lookup, after the anonymous union
2980        //   definition, the members of the anonymous union are
2981        //   considered to have been defined in the scope in which the
2982        //   anonymous union is declared.
2983        unsigned OldChainingSize = Chaining.size();
2984        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2985          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2986               PE = IF->chain_end(); PI != PE; ++PI)
2987            Chaining.push_back(*PI);
2988        else
2989          Chaining.push_back(VD);
2990
2991        assert(Chaining.size() >= 2);
2992        NamedDecl **NamedChain =
2993          new (SemaRef.Context)NamedDecl*[Chaining.size()];
2994        for (unsigned i = 0; i < Chaining.size(); i++)
2995          NamedChain[i] = Chaining[i];
2996
2997        IndirectFieldDecl* IndirectField =
2998          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2999                                    VD->getIdentifier(), VD->getType(),
3000                                    NamedChain, Chaining.size());
3001
3002        IndirectField->setAccess(AS);
3003        IndirectField->setImplicit();
3004        SemaRef.PushOnScopeChains(IndirectField, S);
3005
3006        // That includes picking up the appropriate access specifier.
3007        if (AS != AS_none) IndirectField->setAccess(AS);
3008
3009        Chaining.resize(OldChainingSize);
3010      }
3011    }
3012  }
3013
3014  return Invalid;
3015}
3016
3017/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3018/// a VarDecl::StorageClass. Any error reporting is up to the caller:
3019/// illegal input values are mapped to SC_None.
3020static StorageClass
3021StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
3022  switch (StorageClassSpec) {
3023  case DeclSpec::SCS_unspecified:    return SC_None;
3024  case DeclSpec::SCS_extern:         return SC_Extern;
3025  case DeclSpec::SCS_static:         return SC_Static;
3026  case DeclSpec::SCS_auto:           return SC_Auto;
3027  case DeclSpec::SCS_register:       return SC_Register;
3028  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3029    // Illegal SCSs map to None: error reporting is up to the caller.
3030  case DeclSpec::SCS_mutable:        // Fall through.
3031  case DeclSpec::SCS_typedef:        return SC_None;
3032  }
3033  llvm_unreachable("unknown storage class specifier");
3034}
3035
3036/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
3037/// a StorageClass. Any error reporting is up to the caller:
3038/// illegal input values are mapped to SC_None.
3039static StorageClass
3040StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
3041  switch (StorageClassSpec) {
3042  case DeclSpec::SCS_unspecified:    return SC_None;
3043  case DeclSpec::SCS_extern:         return SC_Extern;
3044  case DeclSpec::SCS_static:         return SC_Static;
3045  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3046    // Illegal SCSs map to None: error reporting is up to the caller.
3047  case DeclSpec::SCS_auto:           // Fall through.
3048  case DeclSpec::SCS_mutable:        // Fall through.
3049  case DeclSpec::SCS_register:       // Fall through.
3050  case DeclSpec::SCS_typedef:        return SC_None;
3051  }
3052  llvm_unreachable("unknown storage class specifier");
3053}
3054
3055/// BuildAnonymousStructOrUnion - Handle the declaration of an
3056/// anonymous structure or union. Anonymous unions are a C++ feature
3057/// (C++ [class.union]) and a C11 feature; anonymous structures
3058/// are a C11 feature and GNU C++ extension.
3059Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3060                                             AccessSpecifier AS,
3061                                             RecordDecl *Record) {
3062  DeclContext *Owner = Record->getDeclContext();
3063
3064  // Diagnose whether this anonymous struct/union is an extension.
3065  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3066    Diag(Record->getLocation(), diag::ext_anonymous_union);
3067  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3068    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3069  else if (!Record->isUnion() && !getLangOpts().C11)
3070    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3071
3072  // C and C++ require different kinds of checks for anonymous
3073  // structs/unions.
3074  bool Invalid = false;
3075  if (getLangOpts().CPlusPlus) {
3076    const char* PrevSpec = 0;
3077    unsigned DiagID;
3078    if (Record->isUnion()) {
3079      // C++ [class.union]p6:
3080      //   Anonymous unions declared in a named namespace or in the
3081      //   global namespace shall be declared static.
3082      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3083          (isa<TranslationUnitDecl>(Owner) ||
3084           (isa<NamespaceDecl>(Owner) &&
3085            cast<NamespaceDecl>(Owner)->getDeclName()))) {
3086        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3087          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3088
3089        // Recover by adding 'static'.
3090        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3091                               PrevSpec, DiagID);
3092      }
3093      // C++ [class.union]p6:
3094      //   A storage class is not allowed in a declaration of an
3095      //   anonymous union in a class scope.
3096      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3097               isa<RecordDecl>(Owner)) {
3098        Diag(DS.getStorageClassSpecLoc(),
3099             diag::err_anonymous_union_with_storage_spec)
3100          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3101
3102        // Recover by removing the storage specifier.
3103        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3104                               SourceLocation(),
3105                               PrevSpec, DiagID);
3106      }
3107    }
3108
3109    // Ignore const/volatile/restrict qualifiers.
3110    if (DS.getTypeQualifiers()) {
3111      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3112        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3113          << Record->isUnion() << 0
3114          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3115      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3116        Diag(DS.getVolatileSpecLoc(),
3117             diag::ext_anonymous_struct_union_qualified)
3118          << Record->isUnion() << 1
3119          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3120      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3121        Diag(DS.getRestrictSpecLoc(),
3122             diag::ext_anonymous_struct_union_qualified)
3123          << Record->isUnion() << 2
3124          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3125
3126      DS.ClearTypeQualifiers();
3127    }
3128
3129    // C++ [class.union]p2:
3130    //   The member-specification of an anonymous union shall only
3131    //   define non-static data members. [Note: nested types and
3132    //   functions cannot be declared within an anonymous union. ]
3133    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3134                                 MemEnd = Record->decls_end();
3135         Mem != MemEnd; ++Mem) {
3136      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3137        // C++ [class.union]p3:
3138        //   An anonymous union shall not have private or protected
3139        //   members (clause 11).
3140        assert(FD->getAccess() != AS_none);
3141        if (FD->getAccess() != AS_public) {
3142          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3143            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3144          Invalid = true;
3145        }
3146
3147        // C++ [class.union]p1
3148        //   An object of a class with a non-trivial constructor, a non-trivial
3149        //   copy constructor, a non-trivial destructor, or a non-trivial copy
3150        //   assignment operator cannot be a member of a union, nor can an
3151        //   array of such objects.
3152        if (CheckNontrivialField(FD))
3153          Invalid = true;
3154      } else if ((*Mem)->isImplicit()) {
3155        // Any implicit members are fine.
3156      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3157        // This is a type that showed up in an
3158        // elaborated-type-specifier inside the anonymous struct or
3159        // union, but which actually declares a type outside of the
3160        // anonymous struct or union. It's okay.
3161      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3162        if (!MemRecord->isAnonymousStructOrUnion() &&
3163            MemRecord->getDeclName()) {
3164          // Visual C++ allows type definition in anonymous struct or union.
3165          if (getLangOpts().MicrosoftExt)
3166            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3167              << (int)Record->isUnion();
3168          else {
3169            // This is a nested type declaration.
3170            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3171              << (int)Record->isUnion();
3172            Invalid = true;
3173          }
3174        }
3175      } else if (isa<AccessSpecDecl>(*Mem)) {
3176        // Any access specifier is fine.
3177      } else {
3178        // We have something that isn't a non-static data
3179        // member. Complain about it.
3180        unsigned DK = diag::err_anonymous_record_bad_member;
3181        if (isa<TypeDecl>(*Mem))
3182          DK = diag::err_anonymous_record_with_type;
3183        else if (isa<FunctionDecl>(*Mem))
3184          DK = diag::err_anonymous_record_with_function;
3185        else if (isa<VarDecl>(*Mem))
3186          DK = diag::err_anonymous_record_with_static;
3187
3188        // Visual C++ allows type definition in anonymous struct or union.
3189        if (getLangOpts().MicrosoftExt &&
3190            DK == diag::err_anonymous_record_with_type)
3191          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3192            << (int)Record->isUnion();
3193        else {
3194          Diag((*Mem)->getLocation(), DK)
3195              << (int)Record->isUnion();
3196          Invalid = true;
3197        }
3198      }
3199    }
3200  }
3201
3202  if (!Record->isUnion() && !Owner->isRecord()) {
3203    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3204      << (int)getLangOpts().CPlusPlus;
3205    Invalid = true;
3206  }
3207
3208  // Mock up a declarator.
3209  Declarator Dc(DS, Declarator::MemberContext);
3210  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3211  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3212
3213  // Create a declaration for this anonymous struct/union.
3214  NamedDecl *Anon = 0;
3215  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3216    Anon = FieldDecl::Create(Context, OwningClass,
3217                             DS.getLocStart(),
3218                             Record->getLocation(),
3219                             /*IdentifierInfo=*/0,
3220                             Context.getTypeDeclType(Record),
3221                             TInfo,
3222                             /*BitWidth=*/0, /*Mutable=*/false,
3223                             /*InitStyle=*/ICIS_NoInit);
3224    Anon->setAccess(AS);
3225    if (getLangOpts().CPlusPlus)
3226      FieldCollector->Add(cast<FieldDecl>(Anon));
3227  } else {
3228    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3229    assert(SCSpec != DeclSpec::SCS_typedef &&
3230           "Parser allowed 'typedef' as storage class VarDecl.");
3231    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3232    if (SCSpec == DeclSpec::SCS_mutable) {
3233      // mutable can only appear on non-static class members, so it's always
3234      // an error here
3235      Diag(Record->getLocation(), diag::err_mutable_nonmember);
3236      Invalid = true;
3237      SC = SC_None;
3238    }
3239    SCSpec = DS.getStorageClassSpecAsWritten();
3240    VarDecl::StorageClass SCAsWritten
3241      = StorageClassSpecToVarDeclStorageClass(SCSpec);
3242
3243    Anon = VarDecl::Create(Context, Owner,
3244                           DS.getLocStart(),
3245                           Record->getLocation(), /*IdentifierInfo=*/0,
3246                           Context.getTypeDeclType(Record),
3247                           TInfo, SC, SCAsWritten);
3248
3249    // Default-initialize the implicit variable. This initialization will be
3250    // trivial in almost all cases, except if a union member has an in-class
3251    // initializer:
3252    //   union { int n = 0; };
3253    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3254  }
3255  Anon->setImplicit();
3256
3257  // Add the anonymous struct/union object to the current
3258  // context. We'll be referencing this object when we refer to one of
3259  // its members.
3260  Owner->addDecl(Anon);
3261
3262  // Inject the members of the anonymous struct/union into the owning
3263  // context and into the identifier resolver chain for name lookup
3264  // purposes.
3265  SmallVector<NamedDecl*, 2> Chain;
3266  Chain.push_back(Anon);
3267
3268  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3269                                          Chain, false))
3270    Invalid = true;
3271
3272  // Mark this as an anonymous struct/union type. Note that we do not
3273  // do this until after we have already checked and injected the
3274  // members of this anonymous struct/union type, because otherwise
3275  // the members could be injected twice: once by DeclContext when it
3276  // builds its lookup table, and once by
3277  // InjectAnonymousStructOrUnionMembers.
3278  Record->setAnonymousStructOrUnion(true);
3279
3280  if (Invalid)
3281    Anon->setInvalidDecl();
3282
3283  return Anon;
3284}
3285
3286/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3287/// Microsoft C anonymous structure.
3288/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3289/// Example:
3290///
3291/// struct A { int a; };
3292/// struct B { struct A; int b; };
3293///
3294/// void foo() {
3295///   B var;
3296///   var.a = 3;
3297/// }
3298///
3299Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3300                                           RecordDecl *Record) {
3301
3302  // If there is no Record, get the record via the typedef.
3303  if (!Record)
3304    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3305
3306  // Mock up a declarator.
3307  Declarator Dc(DS, Declarator::TypeNameContext);
3308  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3309  assert(TInfo && "couldn't build declarator info for anonymous struct");
3310
3311  // Create a declaration for this anonymous struct.
3312  NamedDecl* Anon = FieldDecl::Create(Context,
3313                             cast<RecordDecl>(CurContext),
3314                             DS.getLocStart(),
3315                             DS.getLocStart(),
3316                             /*IdentifierInfo=*/0,
3317                             Context.getTypeDeclType(Record),
3318                             TInfo,
3319                             /*BitWidth=*/0, /*Mutable=*/false,
3320                             /*InitStyle=*/ICIS_NoInit);
3321  Anon->setImplicit();
3322
3323  // Add the anonymous struct object to the current context.
3324  CurContext->addDecl(Anon);
3325
3326  // Inject the members of the anonymous struct into the current
3327  // context and into the identifier resolver chain for name lookup
3328  // purposes.
3329  SmallVector<NamedDecl*, 2> Chain;
3330  Chain.push_back(Anon);
3331
3332  RecordDecl *RecordDef = Record->getDefinition();
3333  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3334                                                        RecordDef, AS_none,
3335                                                        Chain, true))
3336    Anon->setInvalidDecl();
3337
3338  return Anon;
3339}
3340
3341/// GetNameForDeclarator - Determine the full declaration name for the
3342/// given Declarator.
3343DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3344  return GetNameFromUnqualifiedId(D.getName());
3345}
3346
3347/// \brief Retrieves the declaration name from a parsed unqualified-id.
3348DeclarationNameInfo
3349Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3350  DeclarationNameInfo NameInfo;
3351  NameInfo.setLoc(Name.StartLocation);
3352
3353  switch (Name.getKind()) {
3354
3355  case UnqualifiedId::IK_ImplicitSelfParam:
3356  case UnqualifiedId::IK_Identifier:
3357    NameInfo.setName(Name.Identifier);
3358    NameInfo.setLoc(Name.StartLocation);
3359    return NameInfo;
3360
3361  case UnqualifiedId::IK_OperatorFunctionId:
3362    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3363                                           Name.OperatorFunctionId.Operator));
3364    NameInfo.setLoc(Name.StartLocation);
3365    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3366      = Name.OperatorFunctionId.SymbolLocations[0];
3367    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3368      = Name.EndLocation.getRawEncoding();
3369    return NameInfo;
3370
3371  case UnqualifiedId::IK_LiteralOperatorId:
3372    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3373                                                           Name.Identifier));
3374    NameInfo.setLoc(Name.StartLocation);
3375    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3376    return NameInfo;
3377
3378  case UnqualifiedId::IK_ConversionFunctionId: {
3379    TypeSourceInfo *TInfo;
3380    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3381    if (Ty.isNull())
3382      return DeclarationNameInfo();
3383    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3384                                               Context.getCanonicalType(Ty)));
3385    NameInfo.setLoc(Name.StartLocation);
3386    NameInfo.setNamedTypeInfo(TInfo);
3387    return NameInfo;
3388  }
3389
3390  case UnqualifiedId::IK_ConstructorName: {
3391    TypeSourceInfo *TInfo;
3392    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3393    if (Ty.isNull())
3394      return DeclarationNameInfo();
3395    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3396                                              Context.getCanonicalType(Ty)));
3397    NameInfo.setLoc(Name.StartLocation);
3398    NameInfo.setNamedTypeInfo(TInfo);
3399    return NameInfo;
3400  }
3401
3402  case UnqualifiedId::IK_ConstructorTemplateId: {
3403    // In well-formed code, we can only have a constructor
3404    // template-id that refers to the current context, so go there
3405    // to find the actual type being constructed.
3406    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3407    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3408      return DeclarationNameInfo();
3409
3410    // Determine the type of the class being constructed.
3411    QualType CurClassType = Context.getTypeDeclType(CurClass);
3412
3413    // FIXME: Check two things: that the template-id names the same type as
3414    // CurClassType, and that the template-id does not occur when the name
3415    // was qualified.
3416
3417    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3418                                    Context.getCanonicalType(CurClassType)));
3419    NameInfo.setLoc(Name.StartLocation);
3420    // FIXME: should we retrieve TypeSourceInfo?
3421    NameInfo.setNamedTypeInfo(0);
3422    return NameInfo;
3423  }
3424
3425  case UnqualifiedId::IK_DestructorName: {
3426    TypeSourceInfo *TInfo;
3427    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3428    if (Ty.isNull())
3429      return DeclarationNameInfo();
3430    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3431                                              Context.getCanonicalType(Ty)));
3432    NameInfo.setLoc(Name.StartLocation);
3433    NameInfo.setNamedTypeInfo(TInfo);
3434    return NameInfo;
3435  }
3436
3437  case UnqualifiedId::IK_TemplateId: {
3438    TemplateName TName = Name.TemplateId->Template.get();
3439    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3440    return Context.getNameForTemplate(TName, TNameLoc);
3441  }
3442
3443  } // switch (Name.getKind())
3444
3445  llvm_unreachable("Unknown name kind");
3446}
3447
3448static QualType getCoreType(QualType Ty) {
3449  do {
3450    if (Ty->isPointerType() || Ty->isReferenceType())
3451      Ty = Ty->getPointeeType();
3452    else if (Ty->isArrayType())
3453      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3454    else
3455      return Ty.withoutLocalFastQualifiers();
3456  } while (true);
3457}
3458
3459/// hasSimilarParameters - Determine whether the C++ functions Declaration
3460/// and Definition have "nearly" matching parameters. This heuristic is
3461/// used to improve diagnostics in the case where an out-of-line function
3462/// definition doesn't match any declaration within the class or namespace.
3463/// Also sets Params to the list of indices to the parameters that differ
3464/// between the declaration and the definition. If hasSimilarParameters
3465/// returns true and Params is empty, then all of the parameters match.
3466static bool hasSimilarParameters(ASTContext &Context,
3467                                     FunctionDecl *Declaration,
3468                                     FunctionDecl *Definition,
3469                                     llvm::SmallVectorImpl<unsigned> &Params) {
3470  Params.clear();
3471  if (Declaration->param_size() != Definition->param_size())
3472    return false;
3473  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3474    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3475    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3476
3477    // The parameter types are identical
3478    if (Context.hasSameType(DefParamTy, DeclParamTy))
3479      continue;
3480
3481    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3482    QualType DefParamBaseTy = getCoreType(DefParamTy);
3483    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3484    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3485
3486    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3487        (DeclTyName && DeclTyName == DefTyName))
3488      Params.push_back(Idx);
3489    else  // The two parameters aren't even close
3490      return false;
3491  }
3492
3493  return true;
3494}
3495
3496/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3497/// declarator needs to be rebuilt in the current instantiation.
3498/// Any bits of declarator which appear before the name are valid for
3499/// consideration here.  That's specifically the type in the decl spec
3500/// and the base type in any member-pointer chunks.
3501static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3502                                                    DeclarationName Name) {
3503  // The types we specifically need to rebuild are:
3504  //   - typenames, typeofs, and decltypes
3505  //   - types which will become injected class names
3506  // Of course, we also need to rebuild any type referencing such a
3507  // type.  It's safest to just say "dependent", but we call out a
3508  // few cases here.
3509
3510  DeclSpec &DS = D.getMutableDeclSpec();
3511  switch (DS.getTypeSpecType()) {
3512  case DeclSpec::TST_typename:
3513  case DeclSpec::TST_typeofType:
3514  case DeclSpec::TST_underlyingType:
3515  case DeclSpec::TST_atomic: {
3516    // Grab the type from the parser.
3517    TypeSourceInfo *TSI = 0;
3518    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3519    if (T.isNull() || !T->isDependentType()) break;
3520
3521    // Make sure there's a type source info.  This isn't really much
3522    // of a waste; most dependent types should have type source info
3523    // attached already.
3524    if (!TSI)
3525      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3526
3527    // Rebuild the type in the current instantiation.
3528    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3529    if (!TSI) return true;
3530
3531    // Store the new type back in the decl spec.
3532    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3533    DS.UpdateTypeRep(LocType);
3534    break;
3535  }
3536
3537  case DeclSpec::TST_decltype:
3538  case DeclSpec::TST_typeofExpr: {
3539    Expr *E = DS.getRepAsExpr();
3540    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3541    if (Result.isInvalid()) return true;
3542    DS.UpdateExprRep(Result.get());
3543    break;
3544  }
3545
3546  default:
3547    // Nothing to do for these decl specs.
3548    break;
3549  }
3550
3551  // It doesn't matter what order we do this in.
3552  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3553    DeclaratorChunk &Chunk = D.getTypeObject(I);
3554
3555    // The only type information in the declarator which can come
3556    // before the declaration name is the base type of a member
3557    // pointer.
3558    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3559      continue;
3560
3561    // Rebuild the scope specifier in-place.
3562    CXXScopeSpec &SS = Chunk.Mem.Scope();
3563    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3564      return true;
3565  }
3566
3567  return false;
3568}
3569
3570Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3571  D.setFunctionDefinitionKind(FDK_Declaration);
3572  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
3573
3574  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3575      Dcl && Dcl->getDeclContext()->isFileContext())
3576    Dcl->setTopLevelDeclInObjCContainer();
3577
3578  return Dcl;
3579}
3580
3581/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3582///   If T is the name of a class, then each of the following shall have a
3583///   name different from T:
3584///     - every static data member of class T;
3585///     - every member function of class T
3586///     - every member of class T that is itself a type;
3587/// \returns true if the declaration name violates these rules.
3588bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3589                                   DeclarationNameInfo NameInfo) {
3590  DeclarationName Name = NameInfo.getName();
3591
3592  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3593    if (Record->getIdentifier() && Record->getDeclName() == Name) {
3594      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3595      return true;
3596    }
3597
3598  return false;
3599}
3600
3601/// \brief Diagnose a declaration whose declarator-id has the given
3602/// nested-name-specifier.
3603///
3604/// \param SS The nested-name-specifier of the declarator-id.
3605///
3606/// \param DC The declaration context to which the nested-name-specifier
3607/// resolves.
3608///
3609/// \param Name The name of the entity being declared.
3610///
3611/// \param Loc The location of the name of the entity being declared.
3612///
3613/// \returns true if we cannot safely recover from this error, false otherwise.
3614bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3615                                        DeclarationName Name,
3616                                      SourceLocation Loc) {
3617  DeclContext *Cur = CurContext;
3618  while (isa<LinkageSpecDecl>(Cur))
3619    Cur = Cur->getParent();
3620
3621  // C++ [dcl.meaning]p1:
3622  //   A declarator-id shall not be qualified except for the definition
3623  //   of a member function (9.3) or static data member (9.4) outside of
3624  //   its class, the definition or explicit instantiation of a function
3625  //   or variable member of a namespace outside of its namespace, or the
3626  //   definition of an explicit specialization outside of its namespace,
3627  //   or the declaration of a friend function that is a member of
3628  //   another class or namespace (11.3). [...]
3629
3630  // The user provided a superfluous scope specifier that refers back to the
3631  // class or namespaces in which the entity is already declared.
3632  //
3633  // class X {
3634  //   void X::f();
3635  // };
3636  if (Cur->Equals(DC)) {
3637    Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3638                                   : diag::err_member_extra_qualification)
3639      << Name << FixItHint::CreateRemoval(SS.getRange());
3640    SS.clear();
3641    return false;
3642  }
3643
3644  // Check whether the qualifying scope encloses the scope of the original
3645  // declaration.
3646  if (!Cur->Encloses(DC)) {
3647    if (Cur->isRecord())
3648      Diag(Loc, diag::err_member_qualification)
3649        << Name << SS.getRange();
3650    else if (isa<TranslationUnitDecl>(DC))
3651      Diag(Loc, diag::err_invalid_declarator_global_scope)
3652        << Name << SS.getRange();
3653    else if (isa<FunctionDecl>(Cur))
3654      Diag(Loc, diag::err_invalid_declarator_in_function)
3655        << Name << SS.getRange();
3656    else
3657      Diag(Loc, diag::err_invalid_declarator_scope)
3658      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3659
3660    return true;
3661  }
3662
3663  if (Cur->isRecord()) {
3664    // Cannot qualify members within a class.
3665    Diag(Loc, diag::err_member_qualification)
3666      << Name << SS.getRange();
3667    SS.clear();
3668
3669    // C++ constructors and destructors with incorrect scopes can break
3670    // our AST invariants by having the wrong underlying types. If
3671    // that's the case, then drop this declaration entirely.
3672    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3673         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3674        !Context.hasSameType(Name.getCXXNameType(),
3675                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3676      return true;
3677
3678    return false;
3679  }
3680
3681  // C++11 [dcl.meaning]p1:
3682  //   [...] "The nested-name-specifier of the qualified declarator-id shall
3683  //   not begin with a decltype-specifer"
3684  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3685  while (SpecLoc.getPrefix())
3686    SpecLoc = SpecLoc.getPrefix();
3687  if (dyn_cast_or_null<DecltypeType>(
3688        SpecLoc.getNestedNameSpecifier()->getAsType()))
3689    Diag(Loc, diag::err_decltype_in_declarator)
3690      << SpecLoc.getTypeLoc().getSourceRange();
3691
3692  return false;
3693}
3694
3695NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3696                                  MultiTemplateParamsArg TemplateParamLists) {
3697  // TODO: consider using NameInfo for diagnostic.
3698  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3699  DeclarationName Name = NameInfo.getName();
3700
3701  // All of these full declarators require an identifier.  If it doesn't have
3702  // one, the ParsedFreeStandingDeclSpec action should be used.
3703  if (!Name) {
3704    if (!D.isInvalidType())  // Reject this if we think it is valid.
3705      Diag(D.getDeclSpec().getLocStart(),
3706           diag::err_declarator_need_ident)
3707        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3708    return 0;
3709  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3710    return 0;
3711
3712  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3713  // we find one that is.
3714  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3715         (S->getFlags() & Scope::TemplateParamScope) != 0)
3716    S = S->getParent();
3717
3718  DeclContext *DC = CurContext;
3719  if (D.getCXXScopeSpec().isInvalid())
3720    D.setInvalidType();
3721  else if (D.getCXXScopeSpec().isSet()) {
3722    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3723                                        UPPC_DeclarationQualifier))
3724      return 0;
3725
3726    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3727    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3728    if (!DC) {
3729      // If we could not compute the declaration context, it's because the
3730      // declaration context is dependent but does not refer to a class,
3731      // class template, or class template partial specialization. Complain
3732      // and return early, to avoid the coming semantic disaster.
3733      Diag(D.getIdentifierLoc(),
3734           diag::err_template_qualified_declarator_no_match)
3735        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3736        << D.getCXXScopeSpec().getRange();
3737      return 0;
3738    }
3739    bool IsDependentContext = DC->isDependentContext();
3740
3741    if (!IsDependentContext &&
3742        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3743      return 0;
3744
3745    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3746      Diag(D.getIdentifierLoc(),
3747           diag::err_member_def_undefined_record)
3748        << Name << DC << D.getCXXScopeSpec().getRange();
3749      D.setInvalidType();
3750    } else if (!D.getDeclSpec().isFriendSpecified()) {
3751      if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3752                                      Name, D.getIdentifierLoc())) {
3753        if (DC->isRecord())
3754          return 0;
3755
3756        D.setInvalidType();
3757      }
3758    }
3759
3760    // Check whether we need to rebuild the type of the given
3761    // declaration in the current instantiation.
3762    if (EnteringContext && IsDependentContext &&
3763        TemplateParamLists.size() != 0) {
3764      ContextRAII SavedContext(*this, DC);
3765      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3766        D.setInvalidType();
3767    }
3768  }
3769
3770  if (DiagnoseClassNameShadow(DC, NameInfo))
3771    // If this is a typedef, we'll end up spewing multiple diagnostics.
3772    // Just return early; it's safer.
3773    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3774      return 0;
3775
3776  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3777  QualType R = TInfo->getType();
3778
3779  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3780                                      UPPC_DeclarationType))
3781    D.setInvalidType();
3782
3783  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3784                        ForRedeclaration);
3785
3786  // See if this is a redefinition of a variable in the same scope.
3787  if (!D.getCXXScopeSpec().isSet()) {
3788    bool IsLinkageLookup = false;
3789
3790    // If the declaration we're planning to build will be a function
3791    // or object with linkage, then look for another declaration with
3792    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3793    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3794      /* Do nothing*/;
3795    else if (R->isFunctionType()) {
3796      if (CurContext->isFunctionOrMethod() ||
3797          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3798        IsLinkageLookup = true;
3799    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3800      IsLinkageLookup = true;
3801    else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3802             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3803      IsLinkageLookup = true;
3804
3805    if (IsLinkageLookup)
3806      Previous.clear(LookupRedeclarationWithLinkage);
3807
3808    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3809  } else { // Something like "int foo::x;"
3810    LookupQualifiedName(Previous, DC);
3811
3812    // C++ [dcl.meaning]p1:
3813    //   When the declarator-id is qualified, the declaration shall refer to a
3814    //  previously declared member of the class or namespace to which the
3815    //  qualifier refers (or, in the case of a namespace, of an element of the
3816    //  inline namespace set of that namespace (7.3.1)) or to a specialization
3817    //  thereof; [...]
3818    //
3819    // Note that we already checked the context above, and that we do not have
3820    // enough information to make sure that Previous contains the declaration
3821    // we want to match. For example, given:
3822    //
3823    //   class X {
3824    //     void f();
3825    //     void f(float);
3826    //   };
3827    //
3828    //   void X::f(int) { } // ill-formed
3829    //
3830    // In this case, Previous will point to the overload set
3831    // containing the two f's declared in X, but neither of them
3832    // matches.
3833
3834    // C++ [dcl.meaning]p1:
3835    //   [...] the member shall not merely have been introduced by a
3836    //   using-declaration in the scope of the class or namespace nominated by
3837    //   the nested-name-specifier of the declarator-id.
3838    RemoveUsingDecls(Previous);
3839  }
3840
3841  if (Previous.isSingleResult() &&
3842      Previous.getFoundDecl()->isTemplateParameter()) {
3843    // Maybe we will complain about the shadowed template parameter.
3844    if (!D.isInvalidType())
3845      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3846                                      Previous.getFoundDecl());
3847
3848    // Just pretend that we didn't see the previous declaration.
3849    Previous.clear();
3850  }
3851
3852  // In C++, the previous declaration we find might be a tag type
3853  // (class or enum). In this case, the new declaration will hide the
3854  // tag type. Note that this does does not apply if we're declaring a
3855  // typedef (C++ [dcl.typedef]p4).
3856  if (Previous.isSingleTagDecl() &&
3857      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3858    Previous.clear();
3859
3860  NamedDecl *New;
3861
3862  bool AddToScope = true;
3863  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3864    if (TemplateParamLists.size()) {
3865      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3866      return 0;
3867    }
3868
3869    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3870  } else if (R->isFunctionType()) {
3871    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3872                                  TemplateParamLists,
3873                                  AddToScope);
3874  } else {
3875    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3876                                  TemplateParamLists);
3877  }
3878
3879  if (New == 0)
3880    return 0;
3881
3882  // If this has an identifier and is not an invalid redeclaration or
3883  // function template specialization, add it to the scope stack.
3884  if (New->getDeclName() && AddToScope &&
3885       !(D.isRedeclaration() && New->isInvalidDecl()))
3886    PushOnScopeChains(New, S);
3887
3888  return New;
3889}
3890
3891/// Helper method to turn variable array types into constant array
3892/// types in certain situations which would otherwise be errors (for
3893/// GCC compatibility).
3894static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3895                                                    ASTContext &Context,
3896                                                    bool &SizeIsNegative,
3897                                                    llvm::APSInt &Oversized) {
3898  // This method tries to turn a variable array into a constant
3899  // array even when the size isn't an ICE.  This is necessary
3900  // for compatibility with code that depends on gcc's buggy
3901  // constant expression folding, like struct {char x[(int)(char*)2];}
3902  SizeIsNegative = false;
3903  Oversized = 0;
3904
3905  if (T->isDependentType())
3906    return QualType();
3907
3908  QualifierCollector Qs;
3909  const Type *Ty = Qs.strip(T);
3910
3911  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3912    QualType Pointee = PTy->getPointeeType();
3913    QualType FixedType =
3914        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3915                                            Oversized);
3916    if (FixedType.isNull()) return FixedType;
3917    FixedType = Context.getPointerType(FixedType);
3918    return Qs.apply(Context, FixedType);
3919  }
3920  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3921    QualType Inner = PTy->getInnerType();
3922    QualType FixedType =
3923        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3924                                            Oversized);
3925    if (FixedType.isNull()) return FixedType;
3926    FixedType = Context.getParenType(FixedType);
3927    return Qs.apply(Context, FixedType);
3928  }
3929
3930  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3931  if (!VLATy)
3932    return QualType();
3933  // FIXME: We should probably handle this case
3934  if (VLATy->getElementType()->isVariablyModifiedType())
3935    return QualType();
3936
3937  llvm::APSInt Res;
3938  if (!VLATy->getSizeExpr() ||
3939      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3940    return QualType();
3941
3942  // Check whether the array size is negative.
3943  if (Res.isSigned() && Res.isNegative()) {
3944    SizeIsNegative = true;
3945    return QualType();
3946  }
3947
3948  // Check whether the array is too large to be addressed.
3949  unsigned ActiveSizeBits
3950    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3951                                              Res);
3952  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3953    Oversized = Res;
3954    return QualType();
3955  }
3956
3957  return Context.getConstantArrayType(VLATy->getElementType(),
3958                                      Res, ArrayType::Normal, 0);
3959}
3960
3961static void
3962FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
3963  if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
3964    PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
3965    FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
3966                                      DstPTL->getPointeeLoc());
3967    DstPTL->setStarLoc(SrcPTL->getStarLoc());
3968    return;
3969  }
3970  if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
3971    ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
3972    FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
3973                                      DstPTL->getInnerLoc());
3974    DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
3975    DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
3976    return;
3977  }
3978  ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
3979  ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
3980  TypeLoc SrcElemTL = SrcATL->getElementLoc();
3981  TypeLoc DstElemTL = DstATL->getElementLoc();
3982  DstElemTL.initializeFullCopy(SrcElemTL);
3983  DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
3984  DstATL->setSizeExpr(SrcATL->getSizeExpr());
3985  DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
3986}
3987
3988/// Helper method to turn variable array types into constant array
3989/// types in certain situations which would otherwise be errors (for
3990/// GCC compatibility).
3991static TypeSourceInfo*
3992TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
3993                                              ASTContext &Context,
3994                                              bool &SizeIsNegative,
3995                                              llvm::APSInt &Oversized) {
3996  QualType FixedTy
3997    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
3998                                          SizeIsNegative, Oversized);
3999  if (FixedTy.isNull())
4000    return 0;
4001  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4002  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4003                                    FixedTInfo->getTypeLoc());
4004  return FixedTInfo;
4005}
4006
4007/// \brief Register the given locally-scoped extern "C" declaration so
4008/// that it can be found later for redeclarations
4009void
4010Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
4011                                       const LookupResult &Previous,
4012                                       Scope *S) {
4013  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
4014         "Decl is not a locally-scoped decl!");
4015  // Note that we have a locally-scoped external with this name.
4016  LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4017
4018  if (!Previous.isSingleResult())
4019    return;
4020
4021  NamedDecl *PrevDecl = Previous.getFoundDecl();
4022
4023  // If there was a previous declaration of this entity, it may be in
4024  // our identifier chain. Update the identifier chain with the new
4025  // declaration.
4026  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
4027    // The previous declaration was found on the identifer resolver
4028    // chain, so remove it from its scope.
4029
4030    if (S->isDeclScope(PrevDecl)) {
4031      // Special case for redeclarations in the SAME scope.
4032      // Because this declaration is going to be added to the identifier chain
4033      // later, we should temporarily take it OFF the chain.
4034      IdResolver.RemoveDecl(ND);
4035
4036    } else {
4037      // Find the scope for the original declaration.
4038      while (S && !S->isDeclScope(PrevDecl))
4039        S = S->getParent();
4040    }
4041
4042    if (S)
4043      S->RemoveDecl(PrevDecl);
4044  }
4045}
4046
4047llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
4048Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4049  if (ExternalSource) {
4050    // Load locally-scoped external decls from the external source.
4051    SmallVector<NamedDecl *, 4> Decls;
4052    ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4053    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4054      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4055        = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4056      if (Pos == LocallyScopedExternCDecls.end())
4057        LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4058    }
4059  }
4060
4061  return LocallyScopedExternCDecls.find(Name);
4062}
4063
4064/// \brief Diagnose function specifiers on a declaration of an identifier that
4065/// does not identify a function.
4066void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
4067  // FIXME: We should probably indicate the identifier in question to avoid
4068  // confusion for constructs like "inline int a(), b;"
4069  if (D.getDeclSpec().isInlineSpecified())
4070    Diag(D.getDeclSpec().getInlineSpecLoc(),
4071         diag::err_inline_non_function);
4072
4073  if (D.getDeclSpec().isVirtualSpecified())
4074    Diag(D.getDeclSpec().getVirtualSpecLoc(),
4075         diag::err_virtual_non_function);
4076
4077  if (D.getDeclSpec().isExplicitSpecified())
4078    Diag(D.getDeclSpec().getExplicitSpecLoc(),
4079         diag::err_explicit_non_function);
4080}
4081
4082NamedDecl*
4083Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4084                             TypeSourceInfo *TInfo, LookupResult &Previous) {
4085  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4086  if (D.getCXXScopeSpec().isSet()) {
4087    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4088      << D.getCXXScopeSpec().getRange();
4089    D.setInvalidType();
4090    // Pretend we didn't see the scope specifier.
4091    DC = CurContext;
4092    Previous.clear();
4093  }
4094
4095  if (getLangOpts().CPlusPlus) {
4096    // Check that there are no default arguments (C++ only).
4097    CheckExtraCXXDefaultArguments(D);
4098  }
4099
4100  DiagnoseFunctionSpecifiers(D);
4101
4102  if (D.getDeclSpec().isThreadSpecified())
4103    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4104  if (D.getDeclSpec().isConstexprSpecified())
4105    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4106      << 1;
4107
4108  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4109    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4110      << D.getName().getSourceRange();
4111    return 0;
4112  }
4113
4114  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4115  if (!NewTD) return 0;
4116
4117  // Handle attributes prior to checking for duplicates in MergeVarDecl
4118  ProcessDeclAttributes(S, NewTD, D);
4119
4120  CheckTypedefForVariablyModifiedType(S, NewTD);
4121
4122  bool Redeclaration = D.isRedeclaration();
4123  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4124  D.setRedeclaration(Redeclaration);
4125  return ND;
4126}
4127
4128void
4129Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4130  // C99 6.7.7p2: If a typedef name specifies a variably modified type
4131  // then it shall have block scope.
4132  // Note that variably modified types must be fixed before merging the decl so
4133  // that redeclarations will match.
4134  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4135  QualType T = TInfo->getType();
4136  if (T->isVariablyModifiedType()) {
4137    getCurFunction()->setHasBranchProtectedScope();
4138
4139    if (S->getFnParent() == 0) {
4140      bool SizeIsNegative;
4141      llvm::APSInt Oversized;
4142      TypeSourceInfo *FixedTInfo =
4143        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4144                                                      SizeIsNegative,
4145                                                      Oversized);
4146      if (FixedTInfo) {
4147        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4148        NewTD->setTypeSourceInfo(FixedTInfo);
4149      } else {
4150        if (SizeIsNegative)
4151          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4152        else if (T->isVariableArrayType())
4153          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4154        else if (Oversized.getBoolValue())
4155          Diag(NewTD->getLocation(), diag::err_array_too_large)
4156            << Oversized.toString(10);
4157        else
4158          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4159        NewTD->setInvalidDecl();
4160      }
4161    }
4162  }
4163}
4164
4165
4166/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4167/// declares a typedef-name, either using the 'typedef' type specifier or via
4168/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4169NamedDecl*
4170Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4171                           LookupResult &Previous, bool &Redeclaration) {
4172  // Merge the decl with the existing one if appropriate. If the decl is
4173  // in an outer scope, it isn't the same thing.
4174  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4175                       /*ExplicitInstantiationOrSpecialization=*/false);
4176  filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4177  if (!Previous.empty()) {
4178    Redeclaration = true;
4179    MergeTypedefNameDecl(NewTD, Previous);
4180  }
4181
4182  // If this is the C FILE type, notify the AST context.
4183  if (IdentifierInfo *II = NewTD->getIdentifier())
4184    if (!NewTD->isInvalidDecl() &&
4185        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4186      if (II->isStr("FILE"))
4187        Context.setFILEDecl(NewTD);
4188      else if (II->isStr("jmp_buf"))
4189        Context.setjmp_bufDecl(NewTD);
4190      else if (II->isStr("sigjmp_buf"))
4191        Context.setsigjmp_bufDecl(NewTD);
4192      else if (II->isStr("ucontext_t"))
4193        Context.setucontext_tDecl(NewTD);
4194    }
4195
4196  return NewTD;
4197}
4198
4199/// \brief Determines whether the given declaration is an out-of-scope
4200/// previous declaration.
4201///
4202/// This routine should be invoked when name lookup has found a
4203/// previous declaration (PrevDecl) that is not in the scope where a
4204/// new declaration by the same name is being introduced. If the new
4205/// declaration occurs in a local scope, previous declarations with
4206/// linkage may still be considered previous declarations (C99
4207/// 6.2.2p4-5, C++ [basic.link]p6).
4208///
4209/// \param PrevDecl the previous declaration found by name
4210/// lookup
4211///
4212/// \param DC the context in which the new declaration is being
4213/// declared.
4214///
4215/// \returns true if PrevDecl is an out-of-scope previous declaration
4216/// for a new delcaration with the same name.
4217static bool
4218isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4219                                ASTContext &Context) {
4220  if (!PrevDecl)
4221    return false;
4222
4223  if (!PrevDecl->hasLinkage())
4224    return false;
4225
4226  if (Context.getLangOpts().CPlusPlus) {
4227    // C++ [basic.link]p6:
4228    //   If there is a visible declaration of an entity with linkage
4229    //   having the same name and type, ignoring entities declared
4230    //   outside the innermost enclosing namespace scope, the block
4231    //   scope declaration declares that same entity and receives the
4232    //   linkage of the previous declaration.
4233    DeclContext *OuterContext = DC->getRedeclContext();
4234    if (!OuterContext->isFunctionOrMethod())
4235      // This rule only applies to block-scope declarations.
4236      return false;
4237
4238    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4239    if (PrevOuterContext->isRecord())
4240      // We found a member function: ignore it.
4241      return false;
4242
4243    // Find the innermost enclosing namespace for the new and
4244    // previous declarations.
4245    OuterContext = OuterContext->getEnclosingNamespaceContext();
4246    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4247
4248    // The previous declaration is in a different namespace, so it
4249    // isn't the same function.
4250    if (!OuterContext->Equals(PrevOuterContext))
4251      return false;
4252  }
4253
4254  return true;
4255}
4256
4257static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4258  CXXScopeSpec &SS = D.getCXXScopeSpec();
4259  if (!SS.isSet()) return;
4260  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4261}
4262
4263bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4264  QualType type = decl->getType();
4265  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4266  if (lifetime == Qualifiers::OCL_Autoreleasing) {
4267    // Various kinds of declaration aren't allowed to be __autoreleasing.
4268    unsigned kind = -1U;
4269    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4270      if (var->hasAttr<BlocksAttr>())
4271        kind = 0; // __block
4272      else if (!var->hasLocalStorage())
4273        kind = 1; // global
4274    } else if (isa<ObjCIvarDecl>(decl)) {
4275      kind = 3; // ivar
4276    } else if (isa<FieldDecl>(decl)) {
4277      kind = 2; // field
4278    }
4279
4280    if (kind != -1U) {
4281      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4282        << kind;
4283    }
4284  } else if (lifetime == Qualifiers::OCL_None) {
4285    // Try to infer lifetime.
4286    if (!type->isObjCLifetimeType())
4287      return false;
4288
4289    lifetime = type->getObjCARCImplicitLifetime();
4290    type = Context.getLifetimeQualifiedType(type, lifetime);
4291    decl->setType(type);
4292  }
4293
4294  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4295    // Thread-local variables cannot have lifetime.
4296    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4297        var->isThreadSpecified()) {
4298      Diag(var->getLocation(), diag::err_arc_thread_ownership)
4299        << var->getType();
4300      return true;
4301    }
4302  }
4303
4304  return false;
4305}
4306
4307NamedDecl*
4308Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4309                              TypeSourceInfo *TInfo, LookupResult &Previous,
4310                              MultiTemplateParamsArg TemplateParamLists) {
4311  QualType R = TInfo->getType();
4312  DeclarationName Name = GetNameForDeclarator(D).getName();
4313
4314  // Check that there are no default arguments (C++ only).
4315  if (getLangOpts().CPlusPlus)
4316    CheckExtraCXXDefaultArguments(D);
4317
4318  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4319  assert(SCSpec != DeclSpec::SCS_typedef &&
4320         "Parser allowed 'typedef' as storage class VarDecl.");
4321  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
4322  if (SCSpec == DeclSpec::SCS_mutable) {
4323    // mutable can only appear on non-static class members, so it's always
4324    // an error here
4325    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4326    D.setInvalidType();
4327    SC = SC_None;
4328  }
4329  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4330  VarDecl::StorageClass SCAsWritten
4331    = StorageClassSpecToVarDeclStorageClass(SCSpec);
4332
4333  IdentifierInfo *II = Name.getAsIdentifierInfo();
4334  if (!II) {
4335    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4336      << Name;
4337    return 0;
4338  }
4339
4340  DiagnoseFunctionSpecifiers(D);
4341
4342  if (!DC->isRecord() && S->getFnParent() == 0) {
4343    // C99 6.9p2: The storage-class specifiers auto and register shall not
4344    // appear in the declaration specifiers in an external declaration.
4345    if (SC == SC_Auto || SC == SC_Register) {
4346
4347      // If this is a register variable with an asm label specified, then this
4348      // is a GNU extension.
4349      if (SC == SC_Register && D.getAsmLabel())
4350        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4351      else
4352        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4353      D.setInvalidType();
4354    }
4355  }
4356
4357  if (getLangOpts().OpenCL) {
4358    // Set up the special work-group-local storage class for variables in the
4359    // OpenCL __local address space.
4360    if (R.getAddressSpace() == LangAS::opencl_local) {
4361      SC = SC_OpenCLWorkGroupLocal;
4362      SCAsWritten = SC_OpenCLWorkGroupLocal;
4363    }
4364  }
4365
4366  bool isExplicitSpecialization = false;
4367  VarDecl *NewVD;
4368  if (!getLangOpts().CPlusPlus) {
4369    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4370                            D.getIdentifierLoc(), II,
4371                            R, TInfo, SC, SCAsWritten);
4372
4373    if (D.isInvalidType())
4374      NewVD->setInvalidDecl();
4375  } else {
4376    if (DC->isRecord() && !CurContext->isRecord()) {
4377      // This is an out-of-line definition of a static data member.
4378      if (SC == SC_Static) {
4379        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4380             diag::err_static_out_of_line)
4381          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4382      } else if (SC == SC_None)
4383        SC = SC_Static;
4384    }
4385    if (SC == SC_Static && CurContext->isRecord()) {
4386      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4387        if (RD->isLocalClass())
4388          Diag(D.getIdentifierLoc(),
4389               diag::err_static_data_member_not_allowed_in_local_class)
4390            << Name << RD->getDeclName();
4391
4392        // C++98 [class.union]p1: If a union contains a static data member,
4393        // the program is ill-formed. C++11 drops this restriction.
4394        if (RD->isUnion())
4395          Diag(D.getIdentifierLoc(),
4396               getLangOpts().CPlusPlus11
4397                 ? diag::warn_cxx98_compat_static_data_member_in_union
4398                 : diag::ext_static_data_member_in_union) << Name;
4399        // We conservatively disallow static data members in anonymous structs.
4400        else if (!RD->getDeclName())
4401          Diag(D.getIdentifierLoc(),
4402               diag::err_static_data_member_not_allowed_in_anon_struct)
4403            << Name << RD->isUnion();
4404      }
4405    }
4406
4407    // Match up the template parameter lists with the scope specifier, then
4408    // determine whether we have a template or a template specialization.
4409    isExplicitSpecialization = false;
4410    bool Invalid = false;
4411    if (TemplateParameterList *TemplateParams
4412        = MatchTemplateParametersToScopeSpecifier(
4413                                  D.getDeclSpec().getLocStart(),
4414                                                  D.getIdentifierLoc(),
4415                                                  D.getCXXScopeSpec(),
4416                                                  TemplateParamLists.data(),
4417                                                  TemplateParamLists.size(),
4418                                                  /*never a friend*/ false,
4419                                                  isExplicitSpecialization,
4420                                                  Invalid)) {
4421      if (TemplateParams->size() > 0) {
4422        // There is no such thing as a variable template.
4423        Diag(D.getIdentifierLoc(), diag::err_template_variable)
4424          << II
4425          << SourceRange(TemplateParams->getTemplateLoc(),
4426                         TemplateParams->getRAngleLoc());
4427        return 0;
4428      } else {
4429        // There is an extraneous 'template<>' for this variable. Complain
4430        // about it, but allow the declaration of the variable.
4431        Diag(TemplateParams->getTemplateLoc(),
4432             diag::err_template_variable_noparams)
4433          << II
4434          << SourceRange(TemplateParams->getTemplateLoc(),
4435                         TemplateParams->getRAngleLoc());
4436      }
4437    }
4438
4439    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4440                            D.getIdentifierLoc(), II,
4441                            R, TInfo, SC, SCAsWritten);
4442
4443    // If this decl has an auto type in need of deduction, make a note of the
4444    // Decl so we can diagnose uses of it in its own initializer.
4445    if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4446        R->getContainedAutoType())
4447      ParsingInitForAutoVars.insert(NewVD);
4448
4449    if (D.isInvalidType() || Invalid)
4450      NewVD->setInvalidDecl();
4451
4452    SetNestedNameSpecifier(NewVD, D);
4453
4454    if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4455      NewVD->setTemplateParameterListsInfo(Context,
4456                                           TemplateParamLists.size(),
4457                                           TemplateParamLists.data());
4458    }
4459
4460    if (D.getDeclSpec().isConstexprSpecified())
4461      NewVD->setConstexpr(true);
4462  }
4463
4464  // Set the lexical context. If the declarator has a C++ scope specifier, the
4465  // lexical context will be different from the semantic context.
4466  NewVD->setLexicalDeclContext(CurContext);
4467
4468  if (D.getDeclSpec().isThreadSpecified()) {
4469    if (NewVD->hasLocalStorage())
4470      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4471    else if (!Context.getTargetInfo().isTLSSupported())
4472      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4473    else
4474      NewVD->setThreadSpecified(true);
4475  }
4476
4477  if (D.getDeclSpec().isModulePrivateSpecified()) {
4478    if (isExplicitSpecialization)
4479      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4480        << 2
4481        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4482    else if (NewVD->hasLocalStorage())
4483      Diag(NewVD->getLocation(), diag::err_module_private_local)
4484        << 0 << NewVD->getDeclName()
4485        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4486        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4487    else
4488      NewVD->setModulePrivate();
4489  }
4490
4491  // Handle attributes prior to checking for duplicates in MergeVarDecl
4492  ProcessDeclAttributes(S, NewVD, D);
4493
4494  if (getLangOpts().CUDA) {
4495    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4496    // storage [duration]."
4497    if (SC == SC_None && S->getFnParent() != 0 &&
4498        (NewVD->hasAttr<CUDASharedAttr>() ||
4499         NewVD->hasAttr<CUDAConstantAttr>())) {
4500      NewVD->setStorageClass(SC_Static);
4501      NewVD->setStorageClassAsWritten(SC_Static);
4502    }
4503  }
4504
4505  // In auto-retain/release, infer strong retension for variables of
4506  // retainable type.
4507  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4508    NewVD->setInvalidDecl();
4509
4510  // Handle GNU asm-label extension (encoded as an attribute).
4511  if (Expr *E = (Expr*)D.getAsmLabel()) {
4512    // The parser guarantees this is a string.
4513    StringLiteral *SE = cast<StringLiteral>(E);
4514    StringRef Label = SE->getString();
4515    if (S->getFnParent() != 0) {
4516      switch (SC) {
4517      case SC_None:
4518      case SC_Auto:
4519        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4520        break;
4521      case SC_Register:
4522        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4523          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4524        break;
4525      case SC_Static:
4526      case SC_Extern:
4527      case SC_PrivateExtern:
4528      case SC_OpenCLWorkGroupLocal:
4529        break;
4530      }
4531    }
4532
4533    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4534                                                Context, Label));
4535  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4536    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4537      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4538    if (I != ExtnameUndeclaredIdentifiers.end()) {
4539      NewVD->addAttr(I->second);
4540      ExtnameUndeclaredIdentifiers.erase(I);
4541    }
4542  }
4543
4544  // Diagnose shadowed variables before filtering for scope.
4545  if (!D.getCXXScopeSpec().isSet())
4546    CheckShadow(S, NewVD, Previous);
4547
4548  // Don't consider existing declarations that are in a different
4549  // scope and are out-of-semantic-context declarations (if the new
4550  // declaration has linkage).
4551  FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4552                       isExplicitSpecialization);
4553
4554  if (!getLangOpts().CPlusPlus) {
4555    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4556  } else {
4557    // Merge the decl with the existing one if appropriate.
4558    if (!Previous.empty()) {
4559      if (Previous.isSingleResult() &&
4560          isa<FieldDecl>(Previous.getFoundDecl()) &&
4561          D.getCXXScopeSpec().isSet()) {
4562        // The user tried to define a non-static data member
4563        // out-of-line (C++ [dcl.meaning]p1).
4564        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4565          << D.getCXXScopeSpec().getRange();
4566        Previous.clear();
4567        NewVD->setInvalidDecl();
4568      }
4569    } else if (D.getCXXScopeSpec().isSet()) {
4570      // No previous declaration in the qualifying scope.
4571      Diag(D.getIdentifierLoc(), diag::err_no_member)
4572        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4573        << D.getCXXScopeSpec().getRange();
4574      NewVD->setInvalidDecl();
4575    }
4576
4577    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4578
4579    // This is an explicit specialization of a static data member. Check it.
4580    if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4581        CheckMemberSpecialization(NewVD, Previous))
4582      NewVD->setInvalidDecl();
4583  }
4584
4585  // If this is a locally-scoped extern C variable, update the map of
4586  // such variables.
4587  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4588      !NewVD->isInvalidDecl())
4589    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4590
4591  // If there's a #pragma GCC visibility in scope, and this isn't a class
4592  // member, set the visibility of this variable.
4593  if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4594    AddPushedVisibilityAttribute(NewVD);
4595
4596  return NewVD;
4597}
4598
4599/// \brief Diagnose variable or built-in function shadowing.  Implements
4600/// -Wshadow.
4601///
4602/// This method is called whenever a VarDecl is added to a "useful"
4603/// scope.
4604///
4605/// \param S the scope in which the shadowing name is being declared
4606/// \param R the lookup of the name
4607///
4608void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4609  // Return if warning is ignored.
4610  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4611        DiagnosticsEngine::Ignored)
4612    return;
4613
4614  // Don't diagnose declarations at file scope.
4615  if (D->hasGlobalStorage())
4616    return;
4617
4618  DeclContext *NewDC = D->getDeclContext();
4619
4620  // Only diagnose if we're shadowing an unambiguous field or variable.
4621  if (R.getResultKind() != LookupResult::Found)
4622    return;
4623
4624  NamedDecl* ShadowedDecl = R.getFoundDecl();
4625  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4626    return;
4627
4628  // Fields are not shadowed by variables in C++ static methods.
4629  if (isa<FieldDecl>(ShadowedDecl))
4630    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4631      if (MD->isStatic())
4632        return;
4633
4634  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4635    if (shadowedVar->isExternC()) {
4636      // For shadowing external vars, make sure that we point to the global
4637      // declaration, not a locally scoped extern declaration.
4638      for (VarDecl::redecl_iterator
4639             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4640           I != E; ++I)
4641        if (I->isFileVarDecl()) {
4642          ShadowedDecl = *I;
4643          break;
4644        }
4645    }
4646
4647  DeclContext *OldDC = ShadowedDecl->getDeclContext();
4648
4649  // Only warn about certain kinds of shadowing for class members.
4650  if (NewDC && NewDC->isRecord()) {
4651    // In particular, don't warn about shadowing non-class members.
4652    if (!OldDC->isRecord())
4653      return;
4654
4655    // TODO: should we warn about static data members shadowing
4656    // static data members from base classes?
4657
4658    // TODO: don't diagnose for inaccessible shadowed members.
4659    // This is hard to do perfectly because we might friend the
4660    // shadowing context, but that's just a false negative.
4661  }
4662
4663  // Determine what kind of declaration we're shadowing.
4664  unsigned Kind;
4665  if (isa<RecordDecl>(OldDC)) {
4666    if (isa<FieldDecl>(ShadowedDecl))
4667      Kind = 3; // field
4668    else
4669      Kind = 2; // static data member
4670  } else if (OldDC->isFileContext())
4671    Kind = 1; // global
4672  else
4673    Kind = 0; // local
4674
4675  DeclarationName Name = R.getLookupName();
4676
4677  // Emit warning and note.
4678  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4679  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4680}
4681
4682/// \brief Check -Wshadow without the advantage of a previous lookup.
4683void Sema::CheckShadow(Scope *S, VarDecl *D) {
4684  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4685        DiagnosticsEngine::Ignored)
4686    return;
4687
4688  LookupResult R(*this, D->getDeclName(), D->getLocation(),
4689                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4690  LookupName(R, S);
4691  CheckShadow(S, D, R);
4692}
4693
4694/// \brief Perform semantic checking on a newly-created variable
4695/// declaration.
4696///
4697/// This routine performs all of the type-checking required for a
4698/// variable declaration once it has been built. It is used both to
4699/// check variables after they have been parsed and their declarators
4700/// have been translated into a declaration, and to check variables
4701/// that have been instantiated from a template.
4702///
4703/// Sets NewVD->isInvalidDecl() if an error was encountered.
4704///
4705/// Returns true if the variable declaration is a redeclaration.
4706bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4707                                    LookupResult &Previous) {
4708  // If the decl is already known invalid, don't check it.
4709  if (NewVD->isInvalidDecl())
4710    return false;
4711
4712  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
4713  QualType T = TInfo->getType();
4714
4715  if (T->isObjCObjectType()) {
4716    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4717      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4718    T = Context.getObjCObjectPointerType(T);
4719    NewVD->setType(T);
4720  }
4721
4722  // Emit an error if an address space was applied to decl with local storage.
4723  // This includes arrays of objects with address space qualifiers, but not
4724  // automatic variables that point to other address spaces.
4725  // ISO/IEC TR 18037 S5.1.2
4726  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4727    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4728    NewVD->setInvalidDecl();
4729    return false;
4730  }
4731
4732  // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4733  // scope.
4734  if ((getLangOpts().OpenCLVersion >= 120)
4735      && NewVD->isStaticLocal()) {
4736    Diag(NewVD->getLocation(), diag::err_static_function_scope);
4737    NewVD->setInvalidDecl();
4738    return false;
4739  }
4740
4741  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4742      && !NewVD->hasAttr<BlocksAttr>()) {
4743    if (getLangOpts().getGC() != LangOptions::NonGC)
4744      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4745    else {
4746      assert(!getLangOpts().ObjCAutoRefCount);
4747      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4748    }
4749  }
4750
4751  bool isVM = T->isVariablyModifiedType();
4752  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4753      NewVD->hasAttr<BlocksAttr>())
4754    getCurFunction()->setHasBranchProtectedScope();
4755
4756  if ((isVM && NewVD->hasLinkage()) ||
4757      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4758    bool SizeIsNegative;
4759    llvm::APSInt Oversized;
4760    TypeSourceInfo *FixedTInfo =
4761      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4762                                                    SizeIsNegative, Oversized);
4763    if (FixedTInfo == 0 && T->isVariableArrayType()) {
4764      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4765      // FIXME: This won't give the correct result for
4766      // int a[10][n];
4767      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4768
4769      if (NewVD->isFileVarDecl())
4770        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4771        << SizeRange;
4772      else if (NewVD->getStorageClass() == SC_Static)
4773        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4774        << SizeRange;
4775      else
4776        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4777        << SizeRange;
4778      NewVD->setInvalidDecl();
4779      return false;
4780    }
4781
4782    if (FixedTInfo == 0) {
4783      if (NewVD->isFileVarDecl())
4784        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4785      else
4786        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4787      NewVD->setInvalidDecl();
4788      return false;
4789    }
4790
4791    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4792    NewVD->setType(FixedTInfo->getType());
4793    NewVD->setTypeSourceInfo(FixedTInfo);
4794  }
4795
4796  if (Previous.empty() && NewVD->isExternC()) {
4797    // Since we did not find anything by this name and we're declaring
4798    // an extern "C" variable, look for a non-visible extern "C"
4799    // declaration with the same name.
4800    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4801      = findLocallyScopedExternCDecl(NewVD->getDeclName());
4802    if (Pos != LocallyScopedExternCDecls.end())
4803      Previous.addDecl(Pos->second);
4804  }
4805
4806  // Filter out any non-conflicting previous declarations.
4807  filterNonConflictingPreviousDecls(Context, NewVD, Previous);
4808
4809  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4810    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4811      << T;
4812    NewVD->setInvalidDecl();
4813    return false;
4814  }
4815
4816  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4817    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4818    NewVD->setInvalidDecl();
4819    return false;
4820  }
4821
4822  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4823    Diag(NewVD->getLocation(), diag::err_block_on_vm);
4824    NewVD->setInvalidDecl();
4825    return false;
4826  }
4827
4828  if (NewVD->isConstexpr() && !T->isDependentType() &&
4829      RequireLiteralType(NewVD->getLocation(), T,
4830                         diag::err_constexpr_var_non_literal)) {
4831    NewVD->setInvalidDecl();
4832    return false;
4833  }
4834
4835  if (!Previous.empty()) {
4836    MergeVarDecl(NewVD, Previous);
4837    return true;
4838  }
4839  return false;
4840}
4841
4842/// \brief Data used with FindOverriddenMethod
4843struct FindOverriddenMethodData {
4844  Sema *S;
4845  CXXMethodDecl *Method;
4846};
4847
4848/// \brief Member lookup function that determines whether a given C++
4849/// method overrides a method in a base class, to be used with
4850/// CXXRecordDecl::lookupInBases().
4851static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4852                                 CXXBasePath &Path,
4853                                 void *UserData) {
4854  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4855
4856  FindOverriddenMethodData *Data
4857    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4858
4859  DeclarationName Name = Data->Method->getDeclName();
4860
4861  // FIXME: Do we care about other names here too?
4862  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4863    // We really want to find the base class destructor here.
4864    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4865    CanQualType CT = Data->S->Context.getCanonicalType(T);
4866
4867    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4868  }
4869
4870  for (Path.Decls = BaseRecord->lookup(Name);
4871       !Path.Decls.empty();
4872       Path.Decls = Path.Decls.slice(1)) {
4873    NamedDecl *D = Path.Decls.front();
4874    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4875      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4876        return true;
4877    }
4878  }
4879
4880  return false;
4881}
4882
4883namespace {
4884  enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
4885}
4886/// \brief Report an error regarding overriding, along with any relevant
4887/// overriden methods.
4888///
4889/// \param DiagID the primary error to report.
4890/// \param MD the overriding method.
4891/// \param OEK which overrides to include as notes.
4892static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
4893                            OverrideErrorKind OEK = OEK_All) {
4894  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
4895  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4896                                      E = MD->end_overridden_methods();
4897       I != E; ++I) {
4898    // This check (& the OEK parameter) could be replaced by a predicate, but
4899    // without lambdas that would be overkill. This is still nicer than writing
4900    // out the diag loop 3 times.
4901    if ((OEK == OEK_All) ||
4902        (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
4903        (OEK == OEK_Deleted && (*I)->isDeleted()))
4904      S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
4905  }
4906}
4907
4908/// AddOverriddenMethods - See if a method overrides any in the base classes,
4909/// and if so, check that it's a valid override and remember it.
4910bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4911  // Look for virtual methods in base classes that this method might override.
4912  CXXBasePaths Paths;
4913  FindOverriddenMethodData Data;
4914  Data.Method = MD;
4915  Data.S = this;
4916  bool hasDeletedOverridenMethods = false;
4917  bool hasNonDeletedOverridenMethods = false;
4918  bool AddedAny = false;
4919  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4920    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4921         E = Paths.found_decls_end(); I != E; ++I) {
4922      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4923        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4924        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4925            !CheckOverridingFunctionAttributes(MD, OldMD) &&
4926            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4927            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4928          hasDeletedOverridenMethods |= OldMD->isDeleted();
4929          hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
4930          AddedAny = true;
4931        }
4932      }
4933    }
4934  }
4935
4936  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
4937    ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
4938  }
4939  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
4940    ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
4941  }
4942
4943  return AddedAny;
4944}
4945
4946namespace {
4947  // Struct for holding all of the extra arguments needed by
4948  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4949  struct ActOnFDArgs {
4950    Scope *S;
4951    Declarator &D;
4952    MultiTemplateParamsArg TemplateParamLists;
4953    bool AddToScope;
4954  };
4955}
4956
4957namespace {
4958
4959// Callback to only accept typo corrections that have a non-zero edit distance.
4960// Also only accept corrections that have the same parent decl.
4961class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4962 public:
4963  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4964                            CXXRecordDecl *Parent)
4965      : Context(Context), OriginalFD(TypoFD),
4966        ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4967
4968  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4969    if (candidate.getEditDistance() == 0)
4970      return false;
4971
4972    llvm::SmallVector<unsigned, 1> MismatchedParams;
4973    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4974                                          CDeclEnd = candidate.end();
4975         CDecl != CDeclEnd; ++CDecl) {
4976      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4977
4978      if (FD && !FD->hasBody() &&
4979          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4980        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4981          CXXRecordDecl *Parent = MD->getParent();
4982          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4983            return true;
4984        } else if (!ExpectedParent) {
4985          return true;
4986        }
4987      }
4988    }
4989
4990    return false;
4991  }
4992
4993 private:
4994  ASTContext &Context;
4995  FunctionDecl *OriginalFD;
4996  CXXRecordDecl *ExpectedParent;
4997};
4998
4999}
5000
5001/// \brief Generate diagnostics for an invalid function redeclaration.
5002///
5003/// This routine handles generating the diagnostic messages for an invalid
5004/// function redeclaration, including finding possible similar declarations
5005/// or performing typo correction if there are no previous declarations with
5006/// the same name.
5007///
5008/// Returns a NamedDecl iff typo correction was performed and substituting in
5009/// the new declaration name does not cause new errors.
5010static NamedDecl* DiagnoseInvalidRedeclaration(
5011    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
5012    ActOnFDArgs &ExtraArgs) {
5013  NamedDecl *Result = NULL;
5014  DeclarationName Name = NewFD->getDeclName();
5015  DeclContext *NewDC = NewFD->getDeclContext();
5016  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
5017                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5018  llvm::SmallVector<unsigned, 1> MismatchedParams;
5019  llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
5020  TypoCorrection Correction;
5021  bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
5022                       ExtraArgs.D.getDeclSpec().isFriendSpecified());
5023  unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
5024                                  : diag::err_member_def_does_not_match;
5025
5026  NewFD->setInvalidDecl();
5027  SemaRef.LookupQualifiedName(Prev, NewDC);
5028  assert(!Prev.isAmbiguous() &&
5029         "Cannot have an ambiguity in previous-declaration lookup");
5030  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5031  DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
5032                                      MD ? MD->getParent() : 0);
5033  if (!Prev.empty()) {
5034    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
5035         Func != FuncEnd; ++Func) {
5036      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
5037      if (FD &&
5038          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
5039        // Add 1 to the index so that 0 can mean the mismatch didn't
5040        // involve a parameter
5041        unsigned ParamNum =
5042            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
5043        NearMatches.push_back(std::make_pair(FD, ParamNum));
5044      }
5045    }
5046  // If the qualified name lookup yielded nothing, try typo correction
5047  } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
5048                                         Prev.getLookupKind(), 0, 0,
5049                                         Validator, NewDC))) {
5050    // Trap errors.
5051    Sema::SFINAETrap Trap(SemaRef);
5052
5053    // Set up everything for the call to ActOnFunctionDeclarator
5054    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
5055                              ExtraArgs.D.getIdentifierLoc());
5056    Previous.clear();
5057    Previous.setLookupName(Correction.getCorrection());
5058    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
5059                                    CDeclEnd = Correction.end();
5060         CDecl != CDeclEnd; ++CDecl) {
5061      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5062      if (FD && !FD->hasBody() &&
5063          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
5064        Previous.addDecl(FD);
5065      }
5066    }
5067    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
5068    // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
5069    // pieces need to verify the typo-corrected C++ declaraction and hopefully
5070    // eliminate the need for the parameter pack ExtraArgs.
5071    Result = SemaRef.ActOnFunctionDeclarator(
5072        ExtraArgs.S, ExtraArgs.D,
5073        Correction.getCorrectionDecl()->getDeclContext(),
5074        NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
5075        ExtraArgs.AddToScope);
5076    if (Trap.hasErrorOccurred()) {
5077      // Pretend the typo correction never occurred
5078      ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
5079                                ExtraArgs.D.getIdentifierLoc());
5080      ExtraArgs.D.setRedeclaration(wasRedeclaration);
5081      Previous.clear();
5082      Previous.setLookupName(Name);
5083      Result = NULL;
5084    } else {
5085      for (LookupResult::iterator Func = Previous.begin(),
5086                               FuncEnd = Previous.end();
5087           Func != FuncEnd; ++Func) {
5088        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
5089          NearMatches.push_back(std::make_pair(FD, 0));
5090      }
5091    }
5092    if (NearMatches.empty()) {
5093      // Ignore the correction if it didn't yield any close FunctionDecl matches
5094      Correction = TypoCorrection();
5095    } else {
5096      DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5097                             : diag::err_member_def_does_not_match_suggest;
5098    }
5099  }
5100
5101  if (Correction) {
5102    // FIXME: use Correction.getCorrectionRange() instead of computing the range
5103    // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5104    // turn causes the correction to fully qualify the name. If we fix
5105    // CorrectTypo to minimally qualify then this change should be good.
5106    SourceRange FixItLoc(NewFD->getLocation());
5107    CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5108    if (Correction.getCorrectionSpecifier() && SS.isValid())
5109      FixItLoc.setBegin(SS.getBeginLoc());
5110    SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
5111        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
5112        << FixItHint::CreateReplacement(
5113            FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5114  } else {
5115    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5116        << Name << NewDC << NewFD->getLocation();
5117  }
5118
5119  bool NewFDisConst = false;
5120  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
5121    NewFDisConst = NewMD->isConst();
5122
5123  for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
5124       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5125       NearMatch != NearMatchEnd; ++NearMatch) {
5126    FunctionDecl *FD = NearMatch->first;
5127    bool FDisConst = false;
5128    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
5129      FDisConst = MD->isConst();
5130
5131    if (unsigned Idx = NearMatch->second) {
5132      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
5133      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5134      if (Loc.isInvalid()) Loc = FD->getLocation();
5135      SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
5136          << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5137    } else if (Correction) {
5138      SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
5139          << Correction.getQuoted(SemaRef.getLangOpts());
5140    } else if (FDisConst != NewFDisConst) {
5141      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
5142          << NewFDisConst << FD->getSourceRange().getEnd();
5143    } else
5144      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
5145  }
5146  return Result;
5147}
5148
5149static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5150                                                          Declarator &D) {
5151  switch (D.getDeclSpec().getStorageClassSpec()) {
5152  default: llvm_unreachable("Unknown storage class!");
5153  case DeclSpec::SCS_auto:
5154  case DeclSpec::SCS_register:
5155  case DeclSpec::SCS_mutable:
5156    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5157                 diag::err_typecheck_sclass_func);
5158    D.setInvalidType();
5159    break;
5160  case DeclSpec::SCS_unspecified: break;
5161  case DeclSpec::SCS_extern: return SC_Extern;
5162  case DeclSpec::SCS_static: {
5163    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5164      // C99 6.7.1p5:
5165      //   The declaration of an identifier for a function that has
5166      //   block scope shall have no explicit storage-class specifier
5167      //   other than extern
5168      // See also (C++ [dcl.stc]p4).
5169      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5170                   diag::err_static_block_func);
5171      break;
5172    } else
5173      return SC_Static;
5174  }
5175  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5176  }
5177
5178  // No explicit storage class has already been returned
5179  return SC_None;
5180}
5181
5182static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5183                                           DeclContext *DC, QualType &R,
5184                                           TypeSourceInfo *TInfo,
5185                                           FunctionDecl::StorageClass SC,
5186                                           bool &IsVirtualOkay) {
5187  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5188  DeclarationName Name = NameInfo.getName();
5189
5190  FunctionDecl *NewFD = 0;
5191  bool isInline = D.getDeclSpec().isInlineSpecified();
5192  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5193  FunctionDecl::StorageClass SCAsWritten
5194    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5195
5196  if (!SemaRef.getLangOpts().CPlusPlus) {
5197    // Determine whether the function was written with a
5198    // prototype. This true when:
5199    //   - there is a prototype in the declarator, or
5200    //   - the type R of the function is some kind of typedef or other reference
5201    //     to a type name (which eventually refers to a function type).
5202    bool HasPrototype =
5203      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5204      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5205
5206    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
5207                                 D.getLocStart(), NameInfo, R,
5208                                 TInfo, SC, SCAsWritten, isInline,
5209                                 HasPrototype);
5210    if (D.isInvalidType())
5211      NewFD->setInvalidDecl();
5212
5213    // Set the lexical context.
5214    NewFD->setLexicalDeclContext(SemaRef.CurContext);
5215
5216    return NewFD;
5217  }
5218
5219  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5220  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5221
5222  // Check that the return type is not an abstract class type.
5223  // For record types, this is done by the AbstractClassUsageDiagnoser once
5224  // the class has been completely parsed.
5225  if (!DC->isRecord() &&
5226      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5227                                     R->getAs<FunctionType>()->getResultType(),
5228                                     diag::err_abstract_type_in_decl,
5229                                     SemaRef.AbstractReturnType))
5230    D.setInvalidType();
5231
5232  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5233    // This is a C++ constructor declaration.
5234    assert(DC->isRecord() &&
5235           "Constructors can only be declared in a member context");
5236
5237    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5238    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5239                                      D.getLocStart(), NameInfo,
5240                                      R, TInfo, isExplicit, isInline,
5241                                      /*isImplicitlyDeclared=*/false,
5242                                      isConstexpr);
5243
5244  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5245    // This is a C++ destructor declaration.
5246    if (DC->isRecord()) {
5247      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5248      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5249      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5250                                        SemaRef.Context, Record,
5251                                        D.getLocStart(),
5252                                        NameInfo, R, TInfo, isInline,
5253                                        /*isImplicitlyDeclared=*/false);
5254
5255      // If the class is complete, then we now create the implicit exception
5256      // specification. If the class is incomplete or dependent, we can't do
5257      // it yet.
5258      if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
5259          Record->getDefinition() && !Record->isBeingDefined() &&
5260          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5261        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5262      }
5263
5264      IsVirtualOkay = true;
5265      return NewDD;
5266
5267    } else {
5268      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5269      D.setInvalidType();
5270
5271      // Create a FunctionDecl to satisfy the function definition parsing
5272      // code path.
5273      return FunctionDecl::Create(SemaRef.Context, DC,
5274                                  D.getLocStart(),
5275                                  D.getIdentifierLoc(), Name, R, TInfo,
5276                                  SC, SCAsWritten, isInline,
5277                                  /*hasPrototype=*/true, isConstexpr);
5278    }
5279
5280  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5281    if (!DC->isRecord()) {
5282      SemaRef.Diag(D.getIdentifierLoc(),
5283           diag::err_conv_function_not_member);
5284      return 0;
5285    }
5286
5287    SemaRef.CheckConversionDeclarator(D, R, SC);
5288    IsVirtualOkay = true;
5289    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5290                                     D.getLocStart(), NameInfo,
5291                                     R, TInfo, isInline, isExplicit,
5292                                     isConstexpr, SourceLocation());
5293
5294  } else if (DC->isRecord()) {
5295    // If the name of the function is the same as the name of the record,
5296    // then this must be an invalid constructor that has a return type.
5297    // (The parser checks for a return type and makes the declarator a
5298    // constructor if it has no return type).
5299    if (Name.getAsIdentifierInfo() &&
5300        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5301      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5302        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5303        << SourceRange(D.getIdentifierLoc());
5304      return 0;
5305    }
5306
5307    bool isStatic = SC == SC_Static;
5308
5309    // [class.free]p1:
5310    // Any allocation function for a class T is a static member
5311    // (even if not explicitly declared static).
5312    if (Name.getCXXOverloadedOperator() == OO_New ||
5313        Name.getCXXOverloadedOperator() == OO_Array_New)
5314      isStatic = true;
5315
5316    // [class.free]p6 Any deallocation function for a class X is a static member
5317    // (even if not explicitly declared static).
5318    if (Name.getCXXOverloadedOperator() == OO_Delete ||
5319        Name.getCXXOverloadedOperator() == OO_Array_Delete)
5320      isStatic = true;
5321
5322    IsVirtualOkay = !isStatic;
5323
5324    // This is a C++ method declaration.
5325    return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5326                                 D.getLocStart(), NameInfo, R,
5327                                 TInfo, isStatic, SCAsWritten, isInline,
5328                                 isConstexpr, SourceLocation());
5329
5330  } else {
5331    // Determine whether the function was written with a
5332    // prototype. This true when:
5333    //   - we're in C++ (where every function has a prototype),
5334    return FunctionDecl::Create(SemaRef.Context, DC,
5335                                D.getLocStart(),
5336                                NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5337                                true/*HasPrototype*/, isConstexpr);
5338  }
5339}
5340
5341void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5342  // In C++, the empty parameter-type-list must be spelled "void"; a
5343  // typedef of void is not permitted.
5344  if (getLangOpts().CPlusPlus &&
5345      Param->getType().getUnqualifiedType() != Context.VoidTy) {
5346    bool IsTypeAlias = false;
5347    if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5348      IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5349    else if (const TemplateSpecializationType *TST =
5350               Param->getType()->getAs<TemplateSpecializationType>())
5351      IsTypeAlias = TST->isTypeAlias();
5352    Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5353      << IsTypeAlias;
5354  }
5355}
5356
5357NamedDecl*
5358Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5359                              TypeSourceInfo *TInfo, LookupResult &Previous,
5360                              MultiTemplateParamsArg TemplateParamLists,
5361                              bool &AddToScope) {
5362  QualType R = TInfo->getType();
5363
5364  assert(R.getTypePtr()->isFunctionType());
5365
5366  // TODO: consider using NameInfo for diagnostic.
5367  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5368  DeclarationName Name = NameInfo.getName();
5369  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
5370
5371  if (D.getDeclSpec().isThreadSpecified())
5372    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5373
5374  // Do not allow returning a objc interface by-value.
5375  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
5376    Diag(D.getIdentifierLoc(),
5377         diag::err_object_cannot_be_passed_returned_by_value) << 0
5378    << R->getAs<FunctionType>()->getResultType()
5379    << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
5380
5381    QualType T = R->getAs<FunctionType>()->getResultType();
5382    T = Context.getObjCObjectPointerType(T);
5383    if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5384      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5385      R = Context.getFunctionType(T, FPT->arg_type_begin(),
5386                                  FPT->getNumArgs(), EPI);
5387    }
5388    else if (isa<FunctionNoProtoType>(R))
5389      R = Context.getFunctionNoProtoType(T);
5390  }
5391
5392  bool isFriend = false;
5393  FunctionTemplateDecl *FunctionTemplate = 0;
5394  bool isExplicitSpecialization = false;
5395  bool isFunctionTemplateSpecialization = false;
5396
5397  bool isDependentClassScopeExplicitSpecialization = false;
5398  bool HasExplicitTemplateArgs = false;
5399  TemplateArgumentListInfo TemplateArgs;
5400
5401  bool isVirtualOkay = false;
5402
5403  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5404                                              isVirtualOkay);
5405  if (!NewFD) return 0;
5406
5407  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5408    NewFD->setTopLevelDeclInObjCContainer();
5409
5410  if (getLangOpts().CPlusPlus) {
5411    bool isInline = D.getDeclSpec().isInlineSpecified();
5412    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5413    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5414    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5415    isFriend = D.getDeclSpec().isFriendSpecified();
5416    if (isFriend && !isInline && D.isFunctionDefinition()) {
5417      // C++ [class.friend]p5
5418      //   A function can be defined in a friend declaration of a
5419      //   class . . . . Such a function is implicitly inline.
5420      NewFD->setImplicitlyInline();
5421    }
5422
5423    // If this is a method defined in an __interface, and is not a constructor
5424    // or an overloaded operator, then set the pure flag (isVirtual will already
5425    // return true).
5426    if (const CXXRecordDecl *Parent =
5427          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5428      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
5429        NewFD->setPure(true);
5430    }
5431
5432    SetNestedNameSpecifier(NewFD, D);
5433    isExplicitSpecialization = false;
5434    isFunctionTemplateSpecialization = false;
5435    if (D.isInvalidType())
5436      NewFD->setInvalidDecl();
5437
5438    // Set the lexical context. If the declarator has a C++
5439    // scope specifier, or is the object of a friend declaration, the
5440    // lexical context will be different from the semantic context.
5441    NewFD->setLexicalDeclContext(CurContext);
5442
5443    // Match up the template parameter lists with the scope specifier, then
5444    // determine whether we have a template or a template specialization.
5445    bool Invalid = false;
5446    if (TemplateParameterList *TemplateParams
5447          = MatchTemplateParametersToScopeSpecifier(
5448                                  D.getDeclSpec().getLocStart(),
5449                                  D.getIdentifierLoc(),
5450                                  D.getCXXScopeSpec(),
5451                                  TemplateParamLists.data(),
5452                                  TemplateParamLists.size(),
5453                                  isFriend,
5454                                  isExplicitSpecialization,
5455                                  Invalid)) {
5456      if (TemplateParams->size() > 0) {
5457        // This is a function template
5458
5459        // Check that we can declare a template here.
5460        if (CheckTemplateDeclScope(S, TemplateParams))
5461          return 0;
5462
5463        // A destructor cannot be a template.
5464        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5465          Diag(NewFD->getLocation(), diag::err_destructor_template);
5466          return 0;
5467        }
5468
5469        // If we're adding a template to a dependent context, we may need to
5470        // rebuilding some of the types used within the template parameter list,
5471        // now that we know what the current instantiation is.
5472        if (DC->isDependentContext()) {
5473          ContextRAII SavedContext(*this, DC);
5474          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5475            Invalid = true;
5476        }
5477
5478
5479        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5480                                                        NewFD->getLocation(),
5481                                                        Name, TemplateParams,
5482                                                        NewFD);
5483        FunctionTemplate->setLexicalDeclContext(CurContext);
5484        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5485
5486        // For source fidelity, store the other template param lists.
5487        if (TemplateParamLists.size() > 1) {
5488          NewFD->setTemplateParameterListsInfo(Context,
5489                                               TemplateParamLists.size() - 1,
5490                                               TemplateParamLists.data());
5491        }
5492      } else {
5493        // This is a function template specialization.
5494        isFunctionTemplateSpecialization = true;
5495        // For source fidelity, store all the template param lists.
5496        NewFD->setTemplateParameterListsInfo(Context,
5497                                             TemplateParamLists.size(),
5498                                             TemplateParamLists.data());
5499
5500        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5501        if (isFriend) {
5502          // We want to remove the "template<>", found here.
5503          SourceRange RemoveRange = TemplateParams->getSourceRange();
5504
5505          // If we remove the template<> and the name is not a
5506          // template-id, we're actually silently creating a problem:
5507          // the friend declaration will refer to an untemplated decl,
5508          // and clearly the user wants a template specialization.  So
5509          // we need to insert '<>' after the name.
5510          SourceLocation InsertLoc;
5511          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5512            InsertLoc = D.getName().getSourceRange().getEnd();
5513            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5514          }
5515
5516          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5517            << Name << RemoveRange
5518            << FixItHint::CreateRemoval(RemoveRange)
5519            << FixItHint::CreateInsertion(InsertLoc, "<>");
5520        }
5521      }
5522    }
5523    else {
5524      // All template param lists were matched against the scope specifier:
5525      // this is NOT (an explicit specialization of) a template.
5526      if (TemplateParamLists.size() > 0)
5527        // For source fidelity, store all the template param lists.
5528        NewFD->setTemplateParameterListsInfo(Context,
5529                                             TemplateParamLists.size(),
5530                                             TemplateParamLists.data());
5531    }
5532
5533    if (Invalid) {
5534      NewFD->setInvalidDecl();
5535      if (FunctionTemplate)
5536        FunctionTemplate->setInvalidDecl();
5537    }
5538
5539    // C++ [dcl.fct.spec]p5:
5540    //   The virtual specifier shall only be used in declarations of
5541    //   nonstatic class member functions that appear within a
5542    //   member-specification of a class declaration; see 10.3.
5543    //
5544    if (isVirtual && !NewFD->isInvalidDecl()) {
5545      if (!isVirtualOkay) {
5546        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5547             diag::err_virtual_non_function);
5548      } else if (!CurContext->isRecord()) {
5549        // 'virtual' was specified outside of the class.
5550        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5551             diag::err_virtual_out_of_class)
5552          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5553      } else if (NewFD->getDescribedFunctionTemplate()) {
5554        // C++ [temp.mem]p3:
5555        //  A member function template shall not be virtual.
5556        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5557             diag::err_virtual_member_function_template)
5558          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5559      } else {
5560        // Okay: Add virtual to the method.
5561        NewFD->setVirtualAsWritten(true);
5562      }
5563    }
5564
5565    // C++ [dcl.fct.spec]p3:
5566    //  The inline specifier shall not appear on a block scope function
5567    //  declaration.
5568    if (isInline && !NewFD->isInvalidDecl()) {
5569      if (CurContext->isFunctionOrMethod()) {
5570        // 'inline' is not allowed on block scope function declaration.
5571        Diag(D.getDeclSpec().getInlineSpecLoc(),
5572             diag::err_inline_declaration_block_scope) << Name
5573          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5574      }
5575    }
5576
5577    // C++ [dcl.fct.spec]p6:
5578    //  The explicit specifier shall be used only in the declaration of a
5579    //  constructor or conversion function within its class definition;
5580    //  see 12.3.1 and 12.3.2.
5581    if (isExplicit && !NewFD->isInvalidDecl()) {
5582      if (!CurContext->isRecord()) {
5583        // 'explicit' was specified outside of the class.
5584        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5585             diag::err_explicit_out_of_class)
5586          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5587      } else if (!isa<CXXConstructorDecl>(NewFD) &&
5588                 !isa<CXXConversionDecl>(NewFD)) {
5589        // 'explicit' was specified on a function that wasn't a constructor
5590        // or conversion function.
5591        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5592             diag::err_explicit_non_ctor_or_conv_function)
5593          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5594      }
5595    }
5596
5597    if (isConstexpr) {
5598      // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5599      // are implicitly inline.
5600      NewFD->setImplicitlyInline();
5601
5602      // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5603      // be either constructors or to return a literal type. Therefore,
5604      // destructors cannot be declared constexpr.
5605      if (isa<CXXDestructorDecl>(NewFD))
5606        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5607    }
5608
5609    // If __module_private__ was specified, mark the function accordingly.
5610    if (D.getDeclSpec().isModulePrivateSpecified()) {
5611      if (isFunctionTemplateSpecialization) {
5612        SourceLocation ModulePrivateLoc
5613          = D.getDeclSpec().getModulePrivateSpecLoc();
5614        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5615          << 0
5616          << FixItHint::CreateRemoval(ModulePrivateLoc);
5617      } else {
5618        NewFD->setModulePrivate();
5619        if (FunctionTemplate)
5620          FunctionTemplate->setModulePrivate();
5621      }
5622    }
5623
5624    if (isFriend) {
5625      // For now, claim that the objects have no previous declaration.
5626      if (FunctionTemplate) {
5627        FunctionTemplate->setObjectOfFriendDecl(false);
5628        FunctionTemplate->setAccess(AS_public);
5629      }
5630      NewFD->setObjectOfFriendDecl(false);
5631      NewFD->setAccess(AS_public);
5632    }
5633
5634    // If a function is defined as defaulted or deleted, mark it as such now.
5635    switch (D.getFunctionDefinitionKind()) {
5636      case FDK_Declaration:
5637      case FDK_Definition:
5638        break;
5639
5640      case FDK_Defaulted:
5641        NewFD->setDefaulted();
5642        break;
5643
5644      case FDK_Deleted:
5645        NewFD->setDeletedAsWritten();
5646        break;
5647    }
5648
5649    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5650        D.isFunctionDefinition()) {
5651      // C++ [class.mfct]p2:
5652      //   A member function may be defined (8.4) in its class definition, in
5653      //   which case it is an inline member function (7.1.2)
5654      NewFD->setImplicitlyInline();
5655    }
5656
5657    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5658        !CurContext->isRecord()) {
5659      // C++ [class.static]p1:
5660      //   A data or function member of a class may be declared static
5661      //   in a class definition, in which case it is a static member of
5662      //   the class.
5663
5664      // Complain about the 'static' specifier if it's on an out-of-line
5665      // member function definition.
5666      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5667           diag::err_static_out_of_line)
5668        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5669    }
5670
5671    // C++11 [except.spec]p15:
5672    //   A deallocation function with no exception-specification is treated
5673    //   as if it were specified with noexcept(true).
5674    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
5675    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
5676         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
5677        getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
5678      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5679      EPI.ExceptionSpecType = EST_BasicNoexcept;
5680      NewFD->setType(Context.getFunctionType(FPT->getResultType(),
5681                                             FPT->arg_type_begin(),
5682                                             FPT->getNumArgs(), EPI));
5683    }
5684  }
5685
5686  // Filter out previous declarations that don't match the scope.
5687  FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5688                       isExplicitSpecialization ||
5689                       isFunctionTemplateSpecialization);
5690
5691  // Handle GNU asm-label extension (encoded as an attribute).
5692  if (Expr *E = (Expr*) D.getAsmLabel()) {
5693    // The parser guarantees this is a string.
5694    StringLiteral *SE = cast<StringLiteral>(E);
5695    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5696                                                SE->getString()));
5697  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5698    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5699      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5700    if (I != ExtnameUndeclaredIdentifiers.end()) {
5701      NewFD->addAttr(I->second);
5702      ExtnameUndeclaredIdentifiers.erase(I);
5703    }
5704  }
5705
5706  // Copy the parameter declarations from the declarator D to the function
5707  // declaration NewFD, if they are available.  First scavenge them into Params.
5708  SmallVector<ParmVarDecl*, 16> Params;
5709  if (D.isFunctionDeclarator()) {
5710    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5711
5712    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5713    // function that takes no arguments, not a function that takes a
5714    // single void argument.
5715    // We let through "const void" here because Sema::GetTypeForDeclarator
5716    // already checks for that case.
5717    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5718        FTI.ArgInfo[0].Param &&
5719        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5720      // Empty arg list, don't push any params.
5721      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
5722    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5723      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5724        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5725        assert(Param->getDeclContext() != NewFD && "Was set before ?");
5726        Param->setDeclContext(NewFD);
5727        Params.push_back(Param);
5728
5729        if (Param->isInvalidDecl())
5730          NewFD->setInvalidDecl();
5731      }
5732    }
5733
5734  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5735    // When we're declaring a function with a typedef, typeof, etc as in the
5736    // following example, we'll need to synthesize (unnamed)
5737    // parameters for use in the declaration.
5738    //
5739    // @code
5740    // typedef void fn(int);
5741    // fn f;
5742    // @endcode
5743
5744    // Synthesize a parameter for each argument type.
5745    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5746         AE = FT->arg_type_end(); AI != AE; ++AI) {
5747      ParmVarDecl *Param =
5748        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5749      Param->setScopeInfo(0, Params.size());
5750      Params.push_back(Param);
5751    }
5752  } else {
5753    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5754           "Should not need args for typedef of non-prototype fn");
5755  }
5756
5757  // Finally, we know we have the right number of parameters, install them.
5758  NewFD->setParams(Params);
5759
5760  // Find all anonymous symbols defined during the declaration of this function
5761  // and add to NewFD. This lets us track decls such 'enum Y' in:
5762  //
5763  //   void f(enum Y {AA} x) {}
5764  //
5765  // which would otherwise incorrectly end up in the translation unit scope.
5766  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5767  DeclsInPrototypeScope.clear();
5768
5769  // Process the non-inheritable attributes on this declaration.
5770  ProcessDeclAttributes(S, NewFD, D,
5771                        /*NonInheritable=*/true, /*Inheritable=*/false);
5772
5773  // Functions returning a variably modified type violate C99 6.7.5.2p2
5774  // because all functions have linkage.
5775  if (!NewFD->isInvalidDecl() &&
5776      NewFD->getResultType()->isVariablyModifiedType()) {
5777    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5778    NewFD->setInvalidDecl();
5779  }
5780
5781  // Handle attributes.
5782  ProcessDeclAttributes(S, NewFD, D,
5783                        /*NonInheritable=*/false, /*Inheritable=*/true);
5784
5785  QualType RetType = NewFD->getResultType();
5786  const CXXRecordDecl *Ret = RetType->isRecordType() ?
5787      RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
5788  if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
5789      Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
5790    const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5791    if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
5792      NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
5793                                                        Context));
5794    }
5795  }
5796
5797  if (!getLangOpts().CPlusPlus) {
5798    // Perform semantic checking on the function declaration.
5799    bool isExplicitSpecialization=false;
5800    if (!NewFD->isInvalidDecl()) {
5801      if (NewFD->isMain())
5802        CheckMain(NewFD, D.getDeclSpec());
5803      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5804                                                  isExplicitSpecialization));
5805    }
5806    // Make graceful recovery from an invalid redeclaration.
5807    else if (!Previous.empty())
5808           D.setRedeclaration(true);
5809    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5810            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5811           "previous declaration set still overloaded");
5812  } else {
5813    // If the declarator is a template-id, translate the parser's template
5814    // argument list into our AST format.
5815    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5816      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5817      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5818      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5819      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5820                                         TemplateId->NumArgs);
5821      translateTemplateArguments(TemplateArgsPtr,
5822                                 TemplateArgs);
5823
5824      HasExplicitTemplateArgs = true;
5825
5826      if (NewFD->isInvalidDecl()) {
5827        HasExplicitTemplateArgs = false;
5828      } else if (FunctionTemplate) {
5829        // Function template with explicit template arguments.
5830        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5831          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5832
5833        HasExplicitTemplateArgs = false;
5834      } else if (!isFunctionTemplateSpecialization &&
5835                 !D.getDeclSpec().isFriendSpecified()) {
5836        // We have encountered something that the user meant to be a
5837        // specialization (because it has explicitly-specified template
5838        // arguments) but that was not introduced with a "template<>" (or had
5839        // too few of them).
5840        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5841          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5842          << FixItHint::CreateInsertion(
5843                                    D.getDeclSpec().getLocStart(),
5844                                        "template<> ");
5845        isFunctionTemplateSpecialization = true;
5846      } else {
5847        // "friend void foo<>(int);" is an implicit specialization decl.
5848        isFunctionTemplateSpecialization = true;
5849      }
5850    } else if (isFriend && isFunctionTemplateSpecialization) {
5851      // This combination is only possible in a recovery case;  the user
5852      // wrote something like:
5853      //   template <> friend void foo(int);
5854      // which we're recovering from as if the user had written:
5855      //   friend void foo<>(int);
5856      // Go ahead and fake up a template id.
5857      HasExplicitTemplateArgs = true;
5858        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5859      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5860    }
5861
5862    // If it's a friend (and only if it's a friend), it's possible
5863    // that either the specialized function type or the specialized
5864    // template is dependent, and therefore matching will fail.  In
5865    // this case, don't check the specialization yet.
5866    bool InstantiationDependent = false;
5867    if (isFunctionTemplateSpecialization && isFriend &&
5868        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5869         TemplateSpecializationType::anyDependentTemplateArguments(
5870            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5871            InstantiationDependent))) {
5872      assert(HasExplicitTemplateArgs &&
5873             "friend function specialization without template args");
5874      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5875                                                       Previous))
5876        NewFD->setInvalidDecl();
5877    } else if (isFunctionTemplateSpecialization) {
5878      if (CurContext->isDependentContext() && CurContext->isRecord()
5879          && !isFriend) {
5880        isDependentClassScopeExplicitSpecialization = true;
5881        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5882          diag::ext_function_specialization_in_class :
5883          diag::err_function_specialization_in_class)
5884          << NewFD->getDeclName();
5885      } else if (CheckFunctionTemplateSpecialization(NewFD,
5886                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5887                                                     Previous))
5888        NewFD->setInvalidDecl();
5889
5890      // C++ [dcl.stc]p1:
5891      //   A storage-class-specifier shall not be specified in an explicit
5892      //   specialization (14.7.3)
5893      if (SC != SC_None) {
5894        if (SC != NewFD->getStorageClass())
5895          Diag(NewFD->getLocation(),
5896               diag::err_explicit_specialization_inconsistent_storage_class)
5897            << SC
5898            << FixItHint::CreateRemoval(
5899                                      D.getDeclSpec().getStorageClassSpecLoc());
5900
5901        else
5902          Diag(NewFD->getLocation(),
5903               diag::ext_explicit_specialization_storage_class)
5904            << FixItHint::CreateRemoval(
5905                                      D.getDeclSpec().getStorageClassSpecLoc());
5906      }
5907
5908    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5909      if (CheckMemberSpecialization(NewFD, Previous))
5910          NewFD->setInvalidDecl();
5911    }
5912
5913    // Perform semantic checking on the function declaration.
5914    if (!isDependentClassScopeExplicitSpecialization) {
5915      if (NewFD->isInvalidDecl()) {
5916        // If this is a class member, mark the class invalid immediately.
5917        // This avoids some consistency errors later.
5918        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5919          methodDecl->getParent()->setInvalidDecl();
5920      } else {
5921        if (NewFD->isMain())
5922          CheckMain(NewFD, D.getDeclSpec());
5923        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5924                                                    isExplicitSpecialization));
5925      }
5926    }
5927
5928    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5929            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5930           "previous declaration set still overloaded");
5931
5932    NamedDecl *PrincipalDecl = (FunctionTemplate
5933                                ? cast<NamedDecl>(FunctionTemplate)
5934                                : NewFD);
5935
5936    if (isFriend && D.isRedeclaration()) {
5937      AccessSpecifier Access = AS_public;
5938      if (!NewFD->isInvalidDecl())
5939        Access = NewFD->getPreviousDecl()->getAccess();
5940
5941      NewFD->setAccess(Access);
5942      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5943
5944      PrincipalDecl->setObjectOfFriendDecl(true);
5945    }
5946
5947    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5948        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5949      PrincipalDecl->setNonMemberOperator();
5950
5951    // If we have a function template, check the template parameter
5952    // list. This will check and merge default template arguments.
5953    if (FunctionTemplate) {
5954      FunctionTemplateDecl *PrevTemplate =
5955                                     FunctionTemplate->getPreviousDecl();
5956      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5957                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5958                            D.getDeclSpec().isFriendSpecified()
5959                              ? (D.isFunctionDefinition()
5960                                   ? TPC_FriendFunctionTemplateDefinition
5961                                   : TPC_FriendFunctionTemplate)
5962                              : (D.getCXXScopeSpec().isSet() &&
5963                                 DC && DC->isRecord() &&
5964                                 DC->isDependentContext())
5965                                  ? TPC_ClassTemplateMember
5966                                  : TPC_FunctionTemplate);
5967    }
5968
5969    if (NewFD->isInvalidDecl()) {
5970      // Ignore all the rest of this.
5971    } else if (!D.isRedeclaration()) {
5972      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5973                                       AddToScope };
5974      // Fake up an access specifier if it's supposed to be a class member.
5975      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5976        NewFD->setAccess(AS_public);
5977
5978      // Qualified decls generally require a previous declaration.
5979      if (D.getCXXScopeSpec().isSet()) {
5980        // ...with the major exception of templated-scope or
5981        // dependent-scope friend declarations.
5982
5983        // TODO: we currently also suppress this check in dependent
5984        // contexts because (1) the parameter depth will be off when
5985        // matching friend templates and (2) we might actually be
5986        // selecting a friend based on a dependent factor.  But there
5987        // are situations where these conditions don't apply and we
5988        // can actually do this check immediately.
5989        if (isFriend &&
5990            (TemplateParamLists.size() ||
5991             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5992             CurContext->isDependentContext())) {
5993          // ignore these
5994        } else {
5995          // The user tried to provide an out-of-line definition for a
5996          // function that is a member of a class or namespace, but there
5997          // was no such member function declared (C++ [class.mfct]p2,
5998          // C++ [namespace.memdef]p2). For example:
5999          //
6000          // class X {
6001          //   void f() const;
6002          // };
6003          //
6004          // void X::f() { } // ill-formed
6005          //
6006          // Complain about this problem, and attempt to suggest close
6007          // matches (e.g., those that differ only in cv-qualifiers and
6008          // whether the parameter types are references).
6009
6010          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
6011                                                               NewFD,
6012                                                               ExtraArgs)) {
6013            AddToScope = ExtraArgs.AddToScope;
6014            return Result;
6015          }
6016        }
6017
6018        // Unqualified local friend declarations are required to resolve
6019        // to something.
6020      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
6021        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
6022                                                             NewFD,
6023                                                             ExtraArgs)) {
6024          AddToScope = ExtraArgs.AddToScope;
6025          return Result;
6026        }
6027      }
6028
6029    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
6030               !isFriend && !isFunctionTemplateSpecialization &&
6031               !isExplicitSpecialization) {
6032      // An out-of-line member function declaration must also be a
6033      // definition (C++ [dcl.meaning]p1).
6034      // Note that this is not the case for explicit specializations of
6035      // function templates or member functions of class templates, per
6036      // C++ [temp.expl.spec]p2. We also allow these declarations as an
6037      // extension for compatibility with old SWIG code which likes to
6038      // generate them.
6039      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
6040        << D.getCXXScopeSpec().getRange();
6041    }
6042  }
6043
6044  AddKnownFunctionAttributes(NewFD);
6045
6046  if (NewFD->hasAttr<OverloadableAttr>() &&
6047      !NewFD->getType()->getAs<FunctionProtoType>()) {
6048    Diag(NewFD->getLocation(),
6049         diag::err_attribute_overloadable_no_prototype)
6050      << NewFD;
6051
6052    // Turn this into a variadic function with no parameters.
6053    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
6054    FunctionProtoType::ExtProtoInfo EPI;
6055    EPI.Variadic = true;
6056    EPI.ExtInfo = FT->getExtInfo();
6057
6058    QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
6059    NewFD->setType(R);
6060  }
6061
6062  // If there's a #pragma GCC visibility in scope, and this isn't a class
6063  // member, set the visibility of this function.
6064  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
6065    AddPushedVisibilityAttribute(NewFD);
6066
6067  // If there's a #pragma clang arc_cf_code_audited in scope, consider
6068  // marking the function.
6069  AddCFAuditedAttribute(NewFD);
6070
6071  // If this is a locally-scoped extern C function, update the
6072  // map of such names.
6073  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
6074      && !NewFD->isInvalidDecl())
6075    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
6076
6077  // Set this FunctionDecl's range up to the right paren.
6078  NewFD->setRangeEnd(D.getSourceRange().getEnd());
6079
6080  if (getLangOpts().CPlusPlus) {
6081    if (FunctionTemplate) {
6082      if (NewFD->isInvalidDecl())
6083        FunctionTemplate->setInvalidDecl();
6084      return FunctionTemplate;
6085    }
6086  }
6087
6088  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
6089  if ((getLangOpts().OpenCLVersion >= 120)
6090      && NewFD->hasAttr<OpenCLKernelAttr>()
6091      && (SC == SC_Static)) {
6092    Diag(D.getIdentifierLoc(), diag::err_static_kernel);
6093    D.setInvalidType();
6094  }
6095
6096  MarkUnusedFileScopedDecl(NewFD);
6097
6098  if (getLangOpts().CUDA)
6099    if (IdentifierInfo *II = NewFD->getIdentifier())
6100      if (!NewFD->isInvalidDecl() &&
6101          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6102        if (II->isStr("cudaConfigureCall")) {
6103          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6104            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6105
6106          Context.setcudaConfigureCallDecl(NewFD);
6107        }
6108      }
6109
6110  // Here we have an function template explicit specialization at class scope.
6111  // The actually specialization will be postponed to template instatiation
6112  // time via the ClassScopeFunctionSpecializationDecl node.
6113  if (isDependentClassScopeExplicitSpecialization) {
6114    ClassScopeFunctionSpecializationDecl *NewSpec =
6115                         ClassScopeFunctionSpecializationDecl::Create(
6116                                Context, CurContext, SourceLocation(),
6117                                cast<CXXMethodDecl>(NewFD),
6118                                HasExplicitTemplateArgs, TemplateArgs);
6119    CurContext->addDecl(NewSpec);
6120    AddToScope = false;
6121  }
6122
6123  return NewFD;
6124}
6125
6126/// \brief Perform semantic checking of a new function declaration.
6127///
6128/// Performs semantic analysis of the new function declaration
6129/// NewFD. This routine performs all semantic checking that does not
6130/// require the actual declarator involved in the declaration, and is
6131/// used both for the declaration of functions as they are parsed
6132/// (called via ActOnDeclarator) and for the declaration of functions
6133/// that have been instantiated via C++ template instantiation (called
6134/// via InstantiateDecl).
6135///
6136/// \param IsExplicitSpecialization whether this new function declaration is
6137/// an explicit specialization of the previous declaration.
6138///
6139/// This sets NewFD->isInvalidDecl() to true if there was an error.
6140///
6141/// \returns true if the function declaration is a redeclaration.
6142bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
6143                                    LookupResult &Previous,
6144                                    bool IsExplicitSpecialization) {
6145  assert(!NewFD->getResultType()->isVariablyModifiedType()
6146         && "Variably modified return types are not handled here");
6147
6148  // Check for a previous declaration of this name.
6149  if (Previous.empty() && NewFD->isExternC()) {
6150    // Since we did not find anything by this name and we're declaring
6151    // an extern "C" function, look for a non-visible extern "C"
6152    // declaration with the same name.
6153    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6154      = findLocallyScopedExternCDecl(NewFD->getDeclName());
6155    if (Pos != LocallyScopedExternCDecls.end())
6156      Previous.addDecl(Pos->second);
6157  }
6158
6159  // Filter out any non-conflicting previous declarations.
6160  filterNonConflictingPreviousDecls(Context, NewFD, Previous);
6161
6162  bool Redeclaration = false;
6163
6164  // Merge or overload the declaration with an existing declaration of
6165  // the same name, if appropriate.
6166  if (!Previous.empty()) {
6167    // Determine whether NewFD is an overload of PrevDecl or
6168    // a declaration that requires merging. If it's an overload,
6169    // there's no more work to do here; we'll just add the new
6170    // function to the scope.
6171
6172    NamedDecl *OldDecl = 0;
6173    if (!AllowOverloadingOfFunction(Previous, Context)) {
6174      Redeclaration = true;
6175      OldDecl = Previous.getFoundDecl();
6176    } else {
6177      switch (CheckOverload(S, NewFD, Previous, OldDecl,
6178                            /*NewIsUsingDecl*/ false)) {
6179      case Ovl_Match:
6180        Redeclaration = true;
6181        break;
6182
6183      case Ovl_NonFunction:
6184        Redeclaration = true;
6185        break;
6186
6187      case Ovl_Overload:
6188        Redeclaration = false;
6189        break;
6190      }
6191
6192      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
6193        // If a function name is overloadable in C, then every function
6194        // with that name must be marked "overloadable".
6195        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6196          << Redeclaration << NewFD;
6197        NamedDecl *OverloadedDecl = 0;
6198        if (Redeclaration)
6199          OverloadedDecl = OldDecl;
6200        else if (!Previous.empty())
6201          OverloadedDecl = Previous.getRepresentativeDecl();
6202        if (OverloadedDecl)
6203          Diag(OverloadedDecl->getLocation(),
6204               diag::note_attribute_overloadable_prev_overload);
6205        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6206                                                        Context));
6207      }
6208    }
6209
6210    if (Redeclaration) {
6211      // NewFD and OldDecl represent declarations that need to be
6212      // merged.
6213      if (MergeFunctionDecl(NewFD, OldDecl, S)) {
6214        NewFD->setInvalidDecl();
6215        return Redeclaration;
6216      }
6217
6218      Previous.clear();
6219      Previous.addDecl(OldDecl);
6220
6221      if (FunctionTemplateDecl *OldTemplateDecl
6222                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
6223        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
6224        FunctionTemplateDecl *NewTemplateDecl
6225          = NewFD->getDescribedFunctionTemplate();
6226        assert(NewTemplateDecl && "Template/non-template mismatch");
6227        if (CXXMethodDecl *Method
6228              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6229          Method->setAccess(OldTemplateDecl->getAccess());
6230          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6231        }
6232
6233        // If this is an explicit specialization of a member that is a function
6234        // template, mark it as a member specialization.
6235        if (IsExplicitSpecialization &&
6236            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6237          NewTemplateDecl->setMemberSpecialization();
6238          assert(OldTemplateDecl->isMemberSpecialization());
6239        }
6240
6241      } else {
6242        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
6243          NewFD->setAccess(OldDecl->getAccess());
6244        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
6245      }
6246    }
6247  }
6248
6249  // Semantic checking for this function declaration (in isolation).
6250  if (getLangOpts().CPlusPlus) {
6251    // C++-specific checks.
6252    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6253      CheckConstructor(Constructor);
6254    } else if (CXXDestructorDecl *Destructor =
6255                dyn_cast<CXXDestructorDecl>(NewFD)) {
6256      CXXRecordDecl *Record = Destructor->getParent();
6257      QualType ClassType = Context.getTypeDeclType(Record);
6258
6259      // FIXME: Shouldn't we be able to perform this check even when the class
6260      // type is dependent? Both gcc and edg can handle that.
6261      if (!ClassType->isDependentType()) {
6262        DeclarationName Name
6263          = Context.DeclarationNames.getCXXDestructorName(
6264                                        Context.getCanonicalType(ClassType));
6265        if (NewFD->getDeclName() != Name) {
6266          Diag(NewFD->getLocation(), diag::err_destructor_name);
6267          NewFD->setInvalidDecl();
6268          return Redeclaration;
6269        }
6270      }
6271    } else if (CXXConversionDecl *Conversion
6272               = dyn_cast<CXXConversionDecl>(NewFD)) {
6273      ActOnConversionDeclarator(Conversion);
6274    }
6275
6276    // Find any virtual functions that this function overrides.
6277    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6278      if (!Method->isFunctionTemplateSpecialization() &&
6279          !Method->getDescribedFunctionTemplate() &&
6280          Method->isCanonicalDecl()) {
6281        if (AddOverriddenMethods(Method->getParent(), Method)) {
6282          // If the function was marked as "static", we have a problem.
6283          if (NewFD->getStorageClass() == SC_Static) {
6284            ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
6285          }
6286        }
6287      }
6288
6289      if (Method->isStatic())
6290        checkThisInStaticMemberFunctionType(Method);
6291    }
6292
6293    // Extra checking for C++ overloaded operators (C++ [over.oper]).
6294    if (NewFD->isOverloadedOperator() &&
6295        CheckOverloadedOperatorDeclaration(NewFD)) {
6296      NewFD->setInvalidDecl();
6297      return Redeclaration;
6298    }
6299
6300    // Extra checking for C++0x literal operators (C++0x [over.literal]).
6301    if (NewFD->getLiteralIdentifier() &&
6302        CheckLiteralOperatorDeclaration(NewFD)) {
6303      NewFD->setInvalidDecl();
6304      return Redeclaration;
6305    }
6306
6307    // In C++, check default arguments now that we have merged decls. Unless
6308    // the lexical context is the class, because in this case this is done
6309    // during delayed parsing anyway.
6310    if (!CurContext->isRecord())
6311      CheckCXXDefaultArguments(NewFD);
6312
6313    // If this function declares a builtin function, check the type of this
6314    // declaration against the expected type for the builtin.
6315    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6316      ASTContext::GetBuiltinTypeError Error;
6317      LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
6318      QualType T = Context.GetBuiltinType(BuiltinID, Error);
6319      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6320        // The type of this function differs from the type of the builtin,
6321        // so forget about the builtin entirely.
6322        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6323      }
6324    }
6325
6326    // If this function is declared as being extern "C", then check to see if
6327    // the function returns a UDT (class, struct, or union type) that is not C
6328    // compatible, and if it does, warn the user.
6329    if (NewFD->hasCLanguageLinkage()) {
6330      QualType R = NewFD->getResultType();
6331      if (R->isIncompleteType() && !R->isVoidType())
6332        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6333            << NewFD << R;
6334      else if (!R.isPODType(Context) && !R->isVoidType() &&
6335               !R->isObjCObjectPointerType())
6336        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
6337    }
6338  }
6339  return Redeclaration;
6340}
6341
6342void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
6343  // C++11 [basic.start.main]p3:  A program that declares main to be inline,
6344  //   static or constexpr is ill-formed.
6345  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
6346  //   shall not appear in a declaration of main.
6347  // static main is not an error under C99, but we should warn about it.
6348  if (FD->getStorageClass() == SC_Static)
6349    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
6350         ? diag::err_static_main : diag::warn_static_main)
6351      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6352  if (FD->isInlineSpecified())
6353    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6354      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
6355  if (FD->isConstexpr()) {
6356    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6357      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6358    FD->setConstexpr(false);
6359  }
6360
6361  QualType T = FD->getType();
6362  assert(T->isFunctionType() && "function decl is not of function type");
6363  const FunctionType* FT = T->castAs<FunctionType>();
6364
6365  // All the standards say that main() should should return 'int'.
6366  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6367    // In C and C++, main magically returns 0 if you fall off the end;
6368    // set the flag which tells us that.
6369    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6370    FD->setHasImplicitReturnZero(true);
6371
6372  // In C with GNU extensions we allow main() to have non-integer return
6373  // type, but we should warn about the extension, and we disable the
6374  // implicit-return-zero rule.
6375  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
6376    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6377
6378  // Otherwise, this is just a flat-out error.
6379  } else {
6380    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
6381    FD->setInvalidDecl(true);
6382  }
6383
6384  // Treat protoless main() as nullary.
6385  if (isa<FunctionNoProtoType>(FT)) return;
6386
6387  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6388  unsigned nparams = FTP->getNumArgs();
6389  assert(FD->getNumParams() == nparams);
6390
6391  bool HasExtraParameters = (nparams > 3);
6392
6393  // Darwin passes an undocumented fourth argument of type char**.  If
6394  // other platforms start sprouting these, the logic below will start
6395  // getting shifty.
6396  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
6397    HasExtraParameters = false;
6398
6399  if (HasExtraParameters) {
6400    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6401    FD->setInvalidDecl(true);
6402    nparams = 3;
6403  }
6404
6405  // FIXME: a lot of the following diagnostics would be improved
6406  // if we had some location information about types.
6407
6408  QualType CharPP =
6409    Context.getPointerType(Context.getPointerType(Context.CharTy));
6410  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
6411
6412  for (unsigned i = 0; i < nparams; ++i) {
6413    QualType AT = FTP->getArgType(i);
6414
6415    bool mismatch = true;
6416
6417    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6418      mismatch = false;
6419    else if (Expected[i] == CharPP) {
6420      // As an extension, the following forms are okay:
6421      //   char const **
6422      //   char const * const *
6423      //   char * const *
6424
6425      QualifierCollector qs;
6426      const PointerType* PT;
6427      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6428          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
6429          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6430        qs.removeConst();
6431        mismatch = !qs.empty();
6432      }
6433    }
6434
6435    if (mismatch) {
6436      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6437      // TODO: suggest replacing given type with expected type
6438      FD->setInvalidDecl(true);
6439    }
6440  }
6441
6442  if (nparams == 1 && !FD->isInvalidDecl()) {
6443    Diag(FD->getLocation(), diag::warn_main_one_arg);
6444  }
6445
6446  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6447    Diag(FD->getLocation(), diag::err_main_template_decl);
6448    FD->setInvalidDecl();
6449  }
6450}
6451
6452bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6453  // FIXME: Need strict checking.  In C89, we need to check for
6454  // any assignment, increment, decrement, function-calls, or
6455  // commas outside of a sizeof.  In C99, it's the same list,
6456  // except that the aforementioned are allowed in unevaluated
6457  // expressions.  Everything else falls under the
6458  // "may accept other forms of constant expressions" exception.
6459  // (We never end up here for C++, so the constant expression
6460  // rules there don't matter.)
6461  if (Init->isConstantInitializer(Context, false))
6462    return false;
6463  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6464    << Init->getSourceRange();
6465  return true;
6466}
6467
6468namespace {
6469  // Visits an initialization expression to see if OrigDecl is evaluated in
6470  // its own initialization and throws a warning if it does.
6471  class SelfReferenceChecker
6472      : public EvaluatedExprVisitor<SelfReferenceChecker> {
6473    Sema &S;
6474    Decl *OrigDecl;
6475    bool isRecordType;
6476    bool isPODType;
6477    bool isReferenceType;
6478
6479  public:
6480    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6481
6482    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6483                                                    S(S), OrigDecl(OrigDecl) {
6484      isPODType = false;
6485      isRecordType = false;
6486      isReferenceType = false;
6487      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6488        isPODType = VD->getType().isPODType(S.Context);
6489        isRecordType = VD->getType()->isRecordType();
6490        isReferenceType = VD->getType()->isReferenceType();
6491      }
6492    }
6493
6494    // For most expressions, the cast is directly above the DeclRefExpr.
6495    // For conditional operators, the cast can be outside the conditional
6496    // operator if both expressions are DeclRefExpr's.
6497    void HandleValue(Expr *E) {
6498      if (isReferenceType)
6499        return;
6500      E = E->IgnoreParenImpCasts();
6501      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6502        HandleDeclRefExpr(DRE);
6503        return;
6504      }
6505
6506      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6507        HandleValue(CO->getTrueExpr());
6508        HandleValue(CO->getFalseExpr());
6509        return;
6510      }
6511
6512      if (isa<MemberExpr>(E)) {
6513        Expr *Base = E->IgnoreParenImpCasts();
6514        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6515          // Check for static member variables and don't warn on them.
6516          if (!isa<FieldDecl>(ME->getMemberDecl()))
6517            return;
6518          Base = ME->getBase()->IgnoreParenImpCasts();
6519        }
6520        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
6521          HandleDeclRefExpr(DRE);
6522        return;
6523      }
6524    }
6525
6526    // Reference types are handled here since all uses of references are
6527    // bad, not just r-value uses.
6528    void VisitDeclRefExpr(DeclRefExpr *E) {
6529      if (isReferenceType)
6530        HandleDeclRefExpr(E);
6531    }
6532
6533    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6534      if (E->getCastKind() == CK_LValueToRValue ||
6535          (isRecordType && E->getCastKind() == CK_NoOp))
6536        HandleValue(E->getSubExpr());
6537
6538      Inherited::VisitImplicitCastExpr(E);
6539    }
6540
6541    void VisitMemberExpr(MemberExpr *E) {
6542      // Don't warn on arrays since they can be treated as pointers.
6543      if (E->getType()->canDecayToPointerType()) return;
6544
6545      // Warn when a non-static method call is followed by non-static member
6546      // field accesses, which is followed by a DeclRefExpr.
6547      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
6548      bool Warn = (MD && !MD->isStatic());
6549      Expr *Base = E->getBase()->IgnoreParenImpCasts();
6550      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6551        if (!isa<FieldDecl>(ME->getMemberDecl()))
6552          Warn = false;
6553        Base = ME->getBase()->IgnoreParenImpCasts();
6554      }
6555
6556      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
6557        if (Warn)
6558          HandleDeclRefExpr(DRE);
6559        return;
6560      }
6561
6562      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
6563      // Visit that expression.
6564      Visit(Base);
6565    }
6566
6567    void VisitUnaryOperator(UnaryOperator *E) {
6568      // For POD record types, addresses of its own members are well-defined.
6569      if (E->getOpcode() == UO_AddrOf && isRecordType &&
6570          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
6571        if (!isPODType)
6572          HandleValue(E->getSubExpr());
6573        return;
6574      }
6575      Inherited::VisitUnaryOperator(E);
6576    }
6577
6578    void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6579
6580    void HandleDeclRefExpr(DeclRefExpr *DRE) {
6581      Decl* ReferenceDecl = DRE->getDecl();
6582      if (OrigDecl != ReferenceDecl) return;
6583      unsigned diag = isReferenceType
6584          ? diag::warn_uninit_self_reference_in_reference_init
6585          : diag::warn_uninit_self_reference_in_init;
6586      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6587                            S.PDiag(diag)
6588                              << DRE->getNameInfo().getName()
6589                              << OrigDecl->getLocation()
6590                              << DRE->getSourceRange());
6591    }
6592  };
6593
6594  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6595  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
6596                                 bool DirectInit) {
6597    // Parameters arguments are occassionially constructed with itself,
6598    // for instance, in recursive functions.  Skip them.
6599    if (isa<ParmVarDecl>(OrigDecl))
6600      return;
6601
6602    E = E->IgnoreParens();
6603
6604    // Skip checking T a = a where T is not a record or reference type.
6605    // Doing so is a way to silence uninitialized warnings.
6606    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
6607      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
6608        if (ICE->getCastKind() == CK_LValueToRValue)
6609          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
6610            if (DRE->getDecl() == OrigDecl)
6611              return;
6612
6613    SelfReferenceChecker(S, OrigDecl).Visit(E);
6614  }
6615}
6616
6617/// AddInitializerToDecl - Adds the initializer Init to the
6618/// declaration dcl. If DirectInit is true, this is C++ direct
6619/// initialization rather than copy initialization.
6620void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6621                                bool DirectInit, bool TypeMayContainAuto) {
6622  // If there is no declaration, there was an error parsing it.  Just ignore
6623  // the initializer.
6624  if (RealDecl == 0 || RealDecl->isInvalidDecl())
6625    return;
6626
6627  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6628    // With declarators parsed the way they are, the parser cannot
6629    // distinguish between a normal initializer and a pure-specifier.
6630    // Thus this grotesque test.
6631    IntegerLiteral *IL;
6632    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6633        Context.getCanonicalType(IL->getType()) == Context.IntTy)
6634      CheckPureMethod(Method, Init->getSourceRange());
6635    else {
6636      Diag(Method->getLocation(), diag::err_member_function_initialization)
6637        << Method->getDeclName() << Init->getSourceRange();
6638      Method->setInvalidDecl();
6639    }
6640    return;
6641  }
6642
6643  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6644  if (!VDecl) {
6645    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6646    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6647    RealDecl->setInvalidDecl();
6648    return;
6649  }
6650
6651  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6652
6653  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6654  AutoType *Auto = 0;
6655  if (TypeMayContainAuto &&
6656      (Auto = VDecl->getType()->getContainedAutoType()) &&
6657      !Auto->isDeduced()) {
6658    Expr *DeduceInit = Init;
6659    // Initializer could be a C++ direct-initializer. Deduction only works if it
6660    // contains exactly one expression.
6661    if (CXXDirectInit) {
6662      if (CXXDirectInit->getNumExprs() == 0) {
6663        // It isn't possible to write this directly, but it is possible to
6664        // end up in this situation with "auto x(some_pack...);"
6665        Diag(CXXDirectInit->getLocStart(),
6666             diag::err_auto_var_init_no_expression)
6667          << VDecl->getDeclName() << VDecl->getType()
6668          << VDecl->getSourceRange();
6669        RealDecl->setInvalidDecl();
6670        return;
6671      } else if (CXXDirectInit->getNumExprs() > 1) {
6672        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6673             diag::err_auto_var_init_multiple_expressions)
6674          << VDecl->getDeclName() << VDecl->getType()
6675          << VDecl->getSourceRange();
6676        RealDecl->setInvalidDecl();
6677        return;
6678      } else {
6679        DeduceInit = CXXDirectInit->getExpr(0);
6680      }
6681    }
6682    TypeSourceInfo *DeducedType = 0;
6683    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6684            DAR_Failed)
6685      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6686    if (!DeducedType) {
6687      RealDecl->setInvalidDecl();
6688      return;
6689    }
6690    VDecl->setTypeSourceInfo(DeducedType);
6691    VDecl->setType(DeducedType->getType());
6692    VDecl->ClearLVCache();
6693
6694    // In ARC, infer lifetime.
6695    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6696      VDecl->setInvalidDecl();
6697
6698    // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6699    // 'id' instead of a specific object type prevents most of our usual checks.
6700    // We only want to warn outside of template instantiations, though:
6701    // inside a template, the 'id' could have come from a parameter.
6702    if (ActiveTemplateInstantiations.empty() &&
6703        DeducedType->getType()->isObjCIdType()) {
6704      SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6705      Diag(Loc, diag::warn_auto_var_is_id)
6706        << VDecl->getDeclName() << DeduceInit->getSourceRange();
6707    }
6708
6709    // If this is a redeclaration, check that the type we just deduced matches
6710    // the previously declared type.
6711    if (VarDecl *Old = VDecl->getPreviousDecl())
6712      MergeVarDeclTypes(VDecl, Old);
6713  }
6714
6715  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6716    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6717    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6718    VDecl->setInvalidDecl();
6719    return;
6720  }
6721
6722  if (!VDecl->getType()->isDependentType()) {
6723    // A definition must end up with a complete type, which means it must be
6724    // complete with the restriction that an array type might be completed by
6725    // the initializer; note that later code assumes this restriction.
6726    QualType BaseDeclType = VDecl->getType();
6727    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6728      BaseDeclType = Array->getElementType();
6729    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6730                            diag::err_typecheck_decl_incomplete_type)) {
6731      RealDecl->setInvalidDecl();
6732      return;
6733    }
6734
6735    // The variable can not have an abstract class type.
6736    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6737                               diag::err_abstract_type_in_decl,
6738                               AbstractVariableType))
6739      VDecl->setInvalidDecl();
6740  }
6741
6742  const VarDecl *Def;
6743  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6744    Diag(VDecl->getLocation(), diag::err_redefinition)
6745      << VDecl->getDeclName();
6746    Diag(Def->getLocation(), diag::note_previous_definition);
6747    VDecl->setInvalidDecl();
6748    return;
6749  }
6750
6751  const VarDecl* PrevInit = 0;
6752  if (getLangOpts().CPlusPlus) {
6753    // C++ [class.static.data]p4
6754    //   If a static data member is of const integral or const
6755    //   enumeration type, its declaration in the class definition can
6756    //   specify a constant-initializer which shall be an integral
6757    //   constant expression (5.19). In that case, the member can appear
6758    //   in integral constant expressions. The member shall still be
6759    //   defined in a namespace scope if it is used in the program and the
6760    //   namespace scope definition shall not contain an initializer.
6761    //
6762    // We already performed a redefinition check above, but for static
6763    // data members we also need to check whether there was an in-class
6764    // declaration with an initializer.
6765    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6766      Diag(VDecl->getLocation(), diag::err_redefinition)
6767        << VDecl->getDeclName();
6768      Diag(PrevInit->getLocation(), diag::note_previous_definition);
6769      return;
6770    }
6771
6772    if (VDecl->hasLocalStorage())
6773      getCurFunction()->setHasBranchProtectedScope();
6774
6775    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6776      VDecl->setInvalidDecl();
6777      return;
6778    }
6779  }
6780
6781  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6782  // a kernel function cannot be initialized."
6783  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6784    Diag(VDecl->getLocation(), diag::err_local_cant_init);
6785    VDecl->setInvalidDecl();
6786    return;
6787  }
6788
6789  // Get the decls type and save a reference for later, since
6790  // CheckInitializerTypes may change it.
6791  QualType DclT = VDecl->getType(), SavT = DclT;
6792
6793  // Top-level message sends default to 'id' when we're in a debugger
6794  // and we are assigning it to a variable of 'id' type.
6795  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6796    if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6797      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6798      if (Result.isInvalid()) {
6799        VDecl->setInvalidDecl();
6800        return;
6801      }
6802      Init = Result.take();
6803    }
6804
6805  // Perform the initialization.
6806  if (!VDecl->isInvalidDecl()) {
6807    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6808    InitializationKind Kind
6809      = DirectInit ?
6810          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6811                                                           Init->getLocStart(),
6812                                                           Init->getLocEnd())
6813                        : InitializationKind::CreateDirectList(
6814                                                          VDecl->getLocation())
6815                   : InitializationKind::CreateCopy(VDecl->getLocation(),
6816                                                    Init->getLocStart());
6817
6818    Expr **Args = &Init;
6819    unsigned NumArgs = 1;
6820    if (CXXDirectInit) {
6821      Args = CXXDirectInit->getExprs();
6822      NumArgs = CXXDirectInit->getNumExprs();
6823    }
6824    InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6825    ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6826                                        MultiExprArg(Args, NumArgs), &DclT);
6827    if (Result.isInvalid()) {
6828      VDecl->setInvalidDecl();
6829      return;
6830    }
6831
6832    Init = Result.takeAs<Expr>();
6833  }
6834
6835  // Check for self-references within variable initializers.
6836  // Variables declared within a function/method body (except for references)
6837  // are handled by a dataflow analysis.
6838  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
6839      VDecl->getType()->isReferenceType()) {
6840    CheckSelfReference(*this, RealDecl, Init, DirectInit);
6841  }
6842
6843  // If the type changed, it means we had an incomplete type that was
6844  // completed by the initializer. For example:
6845  //   int ary[] = { 1, 3, 5 };
6846  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6847  if (!VDecl->isInvalidDecl() && (DclT != SavT))
6848    VDecl->setType(DclT);
6849
6850  // Check any implicit conversions within the expression.
6851  CheckImplicitConversions(Init, VDecl->getLocation());
6852
6853  if (!VDecl->isInvalidDecl()) {
6854    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6855
6856    if (VDecl->hasAttr<BlocksAttr>())
6857      checkRetainCycles(VDecl, Init);
6858
6859    // It is safe to assign a weak reference into a strong variable.
6860    // Although this code can still have problems:
6861    //   id x = self.weakProp;
6862    //   id y = self.weakProp;
6863    // we do not warn to warn spuriously when 'x' and 'y' are on separate
6864    // paths through the function. This should be revisited if
6865    // -Wrepeated-use-of-weak is made flow-sensitive.
6866    if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
6867      DiagnosticsEngine::Level Level =
6868        Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
6869                                 Init->getLocStart());
6870      if (Level != DiagnosticsEngine::Ignored)
6871        getCurFunction()->markSafeWeakUse(Init);
6872    }
6873  }
6874
6875  Init = MaybeCreateExprWithCleanups(Init);
6876  // Attach the initializer to the decl.
6877  VDecl->setInit(Init);
6878
6879  if (VDecl->isLocalVarDecl()) {
6880    // C99 6.7.8p4: All the expressions in an initializer for an object that has
6881    // static storage duration shall be constant expressions or string literals.
6882    // C++ does not have this restriction.
6883    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6884        VDecl->getStorageClass() == SC_Static)
6885      CheckForConstantInitializer(Init, DclT);
6886  } else if (VDecl->isStaticDataMember() &&
6887             VDecl->getLexicalDeclContext()->isRecord()) {
6888    // This is an in-class initialization for a static data member, e.g.,
6889    //
6890    // struct S {
6891    //   static const int value = 17;
6892    // };
6893
6894    // C++ [class.mem]p4:
6895    //   A member-declarator can contain a constant-initializer only
6896    //   if it declares a static member (9.4) of const integral or
6897    //   const enumeration type, see 9.4.2.
6898    //
6899    // C++11 [class.static.data]p3:
6900    //   If a non-volatile const static data member is of integral or
6901    //   enumeration type, its declaration in the class definition can
6902    //   specify a brace-or-equal-initializer in which every initalizer-clause
6903    //   that is an assignment-expression is a constant expression. A static
6904    //   data member of literal type can be declared in the class definition
6905    //   with the constexpr specifier; if so, its declaration shall specify a
6906    //   brace-or-equal-initializer in which every initializer-clause that is
6907    //   an assignment-expression is a constant expression.
6908
6909    // Do nothing on dependent types.
6910    if (DclT->isDependentType()) {
6911
6912    // Allow any 'static constexpr' members, whether or not they are of literal
6913    // type. We separately check that every constexpr variable is of literal
6914    // type.
6915    } else if (VDecl->isConstexpr()) {
6916
6917    // Require constness.
6918    } else if (!DclT.isConstQualified()) {
6919      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6920        << Init->getSourceRange();
6921      VDecl->setInvalidDecl();
6922
6923    // We allow integer constant expressions in all cases.
6924    } else if (DclT->isIntegralOrEnumerationType()) {
6925      // Check whether the expression is a constant expression.
6926      SourceLocation Loc;
6927      if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
6928        // In C++11, a non-constexpr const static data member with an
6929        // in-class initializer cannot be volatile.
6930        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6931      else if (Init->isValueDependent())
6932        ; // Nothing to check.
6933      else if (Init->isIntegerConstantExpr(Context, &Loc))
6934        ; // Ok, it's an ICE!
6935      else if (Init->isEvaluatable(Context)) {
6936        // If we can constant fold the initializer through heroics, accept it,
6937        // but report this as a use of an extension for -pedantic.
6938        Diag(Loc, diag::ext_in_class_initializer_non_constant)
6939          << Init->getSourceRange();
6940      } else {
6941        // Otherwise, this is some crazy unknown case.  Report the issue at the
6942        // location provided by the isIntegerConstantExpr failed check.
6943        Diag(Loc, diag::err_in_class_initializer_non_constant)
6944          << Init->getSourceRange();
6945        VDecl->setInvalidDecl();
6946      }
6947
6948    // We allow foldable floating-point constants as an extension.
6949    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6950      Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6951        << DclT << Init->getSourceRange();
6952      if (getLangOpts().CPlusPlus11)
6953        Diag(VDecl->getLocation(),
6954             diag::note_in_class_initializer_float_type_constexpr)
6955          << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6956
6957      if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6958        Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6959          << Init->getSourceRange();
6960        VDecl->setInvalidDecl();
6961      }
6962
6963    // Suggest adding 'constexpr' in C++11 for literal types.
6964    } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) {
6965      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6966        << DclT << Init->getSourceRange()
6967        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6968      VDecl->setConstexpr(true);
6969
6970    } else {
6971      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6972        << DclT << Init->getSourceRange();
6973      VDecl->setInvalidDecl();
6974    }
6975  } else if (VDecl->isFileVarDecl()) {
6976    if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6977        (!getLangOpts().CPlusPlus ||
6978         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6979      Diag(VDecl->getLocation(), diag::warn_extern_init);
6980
6981    // C99 6.7.8p4. All file scoped initializers need to be constant.
6982    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6983      CheckForConstantInitializer(Init, DclT);
6984  }
6985
6986  // We will represent direct-initialization similarly to copy-initialization:
6987  //    int x(1);  -as-> int x = 1;
6988  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6989  //
6990  // Clients that want to distinguish between the two forms, can check for
6991  // direct initializer using VarDecl::getInitStyle().
6992  // A major benefit is that clients that don't particularly care about which
6993  // exactly form was it (like the CodeGen) can handle both cases without
6994  // special case code.
6995
6996  // C++ 8.5p11:
6997  // The form of initialization (using parentheses or '=') is generally
6998  // insignificant, but does matter when the entity being initialized has a
6999  // class type.
7000  if (CXXDirectInit) {
7001    assert(DirectInit && "Call-style initializer must be direct init.");
7002    VDecl->setInitStyle(VarDecl::CallInit);
7003  } else if (DirectInit) {
7004    // This must be list-initialization. No other way is direct-initialization.
7005    VDecl->setInitStyle(VarDecl::ListInit);
7006  }
7007
7008  CheckCompleteVariableDeclaration(VDecl);
7009}
7010
7011/// ActOnInitializerError - Given that there was an error parsing an
7012/// initializer for the given declaration, try to return to some form
7013/// of sanity.
7014void Sema::ActOnInitializerError(Decl *D) {
7015  // Our main concern here is re-establishing invariants like "a
7016  // variable's type is either dependent or complete".
7017  if (!D || D->isInvalidDecl()) return;
7018
7019  VarDecl *VD = dyn_cast<VarDecl>(D);
7020  if (!VD) return;
7021
7022  // Auto types are meaningless if we can't make sense of the initializer.
7023  if (ParsingInitForAutoVars.count(D)) {
7024    D->setInvalidDecl();
7025    return;
7026  }
7027
7028  QualType Ty = VD->getType();
7029  if (Ty->isDependentType()) return;
7030
7031  // Require a complete type.
7032  if (RequireCompleteType(VD->getLocation(),
7033                          Context.getBaseElementType(Ty),
7034                          diag::err_typecheck_decl_incomplete_type)) {
7035    VD->setInvalidDecl();
7036    return;
7037  }
7038
7039  // Require an abstract type.
7040  if (RequireNonAbstractType(VD->getLocation(), Ty,
7041                             diag::err_abstract_type_in_decl,
7042                             AbstractVariableType)) {
7043    VD->setInvalidDecl();
7044    return;
7045  }
7046
7047  // Don't bother complaining about constructors or destructors,
7048  // though.
7049}
7050
7051void Sema::ActOnUninitializedDecl(Decl *RealDecl,
7052                                  bool TypeMayContainAuto) {
7053  // If there is no declaration, there was an error parsing it. Just ignore it.
7054  if (RealDecl == 0)
7055    return;
7056
7057  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
7058    QualType Type = Var->getType();
7059
7060    // C++11 [dcl.spec.auto]p3
7061    if (TypeMayContainAuto && Type->getContainedAutoType()) {
7062      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
7063        << Var->getDeclName() << Type;
7064      Var->setInvalidDecl();
7065      return;
7066    }
7067
7068    // C++11 [class.static.data]p3: A static data member can be declared with
7069    // the constexpr specifier; if so, its declaration shall specify
7070    // a brace-or-equal-initializer.
7071    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
7072    // the definition of a variable [...] or the declaration of a static data
7073    // member.
7074    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
7075      if (Var->isStaticDataMember())
7076        Diag(Var->getLocation(),
7077             diag::err_constexpr_static_mem_var_requires_init)
7078          << Var->getDeclName();
7079      else
7080        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
7081      Var->setInvalidDecl();
7082      return;
7083    }
7084
7085    switch (Var->isThisDeclarationADefinition()) {
7086    case VarDecl::Definition:
7087      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
7088        break;
7089
7090      // We have an out-of-line definition of a static data member
7091      // that has an in-class initializer, so we type-check this like
7092      // a declaration.
7093      //
7094      // Fall through
7095
7096    case VarDecl::DeclarationOnly:
7097      // It's only a declaration.
7098
7099      // Block scope. C99 6.7p7: If an identifier for an object is
7100      // declared with no linkage (C99 6.2.2p6), the type for the
7101      // object shall be complete.
7102      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
7103          !Var->getLinkage() && !Var->isInvalidDecl() &&
7104          RequireCompleteType(Var->getLocation(), Type,
7105                              diag::err_typecheck_decl_incomplete_type))
7106        Var->setInvalidDecl();
7107
7108      // Make sure that the type is not abstract.
7109      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7110          RequireNonAbstractType(Var->getLocation(), Type,
7111                                 diag::err_abstract_type_in_decl,
7112                                 AbstractVariableType))
7113        Var->setInvalidDecl();
7114      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7115          Var->getStorageClass() == SC_PrivateExtern) {
7116        Diag(Var->getLocation(), diag::warn_private_extern);
7117        Diag(Var->getLocation(), diag::note_private_extern);
7118      }
7119
7120      return;
7121
7122    case VarDecl::TentativeDefinition:
7123      // File scope. C99 6.9.2p2: A declaration of an identifier for an
7124      // object that has file scope without an initializer, and without a
7125      // storage-class specifier or with the storage-class specifier "static",
7126      // constitutes a tentative definition. Note: A tentative definition with
7127      // external linkage is valid (C99 6.2.2p5).
7128      if (!Var->isInvalidDecl()) {
7129        if (const IncompleteArrayType *ArrayT
7130                                    = Context.getAsIncompleteArrayType(Type)) {
7131          if (RequireCompleteType(Var->getLocation(),
7132                                  ArrayT->getElementType(),
7133                                  diag::err_illegal_decl_array_incomplete_type))
7134            Var->setInvalidDecl();
7135        } else if (Var->getStorageClass() == SC_Static) {
7136          // C99 6.9.2p3: If the declaration of an identifier for an object is
7137          // a tentative definition and has internal linkage (C99 6.2.2p3), the
7138          // declared type shall not be an incomplete type.
7139          // NOTE: code such as the following
7140          //     static struct s;
7141          //     struct s { int a; };
7142          // is accepted by gcc. Hence here we issue a warning instead of
7143          // an error and we do not invalidate the static declaration.
7144          // NOTE: to avoid multiple warnings, only check the first declaration.
7145          if (Var->getPreviousDecl() == 0)
7146            RequireCompleteType(Var->getLocation(), Type,
7147                                diag::ext_typecheck_decl_incomplete_type);
7148        }
7149      }
7150
7151      // Record the tentative definition; we're done.
7152      if (!Var->isInvalidDecl())
7153        TentativeDefinitions.push_back(Var);
7154      return;
7155    }
7156
7157    // Provide a specific diagnostic for uninitialized variable
7158    // definitions with incomplete array type.
7159    if (Type->isIncompleteArrayType()) {
7160      Diag(Var->getLocation(),
7161           diag::err_typecheck_incomplete_array_needs_initializer);
7162      Var->setInvalidDecl();
7163      return;
7164    }
7165
7166    // Provide a specific diagnostic for uninitialized variable
7167    // definitions with reference type.
7168    if (Type->isReferenceType()) {
7169      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7170        << Var->getDeclName()
7171        << SourceRange(Var->getLocation(), Var->getLocation());
7172      Var->setInvalidDecl();
7173      return;
7174    }
7175
7176    // Do not attempt to type-check the default initializer for a
7177    // variable with dependent type.
7178    if (Type->isDependentType())
7179      return;
7180
7181    if (Var->isInvalidDecl())
7182      return;
7183
7184    if (RequireCompleteType(Var->getLocation(),
7185                            Context.getBaseElementType(Type),
7186                            diag::err_typecheck_decl_incomplete_type)) {
7187      Var->setInvalidDecl();
7188      return;
7189    }
7190
7191    // The variable can not have an abstract class type.
7192    if (RequireNonAbstractType(Var->getLocation(), Type,
7193                               diag::err_abstract_type_in_decl,
7194                               AbstractVariableType)) {
7195      Var->setInvalidDecl();
7196      return;
7197    }
7198
7199    // Check for jumps past the implicit initializer.  C++0x
7200    // clarifies that this applies to a "variable with automatic
7201    // storage duration", not a "local variable".
7202    // C++11 [stmt.dcl]p3
7203    //   A program that jumps from a point where a variable with automatic
7204    //   storage duration is not in scope to a point where it is in scope is
7205    //   ill-formed unless the variable has scalar type, class type with a
7206    //   trivial default constructor and a trivial destructor, a cv-qualified
7207    //   version of one of these types, or an array of one of the preceding
7208    //   types and is declared without an initializer.
7209    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
7210      if (const RecordType *Record
7211            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
7212        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
7213        // Mark the function for further checking even if the looser rules of
7214        // C++11 do not require such checks, so that we can diagnose
7215        // incompatibilities with C++98.
7216        if (!CXXRecord->isPOD())
7217          getCurFunction()->setHasBranchProtectedScope();
7218      }
7219    }
7220
7221    // C++03 [dcl.init]p9:
7222    //   If no initializer is specified for an object, and the
7223    //   object is of (possibly cv-qualified) non-POD class type (or
7224    //   array thereof), the object shall be default-initialized; if
7225    //   the object is of const-qualified type, the underlying class
7226    //   type shall have a user-declared default
7227    //   constructor. Otherwise, if no initializer is specified for
7228    //   a non- static object, the object and its subobjects, if
7229    //   any, have an indeterminate initial value); if the object
7230    //   or any of its subobjects are of const-qualified type, the
7231    //   program is ill-formed.
7232    // C++0x [dcl.init]p11:
7233    //   If no initializer is specified for an object, the object is
7234    //   default-initialized; [...].
7235    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7236    InitializationKind Kind
7237      = InitializationKind::CreateDefault(Var->getLocation());
7238
7239    InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
7240    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
7241    if (Init.isInvalid())
7242      Var->setInvalidDecl();
7243    else if (Init.get()) {
7244      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
7245      // This is important for template substitution.
7246      Var->setInitStyle(VarDecl::CallInit);
7247    }
7248
7249    CheckCompleteVariableDeclaration(Var);
7250  }
7251}
7252
7253void Sema::ActOnCXXForRangeDecl(Decl *D) {
7254  VarDecl *VD = dyn_cast<VarDecl>(D);
7255  if (!VD) {
7256    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7257    D->setInvalidDecl();
7258    return;
7259  }
7260
7261  VD->setCXXForRangeDecl(true);
7262
7263  // for-range-declaration cannot be given a storage class specifier.
7264  int Error = -1;
7265  switch (VD->getStorageClassAsWritten()) {
7266  case SC_None:
7267    break;
7268  case SC_Extern:
7269    Error = 0;
7270    break;
7271  case SC_Static:
7272    Error = 1;
7273    break;
7274  case SC_PrivateExtern:
7275    Error = 2;
7276    break;
7277  case SC_Auto:
7278    Error = 3;
7279    break;
7280  case SC_Register:
7281    Error = 4;
7282    break;
7283  case SC_OpenCLWorkGroupLocal:
7284    llvm_unreachable("Unexpected storage class");
7285  }
7286  if (VD->isConstexpr())
7287    Error = 5;
7288  if (Error != -1) {
7289    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7290      << VD->getDeclName() << Error;
7291    D->setInvalidDecl();
7292  }
7293}
7294
7295void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7296  if (var->isInvalidDecl()) return;
7297
7298  // In ARC, don't allow jumps past the implicit initialization of a
7299  // local retaining variable.
7300  if (getLangOpts().ObjCAutoRefCount &&
7301      var->hasLocalStorage()) {
7302    switch (var->getType().getObjCLifetime()) {
7303    case Qualifiers::OCL_None:
7304    case Qualifiers::OCL_ExplicitNone:
7305    case Qualifiers::OCL_Autoreleasing:
7306      break;
7307
7308    case Qualifiers::OCL_Weak:
7309    case Qualifiers::OCL_Strong:
7310      getCurFunction()->setHasBranchProtectedScope();
7311      break;
7312    }
7313  }
7314
7315  if (var->isThisDeclarationADefinition() &&
7316      var->getLinkage() == ExternalLinkage &&
7317      getDiagnostics().getDiagnosticLevel(
7318                       diag::warn_missing_variable_declarations,
7319                       var->getLocation())) {
7320    // Find a previous declaration that's not a definition.
7321    VarDecl *prev = var->getPreviousDecl();
7322    while (prev && prev->isThisDeclarationADefinition())
7323      prev = prev->getPreviousDecl();
7324
7325    if (!prev)
7326      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7327  }
7328
7329  // All the following checks are C++ only.
7330  if (!getLangOpts().CPlusPlus) return;
7331
7332  QualType type = var->getType();
7333  if (type->isDependentType()) return;
7334
7335  // __block variables might require us to capture a copy-initializer.
7336  if (var->hasAttr<BlocksAttr>()) {
7337    // It's currently invalid to ever have a __block variable with an
7338    // array type; should we diagnose that here?
7339
7340    // Regardless, we don't want to ignore array nesting when
7341    // constructing this copy.
7342    if (type->isStructureOrClassType()) {
7343      SourceLocation poi = var->getLocation();
7344      Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
7345      ExprResult result =
7346        PerformCopyInitialization(
7347                        InitializedEntity::InitializeBlock(poi, type, false),
7348                                  poi, Owned(varRef));
7349      if (!result.isInvalid()) {
7350        result = MaybeCreateExprWithCleanups(result);
7351        Expr *init = result.takeAs<Expr>();
7352        Context.setBlockVarCopyInits(var, init);
7353      }
7354    }
7355  }
7356
7357  Expr *Init = var->getInit();
7358  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7359  QualType baseType = Context.getBaseElementType(type);
7360
7361  if (!var->getDeclContext()->isDependentContext() &&
7362      Init && !Init->isValueDependent()) {
7363    if (IsGlobal && !var->isConstexpr() &&
7364        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7365                                            var->getLocation())
7366          != DiagnosticsEngine::Ignored &&
7367        !Init->isConstantInitializer(Context, baseType->isReferenceType()))
7368      Diag(var->getLocation(), diag::warn_global_constructor)
7369        << Init->getSourceRange();
7370
7371    if (var->isConstexpr()) {
7372      llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7373      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7374        SourceLocation DiagLoc = var->getLocation();
7375        // If the note doesn't add any useful information other than a source
7376        // location, fold it into the primary diagnostic.
7377        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7378              diag::note_invalid_subexpr_in_const_expr) {
7379          DiagLoc = Notes[0].first;
7380          Notes.clear();
7381        }
7382        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7383          << var << Init->getSourceRange();
7384        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7385          Diag(Notes[I].first, Notes[I].second);
7386      }
7387    } else if (var->isUsableInConstantExpressions(Context)) {
7388      // Check whether the initializer of a const variable of integral or
7389      // enumeration type is an ICE now, since we can't tell whether it was
7390      // initialized by a constant expression if we check later.
7391      var->checkInitIsICE();
7392    }
7393  }
7394
7395  // Require the destructor.
7396  if (const RecordType *recordType = baseType->getAs<RecordType>())
7397    FinalizeVarWithDestructor(var, recordType);
7398}
7399
7400/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7401/// any semantic actions necessary after any initializer has been attached.
7402void
7403Sema::FinalizeDeclaration(Decl *ThisDecl) {
7404  // Note that we are no longer parsing the initializer for this declaration.
7405  ParsingInitForAutoVars.erase(ThisDecl);
7406
7407  const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
7408  if (!VD)
7409    return;
7410
7411  if (VD->isFileVarDecl())
7412    MarkUnusedFileScopedDecl(VD);
7413
7414  // Now we have parsed the initializer and can update the table of magic
7415  // tag values.
7416  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
7417      !VD->getType()->isIntegralOrEnumerationType())
7418    return;
7419
7420  for (specific_attr_iterator<TypeTagForDatatypeAttr>
7421         I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
7422         E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
7423       I != E; ++I) {
7424    const Expr *MagicValueExpr = VD->getInit();
7425    if (!MagicValueExpr) {
7426      continue;
7427    }
7428    llvm::APSInt MagicValueInt;
7429    if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
7430      Diag(I->getRange().getBegin(),
7431           diag::err_type_tag_for_datatype_not_ice)
7432        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7433      continue;
7434    }
7435    if (MagicValueInt.getActiveBits() > 64) {
7436      Diag(I->getRange().getBegin(),
7437           diag::err_type_tag_for_datatype_too_large)
7438        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7439      continue;
7440    }
7441    uint64_t MagicValue = MagicValueInt.getZExtValue();
7442    RegisterTypeTagForDatatype(I->getArgumentKind(),
7443                               MagicValue,
7444                               I->getMatchingCType(),
7445                               I->getLayoutCompatible(),
7446                               I->getMustBeNull());
7447  }
7448}
7449
7450Sema::DeclGroupPtrTy
7451Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7452                              Decl **Group, unsigned NumDecls) {
7453  SmallVector<Decl*, 8> Decls;
7454
7455  if (DS.isTypeSpecOwned())
7456    Decls.push_back(DS.getRepAsDecl());
7457
7458  for (unsigned i = 0; i != NumDecls; ++i)
7459    if (Decl *D = Group[i])
7460      Decls.push_back(D);
7461
7462  if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
7463    if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
7464      getASTContext().addUnnamedTag(Tag);
7465
7466  return BuildDeclaratorGroup(Decls.data(), Decls.size(),
7467                              DS.getTypeSpecType() == DeclSpec::TST_auto);
7468}
7469
7470/// BuildDeclaratorGroup - convert a list of declarations into a declaration
7471/// group, performing any necessary semantic checking.
7472Sema::DeclGroupPtrTy
7473Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7474                           bool TypeMayContainAuto) {
7475  // C++0x [dcl.spec.auto]p7:
7476  //   If the type deduced for the template parameter U is not the same in each
7477  //   deduction, the program is ill-formed.
7478  // FIXME: When initializer-list support is added, a distinction is needed
7479  // between the deduced type U and the deduced type which 'auto' stands for.
7480  //   auto a = 0, b = { 1, 2, 3 };
7481  // is legal because the deduced type U is 'int' in both cases.
7482  if (TypeMayContainAuto && NumDecls > 1) {
7483    QualType Deduced;
7484    CanQualType DeducedCanon;
7485    VarDecl *DeducedDecl = 0;
7486    for (unsigned i = 0; i != NumDecls; ++i) {
7487      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7488        AutoType *AT = D->getType()->getContainedAutoType();
7489        // Don't reissue diagnostics when instantiating a template.
7490        if (AT && D->isInvalidDecl())
7491          break;
7492        if (AT && AT->isDeduced()) {
7493          QualType U = AT->getDeducedType();
7494          CanQualType UCanon = Context.getCanonicalType(U);
7495          if (Deduced.isNull()) {
7496            Deduced = U;
7497            DeducedCanon = UCanon;
7498            DeducedDecl = D;
7499          } else if (DeducedCanon != UCanon) {
7500            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7501                 diag::err_auto_different_deductions)
7502              << Deduced << DeducedDecl->getDeclName()
7503              << U << D->getDeclName()
7504              << DeducedDecl->getInit()->getSourceRange()
7505              << D->getInit()->getSourceRange();
7506            D->setInvalidDecl();
7507            break;
7508          }
7509        }
7510      }
7511    }
7512  }
7513
7514  ActOnDocumentableDecls(Group, NumDecls);
7515
7516  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
7517}
7518
7519void Sema::ActOnDocumentableDecl(Decl *D) {
7520  ActOnDocumentableDecls(&D, 1);
7521}
7522
7523void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7524  // Don't parse the comment if Doxygen diagnostics are ignored.
7525  if (NumDecls == 0 || !Group[0])
7526   return;
7527
7528  if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7529                               Group[0]->getLocation())
7530        == DiagnosticsEngine::Ignored)
7531    return;
7532
7533  if (NumDecls >= 2) {
7534    // This is a decl group.  Normally it will contain only declarations
7535    // procuded from declarator list.  But in case we have any definitions or
7536    // additional declaration references:
7537    //   'typedef struct S {} S;'
7538    //   'typedef struct S *S;'
7539    //   'struct S *pS;'
7540    // FinalizeDeclaratorGroup adds these as separate declarations.
7541    Decl *MaybeTagDecl = Group[0];
7542    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7543      Group++;
7544      NumDecls--;
7545    }
7546  }
7547
7548  // See if there are any new comments that are not attached to a decl.
7549  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7550  if (!Comments.empty() &&
7551      !Comments.back()->isAttached()) {
7552    // There is at least one comment that not attached to a decl.
7553    // Maybe it should be attached to one of these decls?
7554    //
7555    // Note that this way we pick up not only comments that precede the
7556    // declaration, but also comments that *follow* the declaration -- thanks to
7557    // the lookahead in the lexer: we've consumed the semicolon and looked
7558    // ahead through comments.
7559    for (unsigned i = 0; i != NumDecls; ++i)
7560      Context.getCommentForDecl(Group[i], &PP);
7561  }
7562}
7563
7564/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7565/// to introduce parameters into function prototype scope.
7566Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
7567  const DeclSpec &DS = D.getDeclSpec();
7568
7569  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
7570  // C++03 [dcl.stc]p2 also permits 'auto'.
7571  VarDecl::StorageClass StorageClass = SC_None;
7572  VarDecl::StorageClass StorageClassAsWritten = SC_None;
7573  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
7574    StorageClass = SC_Register;
7575    StorageClassAsWritten = SC_Register;
7576  } else if (getLangOpts().CPlusPlus &&
7577             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7578    StorageClass = SC_Auto;
7579    StorageClassAsWritten = SC_Auto;
7580  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
7581    Diag(DS.getStorageClassSpecLoc(),
7582         diag::err_invalid_storage_class_in_func_decl);
7583    D.getMutableDeclSpec().ClearStorageClassSpecs();
7584  }
7585
7586  if (D.getDeclSpec().isThreadSpecified())
7587    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
7588  if (D.getDeclSpec().isConstexprSpecified())
7589    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7590      << 0;
7591
7592  DiagnoseFunctionSpecifiers(D);
7593
7594  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7595  QualType parmDeclType = TInfo->getType();
7596
7597  if (getLangOpts().CPlusPlus) {
7598    // Check that there are no default arguments inside the type of this
7599    // parameter.
7600    CheckExtraCXXDefaultArguments(D);
7601
7602    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7603    if (D.getCXXScopeSpec().isSet()) {
7604      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7605        << D.getCXXScopeSpec().getRange();
7606      D.getCXXScopeSpec().clear();
7607    }
7608  }
7609
7610  // Ensure we have a valid name
7611  IdentifierInfo *II = 0;
7612  if (D.hasName()) {
7613    II = D.getIdentifier();
7614    if (!II) {
7615      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7616        << GetNameForDeclarator(D).getName().getAsString();
7617      D.setInvalidType(true);
7618    }
7619  }
7620
7621  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
7622  if (II) {
7623    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7624                   ForRedeclaration);
7625    LookupName(R, S);
7626    if (R.isSingleResult()) {
7627      NamedDecl *PrevDecl = R.getFoundDecl();
7628      if (PrevDecl->isTemplateParameter()) {
7629        // Maybe we will complain about the shadowed template parameter.
7630        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7631        // Just pretend that we didn't see the previous declaration.
7632        PrevDecl = 0;
7633      } else if (S->isDeclScope(PrevDecl)) {
7634        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
7635        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7636
7637        // Recover by removing the name
7638        II = 0;
7639        D.SetIdentifier(0, D.getIdentifierLoc());
7640        D.setInvalidType(true);
7641      }
7642    }
7643  }
7644
7645  // Temporarily put parameter variables in the translation unit, not
7646  // the enclosing context.  This prevents them from accidentally
7647  // looking like class members in C++.
7648  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
7649                                    D.getLocStart(),
7650                                    D.getIdentifierLoc(), II,
7651                                    parmDeclType, TInfo,
7652                                    StorageClass, StorageClassAsWritten);
7653
7654  if (D.isInvalidType())
7655    New->setInvalidDecl();
7656
7657  assert(S->isFunctionPrototypeScope());
7658  assert(S->getFunctionPrototypeDepth() >= 1);
7659  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7660                    S->getNextFunctionPrototypeIndex());
7661
7662  // Add the parameter declaration into this scope.
7663  S->AddDecl(New);
7664  if (II)
7665    IdResolver.AddDecl(New);
7666
7667  ProcessDeclAttributes(S, New, D);
7668
7669  if (D.getDeclSpec().isModulePrivateSpecified())
7670    Diag(New->getLocation(), diag::err_module_private_local)
7671      << 1 << New->getDeclName()
7672      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7673      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7674
7675  if (New->hasAttr<BlocksAttr>()) {
7676    Diag(New->getLocation(), diag::err_block_on_nonlocal);
7677  }
7678  return New;
7679}
7680
7681/// \brief Synthesizes a variable for a parameter arising from a
7682/// typedef.
7683ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7684                                              SourceLocation Loc,
7685                                              QualType T) {
7686  /* FIXME: setting StartLoc == Loc.
7687     Would it be worth to modify callers so as to provide proper source
7688     location for the unnamed parameters, embedding the parameter's type? */
7689  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7690                                T, Context.getTrivialTypeSourceInfo(T, Loc),
7691                                           SC_None, SC_None, 0);
7692  Param->setImplicit();
7693  return Param;
7694}
7695
7696void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7697                                    ParmVarDecl * const *ParamEnd) {
7698  // Don't diagnose unused-parameter errors in template instantiations; we
7699  // will already have done so in the template itself.
7700  if (!ActiveTemplateInstantiations.empty())
7701    return;
7702
7703  for (; Param != ParamEnd; ++Param) {
7704    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7705        !(*Param)->hasAttr<UnusedAttr>()) {
7706      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7707        << (*Param)->getDeclName();
7708    }
7709  }
7710}
7711
7712void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7713                                                  ParmVarDecl * const *ParamEnd,
7714                                                  QualType ReturnTy,
7715                                                  NamedDecl *D) {
7716  if (LangOpts.NumLargeByValueCopy == 0) // No check.
7717    return;
7718
7719  // Warn if the return value is pass-by-value and larger than the specified
7720  // threshold.
7721  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7722    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7723    if (Size > LangOpts.NumLargeByValueCopy)
7724      Diag(D->getLocation(), diag::warn_return_value_size)
7725          << D->getDeclName() << Size;
7726  }
7727
7728  // Warn if any parameter is pass-by-value and larger than the specified
7729  // threshold.
7730  for (; Param != ParamEnd; ++Param) {
7731    QualType T = (*Param)->getType();
7732    if (T->isDependentType() || !T.isPODType(Context))
7733      continue;
7734    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7735    if (Size > LangOpts.NumLargeByValueCopy)
7736      Diag((*Param)->getLocation(), diag::warn_parameter_size)
7737          << (*Param)->getDeclName() << Size;
7738  }
7739}
7740
7741ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7742                                  SourceLocation NameLoc, IdentifierInfo *Name,
7743                                  QualType T, TypeSourceInfo *TSInfo,
7744                                  VarDecl::StorageClass StorageClass,
7745                                  VarDecl::StorageClass StorageClassAsWritten) {
7746  // In ARC, infer a lifetime qualifier for appropriate parameter types.
7747  if (getLangOpts().ObjCAutoRefCount &&
7748      T.getObjCLifetime() == Qualifiers::OCL_None &&
7749      T->isObjCLifetimeType()) {
7750
7751    Qualifiers::ObjCLifetime lifetime;
7752
7753    // Special cases for arrays:
7754    //   - if it's const, use __unsafe_unretained
7755    //   - otherwise, it's an error
7756    if (T->isArrayType()) {
7757      if (!T.isConstQualified()) {
7758        DelayedDiagnostics.add(
7759            sema::DelayedDiagnostic::makeForbiddenType(
7760            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7761      }
7762      lifetime = Qualifiers::OCL_ExplicitNone;
7763    } else {
7764      lifetime = T->getObjCARCImplicitLifetime();
7765    }
7766    T = Context.getLifetimeQualifiedType(T, lifetime);
7767  }
7768
7769  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7770                                         Context.getAdjustedParameterType(T),
7771                                         TSInfo,
7772                                         StorageClass, StorageClassAsWritten,
7773                                         0);
7774
7775  // Parameters can not be abstract class types.
7776  // For record types, this is done by the AbstractClassUsageDiagnoser once
7777  // the class has been completely parsed.
7778  if (!CurContext->isRecord() &&
7779      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7780                             AbstractParamType))
7781    New->setInvalidDecl();
7782
7783  // Parameter declarators cannot be interface types. All ObjC objects are
7784  // passed by reference.
7785  if (T->isObjCObjectType()) {
7786    SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
7787    Diag(NameLoc,
7788         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7789      << FixItHint::CreateInsertion(TypeEndLoc, "*");
7790    T = Context.getObjCObjectPointerType(T);
7791    New->setType(T);
7792  }
7793
7794  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7795  // duration shall not be qualified by an address-space qualifier."
7796  // Since all parameters have automatic store duration, they can not have
7797  // an address space.
7798  if (T.getAddressSpace() != 0) {
7799    Diag(NameLoc, diag::err_arg_with_address_space);
7800    New->setInvalidDecl();
7801  }
7802
7803  return New;
7804}
7805
7806void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7807                                           SourceLocation LocAfterDecls) {
7808  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7809
7810  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7811  // for a K&R function.
7812  if (!FTI.hasPrototype) {
7813    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7814      --i;
7815      if (FTI.ArgInfo[i].Param == 0) {
7816        SmallString<256> Code;
7817        llvm::raw_svector_ostream(Code) << "  int "
7818                                        << FTI.ArgInfo[i].Ident->getName()
7819                                        << ";\n";
7820        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7821          << FTI.ArgInfo[i].Ident
7822          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7823
7824        // Implicitly declare the argument as type 'int' for lack of a better
7825        // type.
7826        AttributeFactory attrs;
7827        DeclSpec DS(attrs);
7828        const char* PrevSpec; // unused
7829        unsigned DiagID; // unused
7830        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7831                           PrevSpec, DiagID);
7832        // Use the identifier location for the type source range.
7833        DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
7834        DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
7835        Declarator ParamD(DS, Declarator::KNRTypeListContext);
7836        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7837        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7838      }
7839    }
7840  }
7841}
7842
7843Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
7844  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7845  assert(D.isFunctionDeclarator() && "Not a function declarator!");
7846  Scope *ParentScope = FnBodyScope->getParent();
7847
7848  D.setFunctionDefinitionKind(FDK_Definition);
7849  Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
7850  return ActOnStartOfFunctionDef(FnBodyScope, DP);
7851}
7852
7853static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
7854                             const FunctionDecl*& PossibleZeroParamPrototype) {
7855  // Don't warn about invalid declarations.
7856  if (FD->isInvalidDecl())
7857    return false;
7858
7859  // Or declarations that aren't global.
7860  if (!FD->isGlobal())
7861    return false;
7862
7863  // Don't warn about C++ member functions.
7864  if (isa<CXXMethodDecl>(FD))
7865    return false;
7866
7867  // Don't warn about 'main'.
7868  if (FD->isMain())
7869    return false;
7870
7871  // Don't warn about inline functions.
7872  if (FD->isInlined())
7873    return false;
7874
7875  // Don't warn about function templates.
7876  if (FD->getDescribedFunctionTemplate())
7877    return false;
7878
7879  // Don't warn about function template specializations.
7880  if (FD->isFunctionTemplateSpecialization())
7881    return false;
7882
7883  // Don't warn for OpenCL kernels.
7884  if (FD->hasAttr<OpenCLKernelAttr>())
7885    return false;
7886
7887  bool MissingPrototype = true;
7888  for (const FunctionDecl *Prev = FD->getPreviousDecl();
7889       Prev; Prev = Prev->getPreviousDecl()) {
7890    // Ignore any declarations that occur in function or method
7891    // scope, because they aren't visible from the header.
7892    if (Prev->getDeclContext()->isFunctionOrMethod())
7893      continue;
7894
7895    MissingPrototype = !Prev->getType()->isFunctionProtoType();
7896    if (FD->getNumParams() == 0)
7897      PossibleZeroParamPrototype = Prev;
7898    break;
7899  }
7900
7901  return MissingPrototype;
7902}
7903
7904void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7905  // Don't complain if we're in GNU89 mode and the previous definition
7906  // was an extern inline function.
7907  const FunctionDecl *Definition;
7908  if (FD->isDefined(Definition) &&
7909      !canRedefineFunction(Definition, getLangOpts())) {
7910    if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7911        Definition->getStorageClass() == SC_Extern)
7912      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7913        << FD->getDeclName() << getLangOpts().CPlusPlus;
7914    else
7915      Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7916    Diag(Definition->getLocation(), diag::note_previous_definition);
7917    FD->setInvalidDecl();
7918  }
7919}
7920
7921Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7922  // Clear the last template instantiation error context.
7923  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7924
7925  if (!D)
7926    return D;
7927  FunctionDecl *FD = 0;
7928
7929  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7930    FD = FunTmpl->getTemplatedDecl();
7931  else
7932    FD = cast<FunctionDecl>(D);
7933
7934  // Enter a new function scope
7935  PushFunctionScope();
7936
7937  // See if this is a redefinition.
7938  if (!FD->isLateTemplateParsed())
7939    CheckForFunctionRedefinition(FD);
7940
7941  // Builtin functions cannot be defined.
7942  if (unsigned BuiltinID = FD->getBuiltinID()) {
7943    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7944      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7945      FD->setInvalidDecl();
7946    }
7947  }
7948
7949  // The return type of a function definition must be complete
7950  // (C99 6.9.1p3, C++ [dcl.fct]p6).
7951  QualType ResultType = FD->getResultType();
7952  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7953      !FD->isInvalidDecl() &&
7954      RequireCompleteType(FD->getLocation(), ResultType,
7955                          diag::err_func_def_incomplete_result))
7956    FD->setInvalidDecl();
7957
7958  // GNU warning -Wmissing-prototypes:
7959  //   Warn if a global function is defined without a previous
7960  //   prototype declaration. This warning is issued even if the
7961  //   definition itself provides a prototype. The aim is to detect
7962  //   global functions that fail to be declared in header files.
7963  const FunctionDecl *PossibleZeroParamPrototype = 0;
7964  if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
7965    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7966
7967    if (PossibleZeroParamPrototype) {
7968      // We found a declaration that is not a prototype,
7969      // but that could be a zero-parameter prototype
7970      TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo();
7971      TypeLoc TL = TI->getTypeLoc();
7972      if (FunctionNoProtoTypeLoc* FTL = dyn_cast<FunctionNoProtoTypeLoc>(&TL))
7973        Diag(PossibleZeroParamPrototype->getLocation(),
7974             diag::note_declaration_not_a_prototype)
7975          << PossibleZeroParamPrototype
7976          << FixItHint::CreateInsertion(FTL->getRParenLoc(), "void");
7977    }
7978  }
7979
7980  if (FnBodyScope)
7981    PushDeclContext(FnBodyScope, FD);
7982
7983  // Check the validity of our function parameters
7984  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7985                           /*CheckParameterNames=*/true);
7986
7987  // Introduce our parameters into the function scope
7988  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7989    ParmVarDecl *Param = FD->getParamDecl(p);
7990    Param->setOwningFunction(FD);
7991
7992    // If this has an identifier, add it to the scope stack.
7993    if (Param->getIdentifier() && FnBodyScope) {
7994      CheckShadow(FnBodyScope, Param);
7995
7996      PushOnScopeChains(Param, FnBodyScope);
7997    }
7998  }
7999
8000  // If we had any tags defined in the function prototype,
8001  // introduce them into the function scope.
8002  if (FnBodyScope) {
8003    for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
8004           E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
8005      NamedDecl *D = *I;
8006
8007      // Some of these decls (like enums) may have been pinned to the translation unit
8008      // for lack of a real context earlier. If so, remove from the translation unit
8009      // and reattach to the current context.
8010      if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
8011        // Is the decl actually in the context?
8012        for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
8013               DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
8014          if (*DI == D) {
8015            Context.getTranslationUnitDecl()->removeDecl(D);
8016            break;
8017          }
8018        }
8019        // Either way, reassign the lexical decl context to our FunctionDecl.
8020        D->setLexicalDeclContext(CurContext);
8021      }
8022
8023      // If the decl has a non-null name, make accessible in the current scope.
8024      if (!D->getName().empty())
8025        PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
8026
8027      // Similarly, dive into enums and fish their constants out, making them
8028      // accessible in this scope.
8029      if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
8030        for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
8031               EE = ED->enumerator_end(); EI != EE; ++EI)
8032          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
8033      }
8034    }
8035  }
8036
8037  // Ensure that the function's exception specification is instantiated.
8038  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
8039    ResolveExceptionSpec(D->getLocation(), FPT);
8040
8041  // Checking attributes of current function definition
8042  // dllimport attribute.
8043  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
8044  if (DA && (!FD->getAttr<DLLExportAttr>())) {
8045    // dllimport attribute cannot be directly applied to definition.
8046    // Microsoft accepts dllimport for functions defined within class scope.
8047    if (!DA->isInherited() &&
8048        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
8049      Diag(FD->getLocation(),
8050           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
8051        << "dllimport";
8052      FD->setInvalidDecl();
8053      return D;
8054    }
8055
8056    // Visual C++ appears to not think this is an issue, so only issue
8057    // a warning when Microsoft extensions are disabled.
8058    if (!LangOpts.MicrosoftExt) {
8059      // If a symbol previously declared dllimport is later defined, the
8060      // attribute is ignored in subsequent references, and a warning is
8061      // emitted.
8062      Diag(FD->getLocation(),
8063           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
8064        << FD->getName() << "dllimport";
8065    }
8066  }
8067  // We want to attach documentation to original Decl (which might be
8068  // a function template).
8069  ActOnDocumentableDecl(D);
8070  return D;
8071}
8072
8073/// \brief Given the set of return statements within a function body,
8074/// compute the variables that are subject to the named return value
8075/// optimization.
8076///
8077/// Each of the variables that is subject to the named return value
8078/// optimization will be marked as NRVO variables in the AST, and any
8079/// return statement that has a marked NRVO variable as its NRVO candidate can
8080/// use the named return value optimization.
8081///
8082/// This function applies a very simplistic algorithm for NRVO: if every return
8083/// statement in the function has the same NRVO candidate, that candidate is
8084/// the NRVO variable.
8085///
8086/// FIXME: Employ a smarter algorithm that accounts for multiple return
8087/// statements and the lifetimes of the NRVO candidates. We should be able to
8088/// find a maximal set of NRVO variables.
8089void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
8090  ReturnStmt **Returns = Scope->Returns.data();
8091
8092  const VarDecl *NRVOCandidate = 0;
8093  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
8094    if (!Returns[I]->getNRVOCandidate())
8095      return;
8096
8097    if (!NRVOCandidate)
8098      NRVOCandidate = Returns[I]->getNRVOCandidate();
8099    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
8100      return;
8101  }
8102
8103  if (NRVOCandidate)
8104    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
8105}
8106
8107bool Sema::canSkipFunctionBody(Decl *D) {
8108  if (!Consumer.shouldSkipFunctionBody(D))
8109    return false;
8110
8111  if (isa<ObjCMethodDecl>(D))
8112    return true;
8113
8114  FunctionDecl *FD = 0;
8115  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
8116    FD = FTD->getTemplatedDecl();
8117  else
8118    FD = cast<FunctionDecl>(D);
8119
8120  // We cannot skip the body of a function (or function template) which is
8121  // constexpr, since we may need to evaluate its body in order to parse the
8122  // rest of the file.
8123  return !FD->isConstexpr();
8124}
8125
8126Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
8127  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
8128    FD->setHasSkippedBody();
8129  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
8130    MD->setHasSkippedBody();
8131  return ActOnFinishFunctionBody(Decl, 0);
8132}
8133
8134Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
8135  return ActOnFinishFunctionBody(D, BodyArg, false);
8136}
8137
8138Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
8139                                    bool IsInstantiation) {
8140  FunctionDecl *FD = 0;
8141  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
8142  if (FunTmpl)
8143    FD = FunTmpl->getTemplatedDecl();
8144  else
8145    FD = dyn_cast_or_null<FunctionDecl>(dcl);
8146
8147  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
8148  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
8149
8150  if (FD) {
8151    FD->setBody(Body);
8152
8153    // If the function implicitly returns zero (like 'main') or is naked,
8154    // don't complain about missing return statements.
8155    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
8156      WP.disableCheckFallThrough();
8157
8158    // MSVC permits the use of pure specifier (=0) on function definition,
8159    // defined at class scope, warn about this non standard construct.
8160    if (getLangOpts().MicrosoftExt && FD->isPure())
8161      Diag(FD->getLocation(), diag::warn_pure_function_definition);
8162
8163    if (!FD->isInvalidDecl()) {
8164      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
8165      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8166                                             FD->getResultType(), FD);
8167
8168      // If this is a constructor, we need a vtable.
8169      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8170        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
8171
8172      // Try to apply the named return value optimization. We have to check
8173      // if we can do this here because lambdas keep return statements around
8174      // to deduce an implicit return type.
8175      if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8176          !FD->isDependentContext())
8177        computeNRVO(Body, getCurFunction());
8178    }
8179
8180    assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8181           "Function parsing confused");
8182  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
8183    assert(MD == getCurMethodDecl() && "Method parsing confused");
8184    MD->setBody(Body);
8185    if (!MD->isInvalidDecl()) {
8186      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
8187      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8188                                             MD->getResultType(), MD);
8189
8190      if (Body)
8191        computeNRVO(Body, getCurFunction());
8192    }
8193    if (getCurFunction()->ObjCShouldCallSuper) {
8194      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8195        << MD->getSelector().getAsString();
8196      getCurFunction()->ObjCShouldCallSuper = false;
8197    }
8198  } else {
8199    return 0;
8200  }
8201
8202  assert(!getCurFunction()->ObjCShouldCallSuper &&
8203         "This should only be set for ObjC methods, which should have been "
8204         "handled in the block above.");
8205
8206  // Verify and clean out per-function state.
8207  if (Body) {
8208    // C++ constructors that have function-try-blocks can't have return
8209    // statements in the handlers of that block. (C++ [except.handle]p14)
8210    // Verify this.
8211    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8212      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8213
8214    // Verify that gotos and switch cases don't jump into scopes illegally.
8215    if (getCurFunction()->NeedsScopeChecking() &&
8216        !dcl->isInvalidDecl() &&
8217        !hasAnyUnrecoverableErrorsInThisFunction() &&
8218        !PP.isCodeCompletionEnabled())
8219      DiagnoseInvalidJumps(Body);
8220
8221    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8222      if (!Destructor->getParent()->isDependentType())
8223        CheckDestructor(Destructor);
8224
8225      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8226                                             Destructor->getParent());
8227    }
8228
8229    // If any errors have occurred, clear out any temporaries that may have
8230    // been leftover. This ensures that these temporaries won't be picked up for
8231    // deletion in some later function.
8232    if (PP.getDiagnostics().hasErrorOccurred() ||
8233        PP.getDiagnostics().getSuppressAllDiagnostics()) {
8234      DiscardCleanupsInEvaluationContext();
8235    }
8236    if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
8237        !isa<FunctionTemplateDecl>(dcl)) {
8238      // Since the body is valid, issue any analysis-based warnings that are
8239      // enabled.
8240      ActivePolicy = &WP;
8241    }
8242
8243    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8244        (!CheckConstexprFunctionDecl(FD) ||
8245         !CheckConstexprFunctionBody(FD, Body)))
8246      FD->setInvalidDecl();
8247
8248    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
8249    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
8250    assert(MaybeODRUseExprs.empty() &&
8251           "Leftover expressions for odr-use checking");
8252  }
8253
8254  if (!IsInstantiation)
8255    PopDeclContext();
8256
8257  PopFunctionScopeInfo(ActivePolicy, dcl);
8258
8259  // If any errors have occurred, clear out any temporaries that may have
8260  // been leftover. This ensures that these temporaries won't be picked up for
8261  // deletion in some later function.
8262  if (getDiagnostics().hasErrorOccurred()) {
8263    DiscardCleanupsInEvaluationContext();
8264  }
8265
8266  return dcl;
8267}
8268
8269
8270/// When we finish delayed parsing of an attribute, we must attach it to the
8271/// relevant Decl.
8272void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8273                                       ParsedAttributes &Attrs) {
8274  // Always attach attributes to the underlying decl.
8275  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8276    D = TD->getTemplatedDecl();
8277  ProcessDeclAttributeList(S, D, Attrs.getList());
8278
8279  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8280    if (Method->isStatic())
8281      checkThisInStaticMemberFunctionAttributes(Method);
8282}
8283
8284
8285/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8286/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
8287NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
8288                                          IdentifierInfo &II, Scope *S) {
8289  // Before we produce a declaration for an implicitly defined
8290  // function, see whether there was a locally-scoped declaration of
8291  // this name as a function or variable. If so, use that
8292  // (non-visible) declaration, and complain about it.
8293  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
8294    = findLocallyScopedExternCDecl(&II);
8295  if (Pos != LocallyScopedExternCDecls.end()) {
8296    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8297    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8298    return Pos->second;
8299  }
8300
8301  // Extension in C99.  Legal in C90, but warn about it.
8302  unsigned diag_id;
8303  if (II.getName().startswith("__builtin_"))
8304    diag_id = diag::warn_builtin_unknown;
8305  else if (getLangOpts().C99)
8306    diag_id = diag::ext_implicit_function_decl;
8307  else
8308    diag_id = diag::warn_implicit_function_decl;
8309  Diag(Loc, diag_id) << &II;
8310
8311  // Because typo correction is expensive, only do it if the implicit
8312  // function declaration is going to be treated as an error.
8313  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8314    TypoCorrection Corrected;
8315    DeclFilterCCC<FunctionDecl> Validator;
8316    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
8317                                      LookupOrdinaryName, S, 0, Validator))) {
8318      std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8319      std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
8320      FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
8321
8322      Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8323          << FixItHint::CreateReplacement(Loc, CorrectedStr);
8324
8325      if (Func->getLocation().isValid()
8326          && !II.getName().startswith("__builtin_"))
8327        Diag(Func->getLocation(), diag::note_previous_decl)
8328            << CorrectedQuotedStr;
8329    }
8330  }
8331
8332  // Set a Declarator for the implicit definition: int foo();
8333  const char *Dummy;
8334  AttributeFactory attrFactory;
8335  DeclSpec DS(attrFactory);
8336  unsigned DiagID;
8337  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
8338  (void)Error; // Silence warning.
8339  assert(!Error && "Error setting up implicit decl!");
8340  SourceLocation NoLoc;
8341  Declarator D(DS, Declarator::BlockContext);
8342  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8343                                             /*IsAmbiguous=*/false,
8344                                             /*RParenLoc=*/NoLoc,
8345                                             /*ArgInfo=*/0,
8346                                             /*NumArgs=*/0,
8347                                             /*EllipsisLoc=*/NoLoc,
8348                                             /*RParenLoc=*/NoLoc,
8349                                             /*TypeQuals=*/0,
8350                                             /*RefQualifierIsLvalueRef=*/true,
8351                                             /*RefQualifierLoc=*/NoLoc,
8352                                             /*ConstQualifierLoc=*/NoLoc,
8353                                             /*VolatileQualifierLoc=*/NoLoc,
8354                                             /*MutableLoc=*/NoLoc,
8355                                             EST_None,
8356                                             /*ESpecLoc=*/NoLoc,
8357                                             /*Exceptions=*/0,
8358                                             /*ExceptionRanges=*/0,
8359                                             /*NumExceptions=*/0,
8360                                             /*NoexceptExpr=*/0,
8361                                             Loc, Loc, D),
8362                DS.getAttributes(),
8363                SourceLocation());
8364  D.SetIdentifier(&II, Loc);
8365
8366  // Insert this function into translation-unit scope.
8367
8368  DeclContext *PrevDC = CurContext;
8369  CurContext = Context.getTranslationUnitDecl();
8370
8371  FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
8372  FD->setImplicit();
8373
8374  CurContext = PrevDC;
8375
8376  AddKnownFunctionAttributes(FD);
8377
8378  return FD;
8379}
8380
8381/// \brief Adds any function attributes that we know a priori based on
8382/// the declaration of this function.
8383///
8384/// These attributes can apply both to implicitly-declared builtins
8385/// (like __builtin___printf_chk) or to library-declared functions
8386/// like NSLog or printf.
8387///
8388/// We need to check for duplicate attributes both here and where user-written
8389/// attributes are applied to declarations.
8390void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8391  if (FD->isInvalidDecl())
8392    return;
8393
8394  // If this is a built-in function, map its builtin attributes to
8395  // actual attributes.
8396  if (unsigned BuiltinID = FD->getBuiltinID()) {
8397    // Handle printf-formatting attributes.
8398    unsigned FormatIdx;
8399    bool HasVAListArg;
8400    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
8401      if (!FD->getAttr<FormatAttr>()) {
8402        const char *fmt = "printf";
8403        unsigned int NumParams = FD->getNumParams();
8404        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8405            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
8406          fmt = "NSString";
8407        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8408                                               fmt, FormatIdx+1,
8409                                               HasVAListArg ? 0 : FormatIdx+2));
8410      }
8411    }
8412    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
8413                                             HasVAListArg)) {
8414     if (!FD->getAttr<FormatAttr>())
8415       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8416                                              "scanf", FormatIdx+1,
8417                                              HasVAListArg ? 0 : FormatIdx+2));
8418    }
8419
8420    // Mark const if we don't care about errno and that is the only
8421    // thing preventing the function from being const. This allows
8422    // IRgen to use LLVM intrinsics for such functions.
8423    if (!getLangOpts().MathErrno &&
8424        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
8425      if (!FD->getAttr<ConstAttr>())
8426        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8427    }
8428
8429    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
8430        !FD->getAttr<ReturnsTwiceAttr>())
8431      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
8432    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
8433      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
8434    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
8435      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8436  }
8437
8438  IdentifierInfo *Name = FD->getIdentifier();
8439  if (!Name)
8440    return;
8441  if ((!getLangOpts().CPlusPlus &&
8442       FD->getDeclContext()->isTranslationUnit()) ||
8443      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
8444       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
8445       LinkageSpecDecl::lang_c)) {
8446    // Okay: this could be a libc/libm/Objective-C function we know
8447    // about.
8448  } else
8449    return;
8450
8451  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
8452    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
8453    // target-specific builtins, perhaps?
8454    if (!FD->getAttr<FormatAttr>())
8455      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8456                                             "printf", 2,
8457                                             Name->isStr("vasprintf") ? 0 : 3));
8458  }
8459
8460  if (Name->isStr("__CFStringMakeConstantString")) {
8461    // We already have a __builtin___CFStringMakeConstantString,
8462    // but builds that use -fno-constant-cfstrings don't go through that.
8463    if (!FD->getAttr<FormatArgAttr>())
8464      FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
8465  }
8466}
8467
8468TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
8469                                    TypeSourceInfo *TInfo) {
8470  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
8471  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
8472
8473  if (!TInfo) {
8474    assert(D.isInvalidType() && "no declarator info for valid type");
8475    TInfo = Context.getTrivialTypeSourceInfo(T);
8476  }
8477
8478  // Scope manipulation handled by caller.
8479  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
8480                                           D.getLocStart(),
8481                                           D.getIdentifierLoc(),
8482                                           D.getIdentifier(),
8483                                           TInfo);
8484
8485  // Bail out immediately if we have an invalid declaration.
8486  if (D.isInvalidType()) {
8487    NewTD->setInvalidDecl();
8488    return NewTD;
8489  }
8490
8491  if (D.getDeclSpec().isModulePrivateSpecified()) {
8492    if (CurContext->isFunctionOrMethod())
8493      Diag(NewTD->getLocation(), diag::err_module_private_local)
8494        << 2 << NewTD->getDeclName()
8495        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8496        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8497    else
8498      NewTD->setModulePrivate();
8499  }
8500
8501  // C++ [dcl.typedef]p8:
8502  //   If the typedef declaration defines an unnamed class (or
8503  //   enum), the first typedef-name declared by the declaration
8504  //   to be that class type (or enum type) is used to denote the
8505  //   class type (or enum type) for linkage purposes only.
8506  // We need to check whether the type was declared in the declaration.
8507  switch (D.getDeclSpec().getTypeSpecType()) {
8508  case TST_enum:
8509  case TST_struct:
8510  case TST_interface:
8511  case TST_union:
8512  case TST_class: {
8513    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8514
8515    // Do nothing if the tag is not anonymous or already has an
8516    // associated typedef (from an earlier typedef in this decl group).
8517    if (tagFromDeclSpec->getIdentifier()) break;
8518    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
8519
8520    // A well-formed anonymous tag must always be a TUK_Definition.
8521    assert(tagFromDeclSpec->isThisDeclarationADefinition());
8522
8523    // The type must match the tag exactly;  no qualifiers allowed.
8524    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8525      break;
8526
8527    // Otherwise, set this is the anon-decl typedef for the tag.
8528    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
8529    break;
8530  }
8531
8532  default:
8533    break;
8534  }
8535
8536  return NewTD;
8537}
8538
8539
8540/// \brief Check that this is a valid underlying type for an enum declaration.
8541bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8542  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8543  QualType T = TI->getType();
8544
8545  if (T->isDependentType())
8546    return false;
8547
8548  if (const BuiltinType *BT = T->getAs<BuiltinType>())
8549    if (BT->isInteger())
8550      return false;
8551
8552  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8553  return true;
8554}
8555
8556/// Check whether this is a valid redeclaration of a previous enumeration.
8557/// \return true if the redeclaration was invalid.
8558bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8559                                  QualType EnumUnderlyingTy,
8560                                  const EnumDecl *Prev) {
8561  bool IsFixed = !EnumUnderlyingTy.isNull();
8562
8563  if (IsScoped != Prev->isScoped()) {
8564    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8565      << Prev->isScoped();
8566    Diag(Prev->getLocation(), diag::note_previous_use);
8567    return true;
8568  }
8569
8570  if (IsFixed && Prev->isFixed()) {
8571    if (!EnumUnderlyingTy->isDependentType() &&
8572        !Prev->getIntegerType()->isDependentType() &&
8573        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
8574                                        Prev->getIntegerType())) {
8575      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8576        << EnumUnderlyingTy << Prev->getIntegerType();
8577      Diag(Prev->getLocation(), diag::note_previous_use);
8578      return true;
8579    }
8580  } else if (IsFixed != Prev->isFixed()) {
8581    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8582      << Prev->isFixed();
8583    Diag(Prev->getLocation(), diag::note_previous_use);
8584    return true;
8585  }
8586
8587  return false;
8588}
8589
8590/// \brief Get diagnostic %select index for tag kind for
8591/// redeclaration diagnostic message.
8592/// WARNING: Indexes apply to particular diagnostics only!
8593///
8594/// \returns diagnostic %select index.
8595static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
8596  switch (Tag) {
8597  case TTK_Struct: return 0;
8598  case TTK_Interface: return 1;
8599  case TTK_Class:  return 2;
8600  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
8601  }
8602}
8603
8604/// \brief Determine if tag kind is a class-key compatible with
8605/// class for redeclaration (class, struct, or __interface).
8606///
8607/// \returns true iff the tag kind is compatible.
8608static bool isClassCompatTagKind(TagTypeKind Tag)
8609{
8610  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
8611}
8612
8613/// \brief Determine whether a tag with a given kind is acceptable
8614/// as a redeclaration of the given tag declaration.
8615///
8616/// \returns true if the new tag kind is acceptable, false otherwise.
8617bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
8618                                        TagTypeKind NewTag, bool isDefinition,
8619                                        SourceLocation NewTagLoc,
8620                                        const IdentifierInfo &Name) {
8621  // C++ [dcl.type.elab]p3:
8622  //   The class-key or enum keyword present in the
8623  //   elaborated-type-specifier shall agree in kind with the
8624  //   declaration to which the name in the elaborated-type-specifier
8625  //   refers. This rule also applies to the form of
8626  //   elaborated-type-specifier that declares a class-name or
8627  //   friend class since it can be construed as referring to the
8628  //   definition of the class. Thus, in any
8629  //   elaborated-type-specifier, the enum keyword shall be used to
8630  //   refer to an enumeration (7.2), the union class-key shall be
8631  //   used to refer to a union (clause 9), and either the class or
8632  //   struct class-key shall be used to refer to a class (clause 9)
8633  //   declared using the class or struct class-key.
8634  TagTypeKind OldTag = Previous->getTagKind();
8635  if (!isDefinition || !isClassCompatTagKind(NewTag))
8636    if (OldTag == NewTag)
8637      return true;
8638
8639  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
8640    // Warn about the struct/class tag mismatch.
8641    bool isTemplate = false;
8642    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8643      isTemplate = Record->getDescribedClassTemplate();
8644
8645    if (!ActiveTemplateInstantiations.empty()) {
8646      // In a template instantiation, do not offer fix-its for tag mismatches
8647      // since they usually mess up the template instead of fixing the problem.
8648      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8649        << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8650        << getRedeclDiagFromTagKind(OldTag);
8651      return true;
8652    }
8653
8654    if (isDefinition) {
8655      // On definitions, check previous tags and issue a fix-it for each
8656      // one that doesn't match the current tag.
8657      if (Previous->getDefinition()) {
8658        // Don't suggest fix-its for redefinitions.
8659        return true;
8660      }
8661
8662      bool previousMismatch = false;
8663      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8664           E(Previous->redecls_end()); I != E; ++I) {
8665        if (I->getTagKind() != NewTag) {
8666          if (!previousMismatch) {
8667            previousMismatch = true;
8668            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
8669              << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8670              << getRedeclDiagFromTagKind(I->getTagKind());
8671          }
8672          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
8673            << getRedeclDiagFromTagKind(NewTag)
8674            << FixItHint::CreateReplacement(I->getInnerLocStart(),
8675                 TypeWithKeyword::getTagTypeKindName(NewTag));
8676        }
8677      }
8678      return true;
8679    }
8680
8681    // Check for a previous definition.  If current tag and definition
8682    // are same type, do nothing.  If no definition, but disagree with
8683    // with previous tag type, give a warning, but no fix-it.
8684    const TagDecl *Redecl = Previous->getDefinition() ?
8685                            Previous->getDefinition() : Previous;
8686    if (Redecl->getTagKind() == NewTag) {
8687      return true;
8688    }
8689
8690    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8691      << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8692      << getRedeclDiagFromTagKind(OldTag);
8693    Diag(Redecl->getLocation(), diag::note_previous_use);
8694
8695    // If there is a previous defintion, suggest a fix-it.
8696    if (Previous->getDefinition()) {
8697        Diag(NewTagLoc, diag::note_struct_class_suggestion)
8698          << getRedeclDiagFromTagKind(Redecl->getTagKind())
8699          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
8700               TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
8701    }
8702
8703    return true;
8704  }
8705  return false;
8706}
8707
8708/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
8709/// former case, Name will be non-null.  In the later case, Name will be null.
8710/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
8711/// reference/declaration/definition of a tag.
8712Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8713                     SourceLocation KWLoc, CXXScopeSpec &SS,
8714                     IdentifierInfo *Name, SourceLocation NameLoc,
8715                     AttributeList *Attr, AccessSpecifier AS,
8716                     SourceLocation ModulePrivateLoc,
8717                     MultiTemplateParamsArg TemplateParameterLists,
8718                     bool &OwnedDecl, bool &IsDependent,
8719                     SourceLocation ScopedEnumKWLoc,
8720                     bool ScopedEnumUsesClassTag,
8721                     TypeResult UnderlyingType) {
8722  // If this is not a definition, it must have a name.
8723  IdentifierInfo *OrigName = Name;
8724  assert((Name != 0 || TUK == TUK_Definition) &&
8725         "Nameless record must be a definition!");
8726  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
8727
8728  OwnedDecl = false;
8729  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8730  bool ScopedEnum = ScopedEnumKWLoc.isValid();
8731
8732  // FIXME: Check explicit specializations more carefully.
8733  bool isExplicitSpecialization = false;
8734  bool Invalid = false;
8735
8736  // We only need to do this matching if we have template parameters
8737  // or a scope specifier, which also conveniently avoids this work
8738  // for non-C++ cases.
8739  if (TemplateParameterLists.size() > 0 ||
8740      (SS.isNotEmpty() && TUK != TUK_Reference)) {
8741    if (TemplateParameterList *TemplateParams
8742          = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
8743                                                TemplateParameterLists.data(),
8744                                                TemplateParameterLists.size(),
8745                                                    TUK == TUK_Friend,
8746                                                    isExplicitSpecialization,
8747                                                    Invalid)) {
8748      if (TemplateParams->size() > 0) {
8749        // This is a declaration or definition of a class template (which may
8750        // be a member of another template).
8751
8752        if (Invalid)
8753          return 0;
8754
8755        OwnedDecl = false;
8756        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
8757                                               SS, Name, NameLoc, Attr,
8758                                               TemplateParams, AS,
8759                                               ModulePrivateLoc,
8760                                               TemplateParameterLists.size()-1,
8761                                               TemplateParameterLists.data());
8762        return Result.get();
8763      } else {
8764        // The "template<>" header is extraneous.
8765        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8766          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8767        isExplicitSpecialization = true;
8768      }
8769    }
8770  }
8771
8772  // Figure out the underlying type if this a enum declaration. We need to do
8773  // this early, because it's needed to detect if this is an incompatible
8774  // redeclaration.
8775  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8776
8777  if (Kind == TTK_Enum) {
8778    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8779      // No underlying type explicitly specified, or we failed to parse the
8780      // type, default to int.
8781      EnumUnderlying = Context.IntTy.getTypePtr();
8782    else if (UnderlyingType.get()) {
8783      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8784      // integral type; any cv-qualification is ignored.
8785      TypeSourceInfo *TI = 0;
8786      GetTypeFromParser(UnderlyingType.get(), &TI);
8787      EnumUnderlying = TI;
8788
8789      if (CheckEnumUnderlyingType(TI))
8790        // Recover by falling back to int.
8791        EnumUnderlying = Context.IntTy.getTypePtr();
8792
8793      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8794                                          UPPC_FixedUnderlyingType))
8795        EnumUnderlying = Context.IntTy.getTypePtr();
8796
8797    } else if (getLangOpts().MicrosoftMode)
8798      // Microsoft enums are always of int type.
8799      EnumUnderlying = Context.IntTy.getTypePtr();
8800  }
8801
8802  DeclContext *SearchDC = CurContext;
8803  DeclContext *DC = CurContext;
8804  bool isStdBadAlloc = false;
8805
8806  RedeclarationKind Redecl = ForRedeclaration;
8807  if (TUK == TUK_Friend || TUK == TUK_Reference)
8808    Redecl = NotForRedeclaration;
8809
8810  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8811
8812  if (Name && SS.isNotEmpty()) {
8813    // We have a nested-name tag ('struct foo::bar').
8814
8815    // Check for invalid 'foo::'.
8816    if (SS.isInvalid()) {
8817      Name = 0;
8818      goto CreateNewDecl;
8819    }
8820
8821    // If this is a friend or a reference to a class in a dependent
8822    // context, don't try to make a decl for it.
8823    if (TUK == TUK_Friend || TUK == TUK_Reference) {
8824      DC = computeDeclContext(SS, false);
8825      if (!DC) {
8826        IsDependent = true;
8827        return 0;
8828      }
8829    } else {
8830      DC = computeDeclContext(SS, true);
8831      if (!DC) {
8832        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8833          << SS.getRange();
8834        return 0;
8835      }
8836    }
8837
8838    if (RequireCompleteDeclContext(SS, DC))
8839      return 0;
8840
8841    SearchDC = DC;
8842    // Look-up name inside 'foo::'.
8843    LookupQualifiedName(Previous, DC);
8844
8845    if (Previous.isAmbiguous())
8846      return 0;
8847
8848    if (Previous.empty()) {
8849      // Name lookup did not find anything. However, if the
8850      // nested-name-specifier refers to the current instantiation,
8851      // and that current instantiation has any dependent base
8852      // classes, we might find something at instantiation time: treat
8853      // this as a dependent elaborated-type-specifier.
8854      // But this only makes any sense for reference-like lookups.
8855      if (Previous.wasNotFoundInCurrentInstantiation() &&
8856          (TUK == TUK_Reference || TUK == TUK_Friend)) {
8857        IsDependent = true;
8858        return 0;
8859      }
8860
8861      // A tag 'foo::bar' must already exist.
8862      Diag(NameLoc, diag::err_not_tag_in_scope)
8863        << Kind << Name << DC << SS.getRange();
8864      Name = 0;
8865      Invalid = true;
8866      goto CreateNewDecl;
8867    }
8868  } else if (Name) {
8869    // If this is a named struct, check to see if there was a previous forward
8870    // declaration or definition.
8871    // FIXME: We're looking into outer scopes here, even when we
8872    // shouldn't be. Doing so can result in ambiguities that we
8873    // shouldn't be diagnosing.
8874    LookupName(Previous, S);
8875
8876    if (Previous.isAmbiguous() &&
8877        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8878      LookupResult::Filter F = Previous.makeFilter();
8879      while (F.hasNext()) {
8880        NamedDecl *ND = F.next();
8881        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8882          F.erase();
8883      }
8884      F.done();
8885    }
8886
8887    // Note:  there used to be some attempt at recovery here.
8888    if (Previous.isAmbiguous())
8889      return 0;
8890
8891    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8892      // FIXME: This makes sure that we ignore the contexts associated
8893      // with C structs, unions, and enums when looking for a matching
8894      // tag declaration or definition. See the similar lookup tweak
8895      // in Sema::LookupName; is there a better way to deal with this?
8896      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8897        SearchDC = SearchDC->getParent();
8898    }
8899  } else if (S->isFunctionPrototypeScope()) {
8900    // If this is an enum declaration in function prototype scope, set its
8901    // initial context to the translation unit.
8902    // FIXME: [citation needed]
8903    SearchDC = Context.getTranslationUnitDecl();
8904  }
8905
8906  if (Previous.isSingleResult() &&
8907      Previous.getFoundDecl()->isTemplateParameter()) {
8908    // Maybe we will complain about the shadowed template parameter.
8909    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8910    // Just pretend that we didn't see the previous declaration.
8911    Previous.clear();
8912  }
8913
8914  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8915      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8916    // This is a declaration of or a reference to "std::bad_alloc".
8917    isStdBadAlloc = true;
8918
8919    if (Previous.empty() && StdBadAlloc) {
8920      // std::bad_alloc has been implicitly declared (but made invisible to
8921      // name lookup). Fill in this implicit declaration as the previous
8922      // declaration, so that the declarations get chained appropriately.
8923      Previous.addDecl(getStdBadAlloc());
8924    }
8925  }
8926
8927  // If we didn't find a previous declaration, and this is a reference
8928  // (or friend reference), move to the correct scope.  In C++, we
8929  // also need to do a redeclaration lookup there, just in case
8930  // there's a shadow friend decl.
8931  if (Name && Previous.empty() &&
8932      (TUK == TUK_Reference || TUK == TUK_Friend)) {
8933    if (Invalid) goto CreateNewDecl;
8934    assert(SS.isEmpty());
8935
8936    if (TUK == TUK_Reference) {
8937      // C++ [basic.scope.pdecl]p5:
8938      //   -- for an elaborated-type-specifier of the form
8939      //
8940      //          class-key identifier
8941      //
8942      //      if the elaborated-type-specifier is used in the
8943      //      decl-specifier-seq or parameter-declaration-clause of a
8944      //      function defined in namespace scope, the identifier is
8945      //      declared as a class-name in the namespace that contains
8946      //      the declaration; otherwise, except as a friend
8947      //      declaration, the identifier is declared in the smallest
8948      //      non-class, non-function-prototype scope that contains the
8949      //      declaration.
8950      //
8951      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8952      // C structs and unions.
8953      //
8954      // It is an error in C++ to declare (rather than define) an enum
8955      // type, including via an elaborated type specifier.  We'll
8956      // diagnose that later; for now, declare the enum in the same
8957      // scope as we would have picked for any other tag type.
8958      //
8959      // GNU C also supports this behavior as part of its incomplete
8960      // enum types extension, while GNU C++ does not.
8961      //
8962      // Find the context where we'll be declaring the tag.
8963      // FIXME: We would like to maintain the current DeclContext as the
8964      // lexical context,
8965      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8966        SearchDC = SearchDC->getParent();
8967
8968      // Find the scope where we'll be declaring the tag.
8969      while (S->isClassScope() ||
8970             (getLangOpts().CPlusPlus &&
8971              S->isFunctionPrototypeScope()) ||
8972             ((S->getFlags() & Scope::DeclScope) == 0) ||
8973             (S->getEntity() &&
8974              ((DeclContext *)S->getEntity())->isTransparentContext()))
8975        S = S->getParent();
8976    } else {
8977      assert(TUK == TUK_Friend);
8978      // C++ [namespace.memdef]p3:
8979      //   If a friend declaration in a non-local class first declares a
8980      //   class or function, the friend class or function is a member of
8981      //   the innermost enclosing namespace.
8982      SearchDC = SearchDC->getEnclosingNamespaceContext();
8983    }
8984
8985    // In C++, we need to do a redeclaration lookup to properly
8986    // diagnose some problems.
8987    if (getLangOpts().CPlusPlus) {
8988      Previous.setRedeclarationKind(ForRedeclaration);
8989      LookupQualifiedName(Previous, SearchDC);
8990    }
8991  }
8992
8993  if (!Previous.empty()) {
8994    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8995
8996    // It's okay to have a tag decl in the same scope as a typedef
8997    // which hides a tag decl in the same scope.  Finding this
8998    // insanity with a redeclaration lookup can only actually happen
8999    // in C++.
9000    //
9001    // This is also okay for elaborated-type-specifiers, which is
9002    // technically forbidden by the current standard but which is
9003    // okay according to the likely resolution of an open issue;
9004    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
9005    if (getLangOpts().CPlusPlus) {
9006      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9007        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
9008          TagDecl *Tag = TT->getDecl();
9009          if (Tag->getDeclName() == Name &&
9010              Tag->getDeclContext()->getRedeclContext()
9011                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
9012            PrevDecl = Tag;
9013            Previous.clear();
9014            Previous.addDecl(Tag);
9015            Previous.resolveKind();
9016          }
9017        }
9018      }
9019    }
9020
9021    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
9022      // If this is a use of a previous tag, or if the tag is already declared
9023      // in the same scope (so that the definition/declaration completes or
9024      // rementions the tag), reuse the decl.
9025      if (TUK == TUK_Reference || TUK == TUK_Friend ||
9026          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
9027        // Make sure that this wasn't declared as an enum and now used as a
9028        // struct or something similar.
9029        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
9030                                          TUK == TUK_Definition, KWLoc,
9031                                          *Name)) {
9032          bool SafeToContinue
9033            = (PrevTagDecl->getTagKind() != TTK_Enum &&
9034               Kind != TTK_Enum);
9035          if (SafeToContinue)
9036            Diag(KWLoc, diag::err_use_with_wrong_tag)
9037              << Name
9038              << FixItHint::CreateReplacement(SourceRange(KWLoc),
9039                                              PrevTagDecl->getKindName());
9040          else
9041            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
9042          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
9043
9044          if (SafeToContinue)
9045            Kind = PrevTagDecl->getTagKind();
9046          else {
9047            // Recover by making this an anonymous redefinition.
9048            Name = 0;
9049            Previous.clear();
9050            Invalid = true;
9051          }
9052        }
9053
9054        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
9055          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
9056
9057          // If this is an elaborated-type-specifier for a scoped enumeration,
9058          // the 'class' keyword is not necessary and not permitted.
9059          if (TUK == TUK_Reference || TUK == TUK_Friend) {
9060            if (ScopedEnum)
9061              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
9062                << PrevEnum->isScoped()
9063                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
9064            return PrevTagDecl;
9065          }
9066
9067          QualType EnumUnderlyingTy;
9068          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9069            EnumUnderlyingTy = TI->getType();
9070          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
9071            EnumUnderlyingTy = QualType(T, 0);
9072
9073          // All conflicts with previous declarations are recovered by
9074          // returning the previous declaration, unless this is a definition,
9075          // in which case we want the caller to bail out.
9076          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
9077                                     ScopedEnum, EnumUnderlyingTy, PrevEnum))
9078            return TUK == TUK_Declaration ? PrevTagDecl : 0;
9079        }
9080
9081        if (!Invalid) {
9082          // If this is a use, just return the declaration we found.
9083
9084          // FIXME: In the future, return a variant or some other clue
9085          // for the consumer of this Decl to know it doesn't own it.
9086          // For our current ASTs this shouldn't be a problem, but will
9087          // need to be changed with DeclGroups.
9088          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
9089               getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
9090            return PrevTagDecl;
9091
9092          // Diagnose attempts to redefine a tag.
9093          if (TUK == TUK_Definition) {
9094            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
9095              // If we're defining a specialization and the previous definition
9096              // is from an implicit instantiation, don't emit an error
9097              // here; we'll catch this in the general case below.
9098              bool IsExplicitSpecializationAfterInstantiation = false;
9099              if (isExplicitSpecialization) {
9100                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
9101                  IsExplicitSpecializationAfterInstantiation =
9102                    RD->getTemplateSpecializationKind() !=
9103                    TSK_ExplicitSpecialization;
9104                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
9105                  IsExplicitSpecializationAfterInstantiation =
9106                    ED->getTemplateSpecializationKind() !=
9107                    TSK_ExplicitSpecialization;
9108              }
9109
9110              if (!IsExplicitSpecializationAfterInstantiation) {
9111                // A redeclaration in function prototype scope in C isn't
9112                // visible elsewhere, so merely issue a warning.
9113                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
9114                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
9115                else
9116                  Diag(NameLoc, diag::err_redefinition) << Name;
9117                Diag(Def->getLocation(), diag::note_previous_definition);
9118                // If this is a redefinition, recover by making this
9119                // struct be anonymous, which will make any later
9120                // references get the previous definition.
9121                Name = 0;
9122                Previous.clear();
9123                Invalid = true;
9124              }
9125            } else {
9126              // If the type is currently being defined, complain
9127              // about a nested redefinition.
9128              const TagType *Tag
9129                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
9130              if (Tag->isBeingDefined()) {
9131                Diag(NameLoc, diag::err_nested_redefinition) << Name;
9132                Diag(PrevTagDecl->getLocation(),
9133                     diag::note_previous_definition);
9134                Name = 0;
9135                Previous.clear();
9136                Invalid = true;
9137              }
9138            }
9139
9140            // Okay, this is definition of a previously declared or referenced
9141            // tag PrevDecl. We're going to create a new Decl for it.
9142          }
9143        }
9144        // If we get here we have (another) forward declaration or we
9145        // have a definition.  Just create a new decl.
9146
9147      } else {
9148        // If we get here, this is a definition of a new tag type in a nested
9149        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
9150        // new decl/type.  We set PrevDecl to NULL so that the entities
9151        // have distinct types.
9152        Previous.clear();
9153      }
9154      // If we get here, we're going to create a new Decl. If PrevDecl
9155      // is non-NULL, it's a definition of the tag declared by
9156      // PrevDecl. If it's NULL, we have a new definition.
9157
9158
9159    // Otherwise, PrevDecl is not a tag, but was found with tag
9160    // lookup.  This is only actually possible in C++, where a few
9161    // things like templates still live in the tag namespace.
9162    } else {
9163      // Use a better diagnostic if an elaborated-type-specifier
9164      // found the wrong kind of type on the first
9165      // (non-redeclaration) lookup.
9166      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
9167          !Previous.isForRedeclaration()) {
9168        unsigned Kind = 0;
9169        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9170        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9171        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9172        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9173        Diag(PrevDecl->getLocation(), diag::note_declared_at);
9174        Invalid = true;
9175
9176      // Otherwise, only diagnose if the declaration is in scope.
9177      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9178                                isExplicitSpecialization)) {
9179        // do nothing
9180
9181      // Diagnose implicit declarations introduced by elaborated types.
9182      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9183        unsigned Kind = 0;
9184        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9185        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9186        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9187        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9188        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9189        Invalid = true;
9190
9191      // Otherwise it's a declaration.  Call out a particularly common
9192      // case here.
9193      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9194        unsigned Kind = 0;
9195        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
9196        Diag(NameLoc, diag::err_tag_definition_of_typedef)
9197          << Name << Kind << TND->getUnderlyingType();
9198        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9199        Invalid = true;
9200
9201      // Otherwise, diagnose.
9202      } else {
9203        // The tag name clashes with something else in the target scope,
9204        // issue an error and recover by making this tag be anonymous.
9205        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
9206        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9207        Name = 0;
9208        Invalid = true;
9209      }
9210
9211      // The existing declaration isn't relevant to us; we're in a
9212      // new scope, so clear out the previous declaration.
9213      Previous.clear();
9214    }
9215  }
9216
9217CreateNewDecl:
9218
9219  TagDecl *PrevDecl = 0;
9220  if (Previous.isSingleResult())
9221    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9222
9223  // If there is an identifier, use the location of the identifier as the
9224  // location of the decl, otherwise use the location of the struct/union
9225  // keyword.
9226  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
9227
9228  // Otherwise, create a new declaration. If there is a previous
9229  // declaration of the same entity, the two will be linked via
9230  // PrevDecl.
9231  TagDecl *New;
9232
9233  bool IsForwardReference = false;
9234  if (Kind == TTK_Enum) {
9235    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9236    // enum X { A, B, C } D;    D should chain to X.
9237    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
9238                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
9239                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
9240    // If this is an undefined enum, warn.
9241    if (TUK != TUK_Definition && !Invalid) {
9242      TagDecl *Def;
9243      if (getLangOpts().CPlusPlus11 && cast<EnumDecl>(New)->isFixed()) {
9244        // C++0x: 7.2p2: opaque-enum-declaration.
9245        // Conflicts are diagnosed above. Do nothing.
9246      }
9247      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
9248        Diag(Loc, diag::ext_forward_ref_enum_def)
9249          << New;
9250        Diag(Def->getLocation(), diag::note_previous_definition);
9251      } else {
9252        unsigned DiagID = diag::ext_forward_ref_enum;
9253        if (getLangOpts().MicrosoftMode)
9254          DiagID = diag::ext_ms_forward_ref_enum;
9255        else if (getLangOpts().CPlusPlus)
9256          DiagID = diag::err_forward_ref_enum;
9257        Diag(Loc, DiagID);
9258
9259        // If this is a forward-declared reference to an enumeration, make a
9260        // note of it; we won't actually be introducing the declaration into
9261        // the declaration context.
9262        if (TUK == TUK_Reference)
9263          IsForwardReference = true;
9264      }
9265    }
9266
9267    if (EnumUnderlying) {
9268      EnumDecl *ED = cast<EnumDecl>(New);
9269      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9270        ED->setIntegerTypeSourceInfo(TI);
9271      else
9272        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9273      ED->setPromotionType(ED->getIntegerType());
9274    }
9275
9276  } else {
9277    // struct/union/class
9278
9279    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9280    // struct X { int A; } D;    D should chain to X.
9281    if (getLangOpts().CPlusPlus) {
9282      // FIXME: Look for a way to use RecordDecl for simple structs.
9283      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9284                                  cast_or_null<CXXRecordDecl>(PrevDecl));
9285
9286      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
9287        StdBadAlloc = cast<CXXRecordDecl>(New);
9288    } else
9289      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9290                               cast_or_null<RecordDecl>(PrevDecl));
9291  }
9292
9293  // Maybe add qualifier info.
9294  if (SS.isNotEmpty()) {
9295    if (SS.isSet()) {
9296      // If this is either a declaration or a definition, check the
9297      // nested-name-specifier against the current context. We don't do this
9298      // for explicit specializations, because they have similar checking
9299      // (with more specific diagnostics) in the call to
9300      // CheckMemberSpecialization, below.
9301      if (!isExplicitSpecialization &&
9302          (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9303          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9304        Invalid = true;
9305
9306      New->setQualifierInfo(SS.getWithLocInContext(Context));
9307      if (TemplateParameterLists.size() > 0) {
9308        New->setTemplateParameterListsInfo(Context,
9309                                           TemplateParameterLists.size(),
9310                                           TemplateParameterLists.data());
9311      }
9312    }
9313    else
9314      Invalid = true;
9315  }
9316
9317  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9318    // Add alignment attributes if necessary; these attributes are checked when
9319    // the ASTContext lays out the structure.
9320    //
9321    // It is important for implementing the correct semantics that this
9322    // happen here (in act on tag decl). The #pragma pack stack is
9323    // maintained as a result of parser callbacks which can occur at
9324    // many points during the parsing of a struct declaration (because
9325    // the #pragma tokens are effectively skipped over during the
9326    // parsing of the struct).
9327    if (TUK == TUK_Definition) {
9328      AddAlignmentAttributesForRecord(RD);
9329      AddMsStructLayoutForRecord(RD);
9330    }
9331  }
9332
9333  if (ModulePrivateLoc.isValid()) {
9334    if (isExplicitSpecialization)
9335      Diag(New->getLocation(), diag::err_module_private_specialization)
9336        << 2
9337        << FixItHint::CreateRemoval(ModulePrivateLoc);
9338    // __module_private__ does not apply to local classes. However, we only
9339    // diagnose this as an error when the declaration specifiers are
9340    // freestanding. Here, we just ignore the __module_private__.
9341    else if (!SearchDC->isFunctionOrMethod())
9342      New->setModulePrivate();
9343  }
9344
9345  // If this is a specialization of a member class (of a class template),
9346  // check the specialization.
9347  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
9348    Invalid = true;
9349
9350  if (Invalid)
9351    New->setInvalidDecl();
9352
9353  if (Attr)
9354    ProcessDeclAttributeList(S, New, Attr);
9355
9356  // If we're declaring or defining a tag in function prototype scope
9357  // in C, note that this type can only be used within the function.
9358  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
9359    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9360
9361  // Set the lexical context. If the tag has a C++ scope specifier, the
9362  // lexical context will be different from the semantic context.
9363  New->setLexicalDeclContext(CurContext);
9364
9365  // Mark this as a friend decl if applicable.
9366  // In Microsoft mode, a friend declaration also acts as a forward
9367  // declaration so we always pass true to setObjectOfFriendDecl to make
9368  // the tag name visible.
9369  if (TUK == TUK_Friend)
9370    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
9371                               getLangOpts().MicrosoftExt);
9372
9373  // Set the access specifier.
9374  if (!Invalid && SearchDC->isRecord())
9375    SetMemberAccessSpecifier(New, PrevDecl, AS);
9376
9377  if (TUK == TUK_Definition)
9378    New->startDefinition();
9379
9380  // If this has an identifier, add it to the scope stack.
9381  if (TUK == TUK_Friend) {
9382    // We might be replacing an existing declaration in the lookup tables;
9383    // if so, borrow its access specifier.
9384    if (PrevDecl)
9385      New->setAccess(PrevDecl->getAccess());
9386
9387    DeclContext *DC = New->getDeclContext()->getRedeclContext();
9388    DC->makeDeclVisibleInContext(New);
9389    if (Name) // can be null along some error paths
9390      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9391        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
9392  } else if (Name) {
9393    S = getNonFieldDeclScope(S);
9394    PushOnScopeChains(New, S, !IsForwardReference);
9395    if (IsForwardReference)
9396      SearchDC->makeDeclVisibleInContext(New);
9397
9398  } else {
9399    CurContext->addDecl(New);
9400  }
9401
9402  // If this is the C FILE type, notify the AST context.
9403  if (IdentifierInfo *II = New->getIdentifier())
9404    if (!New->isInvalidDecl() &&
9405        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
9406        II->isStr("FILE"))
9407      Context.setFILEDecl(New);
9408
9409  // If we were in function prototype scope (and not in C++ mode), add this
9410  // tag to the list of decls to inject into the function definition scope.
9411  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
9412      InFunctionDeclarator && Name)
9413    DeclsInPrototypeScope.push_back(New);
9414
9415  if (PrevDecl)
9416    mergeDeclAttributes(New, PrevDecl);
9417
9418  // If there's a #pragma GCC visibility in scope, set the visibility of this
9419  // record.
9420  AddPushedVisibilityAttribute(New);
9421
9422  OwnedDecl = true;
9423  // In C++, don't return an invalid declaration. We can't recover well from
9424  // the cases where we make the type anonymous.
9425  return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
9426}
9427
9428void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
9429  AdjustDeclIfTemplate(TagD);
9430  TagDecl *Tag = cast<TagDecl>(TagD);
9431
9432  // Enter the tag context.
9433  PushDeclContext(S, Tag);
9434
9435  ActOnDocumentableDecl(TagD);
9436
9437  // If there's a #pragma GCC visibility in scope, set the visibility of this
9438  // record.
9439  AddPushedVisibilityAttribute(Tag);
9440}
9441
9442Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
9443  assert(isa<ObjCContainerDecl>(IDecl) &&
9444         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
9445  DeclContext *OCD = cast<DeclContext>(IDecl);
9446  assert(getContainingDC(OCD) == CurContext &&
9447      "The next DeclContext should be lexically contained in the current one.");
9448  CurContext = OCD;
9449  return IDecl;
9450}
9451
9452void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
9453                                           SourceLocation FinalLoc,
9454                                           SourceLocation LBraceLoc) {
9455  AdjustDeclIfTemplate(TagD);
9456  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
9457
9458  FieldCollector->StartClass();
9459
9460  if (!Record->getIdentifier())
9461    return;
9462
9463  if (FinalLoc.isValid())
9464    Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
9465
9466  // C++ [class]p2:
9467  //   [...] The class-name is also inserted into the scope of the
9468  //   class itself; this is known as the injected-class-name. For
9469  //   purposes of access checking, the injected-class-name is treated
9470  //   as if it were a public member name.
9471  CXXRecordDecl *InjectedClassName
9472    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
9473                            Record->getLocStart(), Record->getLocation(),
9474                            Record->getIdentifier(),
9475                            /*PrevDecl=*/0,
9476                            /*DelayTypeCreation=*/true);
9477  Context.getTypeDeclType(InjectedClassName, Record);
9478  InjectedClassName->setImplicit();
9479  InjectedClassName->setAccess(AS_public);
9480  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
9481      InjectedClassName->setDescribedClassTemplate(Template);
9482  PushOnScopeChains(InjectedClassName, S);
9483  assert(InjectedClassName->isInjectedClassName() &&
9484         "Broken injected-class-name");
9485}
9486
9487void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
9488                                    SourceLocation RBraceLoc) {
9489  AdjustDeclIfTemplate(TagD);
9490  TagDecl *Tag = cast<TagDecl>(TagD);
9491  Tag->setRBraceLoc(RBraceLoc);
9492
9493  // Make sure we "complete" the definition even it is invalid.
9494  if (Tag->isBeingDefined()) {
9495    assert(Tag->isInvalidDecl() && "We should already have completed it");
9496    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9497      RD->completeDefinition();
9498  }
9499
9500  if (isa<CXXRecordDecl>(Tag))
9501    FieldCollector->FinishClass();
9502
9503  // Exit this scope of this tag's definition.
9504  PopDeclContext();
9505
9506  // Notify the consumer that we've defined a tag.
9507  Consumer.HandleTagDeclDefinition(Tag);
9508}
9509
9510void Sema::ActOnObjCContainerFinishDefinition() {
9511  // Exit this scope of this interface definition.
9512  PopDeclContext();
9513}
9514
9515void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
9516  assert(DC == CurContext && "Mismatch of container contexts");
9517  OriginalLexicalContext = DC;
9518  ActOnObjCContainerFinishDefinition();
9519}
9520
9521void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9522  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
9523  OriginalLexicalContext = 0;
9524}
9525
9526void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
9527  AdjustDeclIfTemplate(TagD);
9528  TagDecl *Tag = cast<TagDecl>(TagD);
9529  Tag->setInvalidDecl();
9530
9531  // Make sure we "complete" the definition even it is invalid.
9532  if (Tag->isBeingDefined()) {
9533    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9534      RD->completeDefinition();
9535  }
9536
9537  // We're undoing ActOnTagStartDefinition here, not
9538  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9539  // the FieldCollector.
9540
9541  PopDeclContext();
9542}
9543
9544// Note that FieldName may be null for anonymous bitfields.
9545ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9546                                IdentifierInfo *FieldName,
9547                                QualType FieldTy, Expr *BitWidth,
9548                                bool *ZeroWidth) {
9549  // Default to true; that shouldn't confuse checks for emptiness
9550  if (ZeroWidth)
9551    *ZeroWidth = true;
9552
9553  // C99 6.7.2.1p4 - verify the field type.
9554  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
9555  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
9556    // Handle incomplete types with specific error.
9557    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
9558      return ExprError();
9559    if (FieldName)
9560      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9561        << FieldName << FieldTy << BitWidth->getSourceRange();
9562    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9563      << FieldTy << BitWidth->getSourceRange();
9564  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9565                                             UPPC_BitFieldWidth))
9566    return ExprError();
9567
9568  // If the bit-width is type- or value-dependent, don't try to check
9569  // it now.
9570  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
9571    return Owned(BitWidth);
9572
9573  llvm::APSInt Value;
9574  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9575  if (ICE.isInvalid())
9576    return ICE;
9577  BitWidth = ICE.take();
9578
9579  if (Value != 0 && ZeroWidth)
9580    *ZeroWidth = false;
9581
9582  // Zero-width bitfield is ok for anonymous field.
9583  if (Value == 0 && FieldName)
9584    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
9585
9586  if (Value.isSigned() && Value.isNegative()) {
9587    if (FieldName)
9588      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
9589               << FieldName << Value.toString(10);
9590    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9591      << Value.toString(10);
9592  }
9593
9594  if (!FieldTy->isDependentType()) {
9595    uint64_t TypeSize = Context.getTypeSize(FieldTy);
9596    if (Value.getZExtValue() > TypeSize) {
9597      if (!getLangOpts().CPlusPlus) {
9598        if (FieldName)
9599          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9600            << FieldName << (unsigned)Value.getZExtValue()
9601            << (unsigned)TypeSize;
9602
9603        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9604          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9605      }
9606
9607      if (FieldName)
9608        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9609          << FieldName << (unsigned)Value.getZExtValue()
9610          << (unsigned)TypeSize;
9611      else
9612        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9613          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9614    }
9615  }
9616
9617  return Owned(BitWidth);
9618}
9619
9620/// ActOnField - Each field of a C struct/union is passed into this in order
9621/// to create a FieldDecl object for it.
9622Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
9623                       Declarator &D, Expr *BitfieldWidth) {
9624  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
9625                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
9626                               /*InitStyle=*/ICIS_NoInit, AS_public);
9627  return Res;
9628}
9629
9630/// HandleField - Analyze a field of a C struct or a C++ data member.
9631///
9632FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9633                             SourceLocation DeclStart,
9634                             Declarator &D, Expr *BitWidth,
9635                             InClassInitStyle InitStyle,
9636                             AccessSpecifier AS) {
9637  IdentifierInfo *II = D.getIdentifier();
9638  SourceLocation Loc = DeclStart;
9639  if (II) Loc = D.getIdentifierLoc();
9640
9641  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9642  QualType T = TInfo->getType();
9643  if (getLangOpts().CPlusPlus) {
9644    CheckExtraCXXDefaultArguments(D);
9645
9646    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9647                                        UPPC_DataMemberType)) {
9648      D.setInvalidType();
9649      T = Context.IntTy;
9650      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9651    }
9652  }
9653
9654  DiagnoseFunctionSpecifiers(D);
9655
9656  if (D.getDeclSpec().isThreadSpecified())
9657    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
9658  if (D.getDeclSpec().isConstexprSpecified())
9659    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9660      << 2;
9661
9662  // Check to see if this name was declared as a member previously
9663  NamedDecl *PrevDecl = 0;
9664  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9665  LookupName(Previous, S);
9666  switch (Previous.getResultKind()) {
9667    case LookupResult::Found:
9668    case LookupResult::FoundUnresolvedValue:
9669      PrevDecl = Previous.getAsSingle<NamedDecl>();
9670      break;
9671
9672    case LookupResult::FoundOverloaded:
9673      PrevDecl = Previous.getRepresentativeDecl();
9674      break;
9675
9676    case LookupResult::NotFound:
9677    case LookupResult::NotFoundInCurrentInstantiation:
9678    case LookupResult::Ambiguous:
9679      break;
9680  }
9681  Previous.suppressDiagnostics();
9682
9683  if (PrevDecl && PrevDecl->isTemplateParameter()) {
9684    // Maybe we will complain about the shadowed template parameter.
9685    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9686    // Just pretend that we didn't see the previous declaration.
9687    PrevDecl = 0;
9688  }
9689
9690  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9691    PrevDecl = 0;
9692
9693  bool Mutable
9694    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
9695  SourceLocation TSSL = D.getLocStart();
9696  FieldDecl *NewFD
9697    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
9698                     TSSL, AS, PrevDecl, &D);
9699
9700  if (NewFD->isInvalidDecl())
9701    Record->setInvalidDecl();
9702
9703  if (D.getDeclSpec().isModulePrivateSpecified())
9704    NewFD->setModulePrivate();
9705
9706  if (NewFD->isInvalidDecl() && PrevDecl) {
9707    // Don't introduce NewFD into scope; there's already something
9708    // with the same name in the same scope.
9709  } else if (II) {
9710    PushOnScopeChains(NewFD, S);
9711  } else
9712    Record->addDecl(NewFD);
9713
9714  return NewFD;
9715}
9716
9717/// \brief Build a new FieldDecl and check its well-formedness.
9718///
9719/// This routine builds a new FieldDecl given the fields name, type,
9720/// record, etc. \p PrevDecl should refer to any previous declaration
9721/// with the same name and in the same scope as the field to be
9722/// created.
9723///
9724/// \returns a new FieldDecl.
9725///
9726/// \todo The Declarator argument is a hack. It will be removed once
9727FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
9728                                TypeSourceInfo *TInfo,
9729                                RecordDecl *Record, SourceLocation Loc,
9730                                bool Mutable, Expr *BitWidth,
9731                                InClassInitStyle InitStyle,
9732                                SourceLocation TSSL,
9733                                AccessSpecifier AS, NamedDecl *PrevDecl,
9734                                Declarator *D) {
9735  IdentifierInfo *II = Name.getAsIdentifierInfo();
9736  bool InvalidDecl = false;
9737  if (D) InvalidDecl = D->isInvalidType();
9738
9739  // If we receive a broken type, recover by assuming 'int' and
9740  // marking this declaration as invalid.
9741  if (T.isNull()) {
9742    InvalidDecl = true;
9743    T = Context.IntTy;
9744  }
9745
9746  QualType EltTy = Context.getBaseElementType(T);
9747  if (!EltTy->isDependentType()) {
9748    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9749      // Fields of incomplete type force their record to be invalid.
9750      Record->setInvalidDecl();
9751      InvalidDecl = true;
9752    } else {
9753      NamedDecl *Def;
9754      EltTy->isIncompleteType(&Def);
9755      if (Def && Def->isInvalidDecl()) {
9756        Record->setInvalidDecl();
9757        InvalidDecl = true;
9758      }
9759    }
9760  }
9761
9762  // C99 6.7.2.1p8: A member of a structure or union may have any type other
9763  // than a variably modified type.
9764  if (!InvalidDecl && T->isVariablyModifiedType()) {
9765    bool SizeIsNegative;
9766    llvm::APSInt Oversized;
9767
9768    TypeSourceInfo *FixedTInfo =
9769      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
9770                                                    SizeIsNegative,
9771                                                    Oversized);
9772    if (FixedTInfo) {
9773      Diag(Loc, diag::warn_illegal_constant_array_size);
9774      TInfo = FixedTInfo;
9775      T = FixedTInfo->getType();
9776    } else {
9777      if (SizeIsNegative)
9778        Diag(Loc, diag::err_typecheck_negative_array_size);
9779      else if (Oversized.getBoolValue())
9780        Diag(Loc, diag::err_array_too_large)
9781          << Oversized.toString(10);
9782      else
9783        Diag(Loc, diag::err_typecheck_field_variable_size);
9784      InvalidDecl = true;
9785    }
9786  }
9787
9788  // Fields can not have abstract class types
9789  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9790                                             diag::err_abstract_type_in_decl,
9791                                             AbstractFieldType))
9792    InvalidDecl = true;
9793
9794  bool ZeroWidth = false;
9795  // If this is declared as a bit-field, check the bit-field.
9796  if (!InvalidDecl && BitWidth) {
9797    BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9798    if (!BitWidth) {
9799      InvalidDecl = true;
9800      BitWidth = 0;
9801      ZeroWidth = false;
9802    }
9803  }
9804
9805  // Check that 'mutable' is consistent with the type of the declaration.
9806  if (!InvalidDecl && Mutable) {
9807    unsigned DiagID = 0;
9808    if (T->isReferenceType())
9809      DiagID = diag::err_mutable_reference;
9810    else if (T.isConstQualified())
9811      DiagID = diag::err_mutable_const;
9812
9813    if (DiagID) {
9814      SourceLocation ErrLoc = Loc;
9815      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9816        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9817      Diag(ErrLoc, DiagID);
9818      Mutable = false;
9819      InvalidDecl = true;
9820    }
9821  }
9822
9823  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9824                                       BitWidth, Mutable, InitStyle);
9825  if (InvalidDecl)
9826    NewFD->setInvalidDecl();
9827
9828  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9829    Diag(Loc, diag::err_duplicate_member) << II;
9830    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9831    NewFD->setInvalidDecl();
9832  }
9833
9834  if (!InvalidDecl && getLangOpts().CPlusPlus) {
9835    if (Record->isUnion()) {
9836      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9837        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9838        if (RDecl->getDefinition()) {
9839          // C++ [class.union]p1: An object of a class with a non-trivial
9840          // constructor, a non-trivial copy constructor, a non-trivial
9841          // destructor, or a non-trivial copy assignment operator
9842          // cannot be a member of a union, nor can an array of such
9843          // objects.
9844          if (CheckNontrivialField(NewFD))
9845            NewFD->setInvalidDecl();
9846        }
9847      }
9848
9849      // C++ [class.union]p1: If a union contains a member of reference type,
9850      // the program is ill-formed.
9851      if (EltTy->isReferenceType()) {
9852        Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9853          << NewFD->getDeclName() << EltTy;
9854        NewFD->setInvalidDecl();
9855      }
9856    }
9857  }
9858
9859  // FIXME: We need to pass in the attributes given an AST
9860  // representation, not a parser representation.
9861  if (D)
9862    // FIXME: What to pass instead of TUScope?
9863    ProcessDeclAttributes(TUScope, NewFD, *D);
9864
9865  // In auto-retain/release, infer strong retension for fields of
9866  // retainable type.
9867  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9868    NewFD->setInvalidDecl();
9869
9870  if (T.isObjCGCWeak())
9871    Diag(Loc, diag::warn_attribute_weak_on_field);
9872
9873  NewFD->setAccess(AS);
9874  return NewFD;
9875}
9876
9877bool Sema::CheckNontrivialField(FieldDecl *FD) {
9878  assert(FD);
9879  assert(getLangOpts().CPlusPlus && "valid check only for C++");
9880
9881  if (FD->isInvalidDecl())
9882    return true;
9883
9884  QualType EltTy = Context.getBaseElementType(FD->getType());
9885  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9886    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
9887    if (RDecl->getDefinition()) {
9888      // We check for copy constructors before constructors
9889      // because otherwise we'll never get complaints about
9890      // copy constructors.
9891
9892      CXXSpecialMember member = CXXInvalid;
9893      // We're required to check for any non-trivial constructors. Since the
9894      // implicit default constructor is suppressed if there are any
9895      // user-declared constructors, we just need to check that there is a
9896      // trivial default constructor and a trivial copy constructor. (We don't
9897      // worry about move constructors here, since this is a C++98 check.)
9898      if (RDecl->hasNonTrivialCopyConstructor())
9899        member = CXXCopyConstructor;
9900      else if (!RDecl->hasTrivialDefaultConstructor())
9901        member = CXXDefaultConstructor;
9902      else if (RDecl->hasNonTrivialCopyAssignment())
9903        member = CXXCopyAssignment;
9904      else if (RDecl->hasNonTrivialDestructor())
9905        member = CXXDestructor;
9906
9907      if (member != CXXInvalid) {
9908        if (!getLangOpts().CPlusPlus11 &&
9909            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9910          // Objective-C++ ARC: it is an error to have a non-trivial field of
9911          // a union. However, system headers in Objective-C programs
9912          // occasionally have Objective-C lifetime objects within unions,
9913          // and rather than cause the program to fail, we make those
9914          // members unavailable.
9915          SourceLocation Loc = FD->getLocation();
9916          if (getSourceManager().isInSystemHeader(Loc)) {
9917            if (!FD->hasAttr<UnavailableAttr>())
9918              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9919                                  "this system field has retaining ownership"));
9920            return false;
9921          }
9922        }
9923
9924        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
9925               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9926               diag::err_illegal_union_or_anon_struct_member)
9927          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9928        DiagnoseNontrivial(RDecl, member);
9929        return !getLangOpts().CPlusPlus11;
9930      }
9931    }
9932  }
9933
9934  return false;
9935}
9936
9937/// TranslateIvarVisibility - Translate visibility from a token ID to an
9938///  AST enum value.
9939static ObjCIvarDecl::AccessControl
9940TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9941  switch (ivarVisibility) {
9942  default: llvm_unreachable("Unknown visitibility kind");
9943  case tok::objc_private: return ObjCIvarDecl::Private;
9944  case tok::objc_public: return ObjCIvarDecl::Public;
9945  case tok::objc_protected: return ObjCIvarDecl::Protected;
9946  case tok::objc_package: return ObjCIvarDecl::Package;
9947  }
9948}
9949
9950/// ActOnIvar - Each ivar field of an objective-c class is passed into this
9951/// in order to create an IvarDecl object for it.
9952Decl *Sema::ActOnIvar(Scope *S,
9953                                SourceLocation DeclStart,
9954                                Declarator &D, Expr *BitfieldWidth,
9955                                tok::ObjCKeywordKind Visibility) {
9956
9957  IdentifierInfo *II = D.getIdentifier();
9958  Expr *BitWidth = (Expr*)BitfieldWidth;
9959  SourceLocation Loc = DeclStart;
9960  if (II) Loc = D.getIdentifierLoc();
9961
9962  // FIXME: Unnamed fields can be handled in various different ways, for
9963  // example, unnamed unions inject all members into the struct namespace!
9964
9965  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9966  QualType T = TInfo->getType();
9967
9968  if (BitWidth) {
9969    // 6.7.2.1p3, 6.7.2.1p4
9970    BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9971    if (!BitWidth)
9972      D.setInvalidType();
9973  } else {
9974    // Not a bitfield.
9975
9976    // validate II.
9977
9978  }
9979  if (T->isReferenceType()) {
9980    Diag(Loc, diag::err_ivar_reference_type);
9981    D.setInvalidType();
9982  }
9983  // C99 6.7.2.1p8: A member of a structure or union may have any type other
9984  // than a variably modified type.
9985  else if (T->isVariablyModifiedType()) {
9986    Diag(Loc, diag::err_typecheck_ivar_variable_size);
9987    D.setInvalidType();
9988  }
9989
9990  // Get the visibility (access control) for this ivar.
9991  ObjCIvarDecl::AccessControl ac =
9992    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9993                                        : ObjCIvarDecl::None;
9994  // Must set ivar's DeclContext to its enclosing interface.
9995  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9996  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9997    return 0;
9998  ObjCContainerDecl *EnclosingContext;
9999  if (ObjCImplementationDecl *IMPDecl =
10000      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10001    if (LangOpts.ObjCRuntime.isFragile()) {
10002    // Case of ivar declared in an implementation. Context is that of its class.
10003      EnclosingContext = IMPDecl->getClassInterface();
10004      assert(EnclosingContext && "Implementation has no class interface!");
10005    }
10006    else
10007      EnclosingContext = EnclosingDecl;
10008  } else {
10009    if (ObjCCategoryDecl *CDecl =
10010        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10011      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
10012        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
10013        return 0;
10014      }
10015    }
10016    EnclosingContext = EnclosingDecl;
10017  }
10018
10019  // Construct the decl.
10020  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
10021                                             DeclStart, Loc, II, T,
10022                                             TInfo, ac, (Expr *)BitfieldWidth);
10023
10024  if (II) {
10025    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
10026                                           ForRedeclaration);
10027    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
10028        && !isa<TagDecl>(PrevDecl)) {
10029      Diag(Loc, diag::err_duplicate_member) << II;
10030      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10031      NewID->setInvalidDecl();
10032    }
10033  }
10034
10035  // Process attributes attached to the ivar.
10036  ProcessDeclAttributes(S, NewID, D);
10037
10038  if (D.isInvalidType())
10039    NewID->setInvalidDecl();
10040
10041  // In ARC, infer 'retaining' for ivars of retainable type.
10042  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
10043    NewID->setInvalidDecl();
10044
10045  if (D.getDeclSpec().isModulePrivateSpecified())
10046    NewID->setModulePrivate();
10047
10048  if (II) {
10049    // FIXME: When interfaces are DeclContexts, we'll need to add
10050    // these to the interface.
10051    S->AddDecl(NewID);
10052    IdResolver.AddDecl(NewID);
10053  }
10054
10055  if (LangOpts.ObjCRuntime.isNonFragile() &&
10056      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
10057    Diag(Loc, diag::warn_ivars_in_interface);
10058
10059  return NewID;
10060}
10061
10062/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
10063/// class and class extensions. For every class @interface and class
10064/// extension @interface, if the last ivar is a bitfield of any type,
10065/// then add an implicit `char :0` ivar to the end of that interface.
10066void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
10067                             SmallVectorImpl<Decl *> &AllIvarDecls) {
10068  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
10069    return;
10070
10071  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
10072  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
10073
10074  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
10075    return;
10076  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
10077  if (!ID) {
10078    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
10079      if (!CD->IsClassExtension())
10080        return;
10081    }
10082    // No need to add this to end of @implementation.
10083    else
10084      return;
10085  }
10086  // All conditions are met. Add a new bitfield to the tail end of ivars.
10087  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
10088  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
10089
10090  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
10091                              DeclLoc, DeclLoc, 0,
10092                              Context.CharTy,
10093                              Context.getTrivialTypeSourceInfo(Context.CharTy,
10094                                                               DeclLoc),
10095                              ObjCIvarDecl::Private, BW,
10096                              true);
10097  AllIvarDecls.push_back(Ivar);
10098}
10099
10100void Sema::ActOnFields(Scope* S,
10101                       SourceLocation RecLoc, Decl *EnclosingDecl,
10102                       llvm::ArrayRef<Decl *> Fields,
10103                       SourceLocation LBrac, SourceLocation RBrac,
10104                       AttributeList *Attr) {
10105  assert(EnclosingDecl && "missing record or interface decl");
10106
10107  // If this is an Objective-C @implementation or category and we have
10108  // new fields here we should reset the layout of the interface since
10109  // it will now change.
10110  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10111    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10112    switch (DC->getKind()) {
10113    default: break;
10114    case Decl::ObjCCategory:
10115      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10116      break;
10117    case Decl::ObjCImplementation:
10118      Context.
10119        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10120      break;
10121    }
10122  }
10123
10124  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10125
10126  // Start counting up the number of named members; make sure to include
10127  // members of anonymous structs and unions in the total.
10128  unsigned NumNamedMembers = 0;
10129  if (Record) {
10130    for (RecordDecl::decl_iterator i = Record->decls_begin(),
10131                                   e = Record->decls_end(); i != e; i++) {
10132      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10133        if (IFD->getDeclName())
10134          ++NumNamedMembers;
10135    }
10136  }
10137
10138  // Verify that all the fields are okay.
10139  SmallVector<FieldDecl*, 32> RecFields;
10140
10141  bool ARCErrReported = false;
10142  for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10143       i != end; ++i) {
10144    FieldDecl *FD = cast<FieldDecl>(*i);
10145
10146    // Get the type for the field.
10147    const Type *FDTy = FD->getType().getTypePtr();
10148
10149    if (!FD->isAnonymousStructOrUnion()) {
10150      // Remember all fields written by the user.
10151      RecFields.push_back(FD);
10152    }
10153
10154    // If the field is already invalid for some reason, don't emit more
10155    // diagnostics about it.
10156    if (FD->isInvalidDecl()) {
10157      EnclosingDecl->setInvalidDecl();
10158      continue;
10159    }
10160
10161    // C99 6.7.2.1p2:
10162    //   A structure or union shall not contain a member with
10163    //   incomplete or function type (hence, a structure shall not
10164    //   contain an instance of itself, but may contain a pointer to
10165    //   an instance of itself), except that the last member of a
10166    //   structure with more than one named member may have incomplete
10167    //   array type; such a structure (and any union containing,
10168    //   possibly recursively, a member that is such a structure)
10169    //   shall not be a member of a structure or an element of an
10170    //   array.
10171    if (FDTy->isFunctionType()) {
10172      // Field declared as a function.
10173      Diag(FD->getLocation(), diag::err_field_declared_as_function)
10174        << FD->getDeclName();
10175      FD->setInvalidDecl();
10176      EnclosingDecl->setInvalidDecl();
10177      continue;
10178    } else if (FDTy->isIncompleteArrayType() && Record &&
10179               ((i + 1 == Fields.end() && !Record->isUnion()) ||
10180                ((getLangOpts().MicrosoftExt ||
10181                  getLangOpts().CPlusPlus) &&
10182                 (i + 1 == Fields.end() || Record->isUnion())))) {
10183      // Flexible array member.
10184      // Microsoft and g++ is more permissive regarding flexible array.
10185      // It will accept flexible array in union and also
10186      // as the sole element of a struct/class.
10187      if (getLangOpts().MicrosoftExt) {
10188        if (Record->isUnion())
10189          Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
10190            << FD->getDeclName();
10191        else if (Fields.size() == 1)
10192          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
10193            << FD->getDeclName() << Record->getTagKind();
10194      } else if (getLangOpts().CPlusPlus) {
10195        if (Record->isUnion())
10196          Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10197            << FD->getDeclName();
10198        else if (Fields.size() == 1)
10199          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10200            << FD->getDeclName() << Record->getTagKind();
10201      } else if (!getLangOpts().C99) {
10202      if (Record->isUnion())
10203        Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10204          << FD->getDeclName();
10205      else
10206        Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10207          << FD->getDeclName() << Record->getTagKind();
10208      } else if (NumNamedMembers < 1) {
10209        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
10210          << FD->getDeclName();
10211        FD->setInvalidDecl();
10212        EnclosingDecl->setInvalidDecl();
10213        continue;
10214      }
10215      if (!FD->getType()->isDependentType() &&
10216          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
10217        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
10218          << FD->getDeclName() << FD->getType();
10219        FD->setInvalidDecl();
10220        EnclosingDecl->setInvalidDecl();
10221        continue;
10222      }
10223      // Okay, we have a legal flexible array member at the end of the struct.
10224      if (Record)
10225        Record->setHasFlexibleArrayMember(true);
10226    } else if (!FDTy->isDependentType() &&
10227               RequireCompleteType(FD->getLocation(), FD->getType(),
10228                                   diag::err_field_incomplete)) {
10229      // Incomplete type
10230      FD->setInvalidDecl();
10231      EnclosingDecl->setInvalidDecl();
10232      continue;
10233    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
10234      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10235        // If this is a member of a union, then entire union becomes "flexible".
10236        if (Record && Record->isUnion()) {
10237          Record->setHasFlexibleArrayMember(true);
10238        } else {
10239          // If this is a struct/class and this is not the last element, reject
10240          // it.  Note that GCC supports variable sized arrays in the middle of
10241          // structures.
10242          if (i + 1 != Fields.end())
10243            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
10244              << FD->getDeclName() << FD->getType();
10245          else {
10246            // We support flexible arrays at the end of structs in
10247            // other structs as an extension.
10248            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10249              << FD->getDeclName();
10250            if (Record)
10251              Record->setHasFlexibleArrayMember(true);
10252          }
10253        }
10254      }
10255      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10256          RequireNonAbstractType(FD->getLocation(), FD->getType(),
10257                                 diag::err_abstract_type_in_decl,
10258                                 AbstractIvarType)) {
10259        // Ivars can not have abstract class types
10260        FD->setInvalidDecl();
10261      }
10262      if (Record && FDTTy->getDecl()->hasObjectMember())
10263        Record->setHasObjectMember(true);
10264    } else if (FDTy->isObjCObjectType()) {
10265      /// A field cannot be an Objective-c object
10266      Diag(FD->getLocation(), diag::err_statically_allocated_object)
10267        << FixItHint::CreateInsertion(FD->getLocation(), "*");
10268      QualType T = Context.getObjCObjectPointerType(FD->getType());
10269      FD->setType(T);
10270    } else if (!getLangOpts().CPlusPlus) {
10271      if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
10272        // It's an error in ARC if a field has lifetime.
10273        // We don't want to report this in a system header, though,
10274        // so we just make the field unavailable.
10275        // FIXME: that's really not sufficient; we need to make the type
10276        // itself invalid to, say, initialize or copy.
10277        QualType T = FD->getType();
10278        Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10279        if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10280          SourceLocation loc = FD->getLocation();
10281          if (getSourceManager().isInSystemHeader(loc)) {
10282            if (!FD->hasAttr<UnavailableAttr>()) {
10283              FD->addAttr(new (Context) UnavailableAttr(loc, Context,
10284                                "this system field has retaining ownership"));
10285            }
10286          } else {
10287            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
10288              << T->isBlockPointerType();
10289          }
10290          ARCErrReported = true;
10291        }
10292      }
10293      else if (getLangOpts().ObjC1 &&
10294               getLangOpts().getGC() != LangOptions::NonGC &&
10295               Record && !Record->hasObjectMember()) {
10296        if (FD->getType()->isObjCObjectPointerType() ||
10297            FD->getType().isObjCGCStrong())
10298          Record->setHasObjectMember(true);
10299        else if (Context.getAsArrayType(FD->getType())) {
10300          QualType BaseType = Context.getBaseElementType(FD->getType());
10301          if (BaseType->isRecordType() &&
10302              BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10303            Record->setHasObjectMember(true);
10304          else if (BaseType->isObjCObjectPointerType() ||
10305                   BaseType.isObjCGCStrong())
10306                 Record->setHasObjectMember(true);
10307        }
10308      }
10309    }
10310    // Keep track of the number of named members.
10311    if (FD->getIdentifier())
10312      ++NumNamedMembers;
10313  }
10314
10315  // Okay, we successfully defined 'Record'.
10316  if (Record) {
10317    bool Completed = false;
10318    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10319      if (!CXXRecord->isInvalidDecl()) {
10320        // Set access bits correctly on the directly-declared conversions.
10321        for (CXXRecordDecl::conversion_iterator
10322               I = CXXRecord->conversion_begin(),
10323               E = CXXRecord->conversion_end(); I != E; ++I)
10324          I.setAccess((*I)->getAccess());
10325
10326        if (!CXXRecord->isDependentType()) {
10327          // Adjust user-defined destructor exception spec.
10328          if (getLangOpts().CPlusPlus11 &&
10329              CXXRecord->hasUserDeclaredDestructor())
10330            AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10331
10332          // Add any implicitly-declared members to this class.
10333          AddImplicitlyDeclaredMembersToClass(CXXRecord);
10334
10335          // If we have virtual base classes, we may end up finding multiple
10336          // final overriders for a given virtual function. Check for this
10337          // problem now.
10338          if (CXXRecord->getNumVBases()) {
10339            CXXFinalOverriderMap FinalOverriders;
10340            CXXRecord->getFinalOverriders(FinalOverriders);
10341
10342            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10343                                             MEnd = FinalOverriders.end();
10344                 M != MEnd; ++M) {
10345              for (OverridingMethods::iterator SO = M->second.begin(),
10346                                            SOEnd = M->second.end();
10347                   SO != SOEnd; ++SO) {
10348                assert(SO->second.size() > 0 &&
10349                       "Virtual function without overridding functions?");
10350                if (SO->second.size() == 1)
10351                  continue;
10352
10353                // C++ [class.virtual]p2:
10354                //   In a derived class, if a virtual member function of a base
10355                //   class subobject has more than one final overrider the
10356                //   program is ill-formed.
10357                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10358                  << (const NamedDecl *)M->first << Record;
10359                Diag(M->first->getLocation(),
10360                     diag::note_overridden_virtual_function);
10361                for (OverridingMethods::overriding_iterator
10362                          OM = SO->second.begin(),
10363                       OMEnd = SO->second.end();
10364                     OM != OMEnd; ++OM)
10365                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
10366                    << (const NamedDecl *)M->first << OM->Method->getParent();
10367
10368                Record->setInvalidDecl();
10369              }
10370            }
10371            CXXRecord->completeDefinition(&FinalOverriders);
10372            Completed = true;
10373          }
10374        }
10375      }
10376    }
10377
10378    if (!Completed)
10379      Record->completeDefinition();
10380
10381  } else {
10382    ObjCIvarDecl **ClsFields =
10383      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
10384    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
10385      ID->setEndOfDefinitionLoc(RBrac);
10386      // Add ivar's to class's DeclContext.
10387      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10388        ClsFields[i]->setLexicalDeclContext(ID);
10389        ID->addDecl(ClsFields[i]);
10390      }
10391      // Must enforce the rule that ivars in the base classes may not be
10392      // duplicates.
10393      if (ID->getSuperClass())
10394        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
10395    } else if (ObjCImplementationDecl *IMPDecl =
10396                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10397      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
10398      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10399        // Ivar declared in @implementation never belongs to the implementation.
10400        // Only it is in implementation's lexical context.
10401        ClsFields[I]->setLexicalDeclContext(IMPDecl);
10402      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
10403      IMPDecl->setIvarLBraceLoc(LBrac);
10404      IMPDecl->setIvarRBraceLoc(RBrac);
10405    } else if (ObjCCategoryDecl *CDecl =
10406                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10407      // case of ivars in class extension; all other cases have been
10408      // reported as errors elsewhere.
10409      // FIXME. Class extension does not have a LocEnd field.
10410      // CDecl->setLocEnd(RBrac);
10411      // Add ivar's to class extension's DeclContext.
10412      // Diagnose redeclaration of private ivars.
10413      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
10414      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10415        if (IDecl) {
10416          if (const ObjCIvarDecl *ClsIvar =
10417              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10418            Diag(ClsFields[i]->getLocation(),
10419                 diag::err_duplicate_ivar_declaration);
10420            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10421            continue;
10422          }
10423          for (const ObjCCategoryDecl *ClsExtDecl =
10424                IDecl->getFirstClassExtension();
10425               ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10426            if (const ObjCIvarDecl *ClsExtIvar =
10427                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10428              Diag(ClsFields[i]->getLocation(),
10429                   diag::err_duplicate_ivar_declaration);
10430              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10431              continue;
10432            }
10433          }
10434        }
10435        ClsFields[i]->setLexicalDeclContext(CDecl);
10436        CDecl->addDecl(ClsFields[i]);
10437      }
10438      CDecl->setIvarLBraceLoc(LBrac);
10439      CDecl->setIvarRBraceLoc(RBrac);
10440    }
10441  }
10442
10443  if (Attr)
10444    ProcessDeclAttributeList(S, Record, Attr);
10445}
10446
10447/// \brief Determine whether the given integral value is representable within
10448/// the given type T.
10449static bool isRepresentableIntegerValue(ASTContext &Context,
10450                                        llvm::APSInt &Value,
10451                                        QualType T) {
10452  assert(T->isIntegralType(Context) && "Integral type required!");
10453  unsigned BitWidth = Context.getIntWidth(T);
10454
10455  if (Value.isUnsigned() || Value.isNonNegative()) {
10456    if (T->isSignedIntegerOrEnumerationType())
10457      --BitWidth;
10458    return Value.getActiveBits() <= BitWidth;
10459  }
10460  return Value.getMinSignedBits() <= BitWidth;
10461}
10462
10463// \brief Given an integral type, return the next larger integral type
10464// (or a NULL type of no such type exists).
10465static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10466  // FIXME: Int128/UInt128 support, which also needs to be introduced into
10467  // enum checking below.
10468  assert(T->isIntegralType(Context) && "Integral type required!");
10469  const unsigned NumTypes = 4;
10470  QualType SignedIntegralTypes[NumTypes] = {
10471    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10472  };
10473  QualType UnsignedIntegralTypes[NumTypes] = {
10474    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10475    Context.UnsignedLongLongTy
10476  };
10477
10478  unsigned BitWidth = Context.getTypeSize(T);
10479  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10480                                                        : UnsignedIntegralTypes;
10481  for (unsigned I = 0; I != NumTypes; ++I)
10482    if (Context.getTypeSize(Types[I]) > BitWidth)
10483      return Types[I];
10484
10485  return QualType();
10486}
10487
10488EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10489                                          EnumConstantDecl *LastEnumConst,
10490                                          SourceLocation IdLoc,
10491                                          IdentifierInfo *Id,
10492                                          Expr *Val) {
10493  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10494  llvm::APSInt EnumVal(IntWidth);
10495  QualType EltTy;
10496
10497  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10498    Val = 0;
10499
10500  if (Val)
10501    Val = DefaultLvalueConversion(Val).take();
10502
10503  if (Val) {
10504    if (Enum->isDependentType() || Val->isTypeDependent())
10505      EltTy = Context.DependentTy;
10506    else {
10507      SourceLocation ExpLoc;
10508      if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
10509          !getLangOpts().MicrosoftMode) {
10510        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10511        // constant-expression in the enumerator-definition shall be a converted
10512        // constant expression of the underlying type.
10513        EltTy = Enum->getIntegerType();
10514        ExprResult Converted =
10515          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10516                                           CCEK_Enumerator);
10517        if (Converted.isInvalid())
10518          Val = 0;
10519        else
10520          Val = Converted.take();
10521      } else if (!Val->isValueDependent() &&
10522                 !(Val = VerifyIntegerConstantExpression(Val,
10523                                                         &EnumVal).take())) {
10524        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
10525      } else {
10526        if (Enum->isFixed()) {
10527          EltTy = Enum->getIntegerType();
10528
10529          // In Obj-C and Microsoft mode, require the enumeration value to be
10530          // representable in the underlying type of the enumeration. In C++11,
10531          // we perform a non-narrowing conversion as part of converted constant
10532          // expression checking.
10533          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10534            if (getLangOpts().MicrosoftMode) {
10535              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
10536              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10537            } else
10538              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
10539          } else
10540            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10541        } else if (getLangOpts().CPlusPlus) {
10542          // C++11 [dcl.enum]p5:
10543          //   If the underlying type is not fixed, the type of each enumerator
10544          //   is the type of its initializing value:
10545          //     - If an initializer is specified for an enumerator, the
10546          //       initializing value has the same type as the expression.
10547          EltTy = Val->getType();
10548        } else {
10549          // C99 6.7.2.2p2:
10550          //   The expression that defines the value of an enumeration constant
10551          //   shall be an integer constant expression that has a value
10552          //   representable as an int.
10553
10554          // Complain if the value is not representable in an int.
10555          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10556            Diag(IdLoc, diag::ext_enum_value_not_int)
10557              << EnumVal.toString(10) << Val->getSourceRange()
10558              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10559          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10560            // Force the type of the expression to 'int'.
10561            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10562          }
10563          EltTy = Val->getType();
10564        }
10565      }
10566    }
10567  }
10568
10569  if (!Val) {
10570    if (Enum->isDependentType())
10571      EltTy = Context.DependentTy;
10572    else if (!LastEnumConst) {
10573      // C++0x [dcl.enum]p5:
10574      //   If the underlying type is not fixed, the type of each enumerator
10575      //   is the type of its initializing value:
10576      //     - If no initializer is specified for the first enumerator, the
10577      //       initializing value has an unspecified integral type.
10578      //
10579      // GCC uses 'int' for its unspecified integral type, as does
10580      // C99 6.7.2.2p3.
10581      if (Enum->isFixed()) {
10582        EltTy = Enum->getIntegerType();
10583      }
10584      else {
10585        EltTy = Context.IntTy;
10586      }
10587    } else {
10588      // Assign the last value + 1.
10589      EnumVal = LastEnumConst->getInitVal();
10590      ++EnumVal;
10591      EltTy = LastEnumConst->getType();
10592
10593      // Check for overflow on increment.
10594      if (EnumVal < LastEnumConst->getInitVal()) {
10595        // C++0x [dcl.enum]p5:
10596        //   If the underlying type is not fixed, the type of each enumerator
10597        //   is the type of its initializing value:
10598        //
10599        //     - Otherwise the type of the initializing value is the same as
10600        //       the type of the initializing value of the preceding enumerator
10601        //       unless the incremented value is not representable in that type,
10602        //       in which case the type is an unspecified integral type
10603        //       sufficient to contain the incremented value. If no such type
10604        //       exists, the program is ill-formed.
10605        QualType T = getNextLargerIntegralType(Context, EltTy);
10606        if (T.isNull() || Enum->isFixed()) {
10607          // There is no integral type larger enough to represent this
10608          // value. Complain, then allow the value to wrap around.
10609          EnumVal = LastEnumConst->getInitVal();
10610          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10611          ++EnumVal;
10612          if (Enum->isFixed())
10613            // When the underlying type is fixed, this is ill-formed.
10614            Diag(IdLoc, diag::err_enumerator_wrapped)
10615              << EnumVal.toString(10)
10616              << EltTy;
10617          else
10618            Diag(IdLoc, diag::warn_enumerator_too_large)
10619              << EnumVal.toString(10);
10620        } else {
10621          EltTy = T;
10622        }
10623
10624        // Retrieve the last enumerator's value, extent that type to the
10625        // type that is supposed to be large enough to represent the incremented
10626        // value, then increment.
10627        EnumVal = LastEnumConst->getInitVal();
10628        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10629        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10630        ++EnumVal;
10631
10632        // If we're not in C++, diagnose the overflow of enumerator values,
10633        // which in C99 means that the enumerator value is not representable in
10634        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10635        // permits enumerator values that are representable in some larger
10636        // integral type.
10637        if (!getLangOpts().CPlusPlus && !T.isNull())
10638          Diag(IdLoc, diag::warn_enum_value_overflow);
10639      } else if (!getLangOpts().CPlusPlus &&
10640                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10641        // Enforce C99 6.7.2.2p2 even when we compute the next value.
10642        Diag(IdLoc, diag::ext_enum_value_not_int)
10643          << EnumVal.toString(10) << 1;
10644      }
10645    }
10646  }
10647
10648  if (!EltTy->isDependentType()) {
10649    // Make the enumerator value match the signedness and size of the
10650    // enumerator's type.
10651    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10652    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10653  }
10654
10655  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10656                                  Val, EnumVal);
10657}
10658
10659
10660Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10661                              SourceLocation IdLoc, IdentifierInfo *Id,
10662                              AttributeList *Attr,
10663                              SourceLocation EqualLoc, Expr *Val) {
10664  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10665  EnumConstantDecl *LastEnumConst =
10666    cast_or_null<EnumConstantDecl>(lastEnumConst);
10667
10668  // The scope passed in may not be a decl scope.  Zip up the scope tree until
10669  // we find one that is.
10670  S = getNonFieldDeclScope(S);
10671
10672  // Verify that there isn't already something declared with this name in this
10673  // scope.
10674  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10675                                         ForRedeclaration);
10676  if (PrevDecl && PrevDecl->isTemplateParameter()) {
10677    // Maybe we will complain about the shadowed template parameter.
10678    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10679    // Just pretend that we didn't see the previous declaration.
10680    PrevDecl = 0;
10681  }
10682
10683  if (PrevDecl) {
10684    // When in C++, we may get a TagDecl with the same name; in this case the
10685    // enum constant will 'hide' the tag.
10686    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10687           "Received TagDecl when not in C++!");
10688    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10689      if (isa<EnumConstantDecl>(PrevDecl))
10690        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10691      else
10692        Diag(IdLoc, diag::err_redefinition) << Id;
10693      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10694      return 0;
10695    }
10696  }
10697
10698  // C++ [class.mem]p15:
10699  // If T is the name of a class, then each of the following shall have a name
10700  // different from T:
10701  // - every enumerator of every member of class T that is an unscoped
10702  // enumerated type
10703  if (CXXRecordDecl *Record
10704                      = dyn_cast<CXXRecordDecl>(
10705                             TheEnumDecl->getDeclContext()->getRedeclContext()))
10706    if (!TheEnumDecl->isScoped() &&
10707        Record->getIdentifier() && Record->getIdentifier() == Id)
10708      Diag(IdLoc, diag::err_member_name_of_class) << Id;
10709
10710  EnumConstantDecl *New =
10711    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10712
10713  if (New) {
10714    // Process attributes.
10715    if (Attr) ProcessDeclAttributeList(S, New, Attr);
10716
10717    // Register this decl in the current scope stack.
10718    New->setAccess(TheEnumDecl->getAccess());
10719    PushOnScopeChains(New, S);
10720  }
10721
10722  ActOnDocumentableDecl(New);
10723
10724  return New;
10725}
10726
10727// Returns true when the enum initial expression does not trigger the
10728// duplicate enum warning.  A few common cases are exempted as follows:
10729// Element2 = Element1
10730// Element2 = Element1 + 1
10731// Element2 = Element1 - 1
10732// Where Element2 and Element1 are from the same enum.
10733static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
10734  Expr *InitExpr = ECD->getInitExpr();
10735  if (!InitExpr)
10736    return true;
10737  InitExpr = InitExpr->IgnoreImpCasts();
10738
10739  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
10740    if (!BO->isAdditiveOp())
10741      return true;
10742    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
10743    if (!IL)
10744      return true;
10745    if (IL->getValue() != 1)
10746      return true;
10747
10748    InitExpr = BO->getLHS();
10749  }
10750
10751  // This checks if the elements are from the same enum.
10752  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
10753  if (!DRE)
10754    return true;
10755
10756  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
10757  if (!EnumConstant)
10758    return true;
10759
10760  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
10761      Enum)
10762    return true;
10763
10764  return false;
10765}
10766
10767struct DupKey {
10768  int64_t val;
10769  bool isTombstoneOrEmptyKey;
10770  DupKey(int64_t val, bool isTombstoneOrEmptyKey)
10771    : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
10772};
10773
10774static DupKey GetDupKey(const llvm::APSInt& Val) {
10775  return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
10776                false);
10777}
10778
10779struct DenseMapInfoDupKey {
10780  static DupKey getEmptyKey() { return DupKey(0, true); }
10781  static DupKey getTombstoneKey() { return DupKey(1, true); }
10782  static unsigned getHashValue(const DupKey Key) {
10783    return (unsigned)(Key.val * 37);
10784  }
10785  static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
10786    return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
10787           LHS.val == RHS.val;
10788  }
10789};
10790
10791// Emits a warning when an element is implicitly set a value that
10792// a previous element has already been set to.
10793static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements,
10794                                        unsigned NumElements, EnumDecl *Enum,
10795                                        QualType EnumType) {
10796  if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
10797                                 Enum->getLocation()) ==
10798      DiagnosticsEngine::Ignored)
10799    return;
10800  // Avoid anonymous enums
10801  if (!Enum->getIdentifier())
10802    return;
10803
10804  // Only check for small enums.
10805  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
10806    return;
10807
10808  typedef llvm::SmallVector<EnumConstantDecl*, 3> ECDVector;
10809  typedef llvm::SmallVector<ECDVector*, 3> DuplicatesVector;
10810
10811  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
10812  typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
10813          ValueToVectorMap;
10814
10815  DuplicatesVector DupVector;
10816  ValueToVectorMap EnumMap;
10817
10818  // Populate the EnumMap with all values represented by enum constants without
10819  // an initialier.
10820  for (unsigned i = 0; i < NumElements; ++i) {
10821    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
10822
10823    // Null EnumConstantDecl means a previous diagnostic has been emitted for
10824    // this constant.  Skip this enum since it may be ill-formed.
10825    if (!ECD) {
10826      return;
10827    }
10828
10829    if (ECD->getInitExpr())
10830      continue;
10831
10832    DupKey Key = GetDupKey(ECD->getInitVal());
10833    DeclOrVector &Entry = EnumMap[Key];
10834
10835    // First time encountering this value.
10836    if (Entry.isNull())
10837      Entry = ECD;
10838  }
10839
10840  // Create vectors for any values that has duplicates.
10841  for (unsigned i = 0; i < NumElements; ++i) {
10842    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
10843    if (!ValidDuplicateEnum(ECD, Enum))
10844      continue;
10845
10846    DupKey Key = GetDupKey(ECD->getInitVal());
10847
10848    DeclOrVector& Entry = EnumMap[Key];
10849    if (Entry.isNull())
10850      continue;
10851
10852    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
10853      // Ensure constants are different.
10854      if (D == ECD)
10855        continue;
10856
10857      // Create new vector and push values onto it.
10858      ECDVector *Vec = new ECDVector();
10859      Vec->push_back(D);
10860      Vec->push_back(ECD);
10861
10862      // Update entry to point to the duplicates vector.
10863      Entry = Vec;
10864
10865      // Store the vector somewhere we can consult later for quick emission of
10866      // diagnostics.
10867      DupVector.push_back(Vec);
10868      continue;
10869    }
10870
10871    ECDVector *Vec = Entry.get<ECDVector*>();
10872    // Make sure constants are not added more than once.
10873    if (*Vec->begin() == ECD)
10874      continue;
10875
10876    Vec->push_back(ECD);
10877  }
10878
10879  // Emit diagnostics.
10880  for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
10881                                  DupVectorEnd = DupVector.end();
10882       DupVectorIter != DupVectorEnd; ++DupVectorIter) {
10883    ECDVector *Vec = *DupVectorIter;
10884    assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
10885
10886    // Emit warning for one enum constant.
10887    ECDVector::iterator I = Vec->begin();
10888    S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
10889      << (*I)->getName() << (*I)->getInitVal().toString(10)
10890      << (*I)->getSourceRange();
10891    ++I;
10892
10893    // Emit one note for each of the remaining enum constants with
10894    // the same value.
10895    for (ECDVector::iterator E = Vec->end(); I != E; ++I)
10896      S.Diag((*I)->getLocation(), diag::note_duplicate_element)
10897        << (*I)->getName() << (*I)->getInitVal().toString(10)
10898        << (*I)->getSourceRange();
10899    delete Vec;
10900  }
10901}
10902
10903void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10904                         SourceLocation RBraceLoc, Decl *EnumDeclX,
10905                         Decl **Elements, unsigned NumElements,
10906                         Scope *S, AttributeList *Attr) {
10907  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10908  QualType EnumType = Context.getTypeDeclType(Enum);
10909
10910  if (Attr)
10911    ProcessDeclAttributeList(S, Enum, Attr);
10912
10913  if (Enum->isDependentType()) {
10914    for (unsigned i = 0; i != NumElements; ++i) {
10915      EnumConstantDecl *ECD =
10916        cast_or_null<EnumConstantDecl>(Elements[i]);
10917      if (!ECD) continue;
10918
10919      ECD->setType(EnumType);
10920    }
10921
10922    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10923    return;
10924  }
10925
10926  // TODO: If the result value doesn't fit in an int, it must be a long or long
10927  // long value.  ISO C does not support this, but GCC does as an extension,
10928  // emit a warning.
10929  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10930  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10931  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10932
10933  // Verify that all the values are okay, compute the size of the values, and
10934  // reverse the list.
10935  unsigned NumNegativeBits = 0;
10936  unsigned NumPositiveBits = 0;
10937
10938  // Keep track of whether all elements have type int.
10939  bool AllElementsInt = true;
10940
10941  for (unsigned i = 0; i != NumElements; ++i) {
10942    EnumConstantDecl *ECD =
10943      cast_or_null<EnumConstantDecl>(Elements[i]);
10944    if (!ECD) continue;  // Already issued a diagnostic.
10945
10946    const llvm::APSInt &InitVal = ECD->getInitVal();
10947
10948    // Keep track of the size of positive and negative values.
10949    if (InitVal.isUnsigned() || InitVal.isNonNegative())
10950      NumPositiveBits = std::max(NumPositiveBits,
10951                                 (unsigned)InitVal.getActiveBits());
10952    else
10953      NumNegativeBits = std::max(NumNegativeBits,
10954                                 (unsigned)InitVal.getMinSignedBits());
10955
10956    // Keep track of whether every enum element has type int (very commmon).
10957    if (AllElementsInt)
10958      AllElementsInt = ECD->getType() == Context.IntTy;
10959  }
10960
10961  // Figure out the type that should be used for this enum.
10962  QualType BestType;
10963  unsigned BestWidth;
10964
10965  // C++0x N3000 [conv.prom]p3:
10966  //   An rvalue of an unscoped enumeration type whose underlying
10967  //   type is not fixed can be converted to an rvalue of the first
10968  //   of the following types that can represent all the values of
10969  //   the enumeration: int, unsigned int, long int, unsigned long
10970  //   int, long long int, or unsigned long long int.
10971  // C99 6.4.4.3p2:
10972  //   An identifier declared as an enumeration constant has type int.
10973  // The C99 rule is modified by a gcc extension
10974  QualType BestPromotionType;
10975
10976  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10977  // -fshort-enums is the equivalent to specifying the packed attribute on all
10978  // enum definitions.
10979  if (LangOpts.ShortEnums)
10980    Packed = true;
10981
10982  if (Enum->isFixed()) {
10983    BestType = Enum->getIntegerType();
10984    if (BestType->isPromotableIntegerType())
10985      BestPromotionType = Context.getPromotedIntegerType(BestType);
10986    else
10987      BestPromotionType = BestType;
10988    // We don't need to set BestWidth, because BestType is going to be the type
10989    // of the enumerators, but we do anyway because otherwise some compilers
10990    // warn that it might be used uninitialized.
10991    BestWidth = CharWidth;
10992  }
10993  else if (NumNegativeBits) {
10994    // If there is a negative value, figure out the smallest integer type (of
10995    // int/long/longlong) that fits.
10996    // If it's packed, check also if it fits a char or a short.
10997    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10998      BestType = Context.SignedCharTy;
10999      BestWidth = CharWidth;
11000    } else if (Packed && NumNegativeBits <= ShortWidth &&
11001               NumPositiveBits < ShortWidth) {
11002      BestType = Context.ShortTy;
11003      BestWidth = ShortWidth;
11004    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
11005      BestType = Context.IntTy;
11006      BestWidth = IntWidth;
11007    } else {
11008      BestWidth = Context.getTargetInfo().getLongWidth();
11009
11010      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
11011        BestType = Context.LongTy;
11012      } else {
11013        BestWidth = Context.getTargetInfo().getLongLongWidth();
11014
11015        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
11016          Diag(Enum->getLocation(), diag::warn_enum_too_large);
11017        BestType = Context.LongLongTy;
11018      }
11019    }
11020    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
11021  } else {
11022    // If there is no negative value, figure out the smallest type that fits
11023    // all of the enumerator values.
11024    // If it's packed, check also if it fits a char or a short.
11025    if (Packed && NumPositiveBits <= CharWidth) {
11026      BestType = Context.UnsignedCharTy;
11027      BestPromotionType = Context.IntTy;
11028      BestWidth = CharWidth;
11029    } else if (Packed && NumPositiveBits <= ShortWidth) {
11030      BestType = Context.UnsignedShortTy;
11031      BestPromotionType = Context.IntTy;
11032      BestWidth = ShortWidth;
11033    } else if (NumPositiveBits <= IntWidth) {
11034      BestType = Context.UnsignedIntTy;
11035      BestWidth = IntWidth;
11036      BestPromotionType
11037        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11038                           ? Context.UnsignedIntTy : Context.IntTy;
11039    } else if (NumPositiveBits <=
11040               (BestWidth = Context.getTargetInfo().getLongWidth())) {
11041      BestType = Context.UnsignedLongTy;
11042      BestPromotionType
11043        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11044                           ? Context.UnsignedLongTy : Context.LongTy;
11045    } else {
11046      BestWidth = Context.getTargetInfo().getLongLongWidth();
11047      assert(NumPositiveBits <= BestWidth &&
11048             "How could an initializer get larger than ULL?");
11049      BestType = Context.UnsignedLongLongTy;
11050      BestPromotionType
11051        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
11052                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
11053    }
11054  }
11055
11056  // Loop over all of the enumerator constants, changing their types to match
11057  // the type of the enum if needed.
11058  for (unsigned i = 0; i != NumElements; ++i) {
11059    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
11060    if (!ECD) continue;  // Already issued a diagnostic.
11061
11062    // Standard C says the enumerators have int type, but we allow, as an
11063    // extension, the enumerators to be larger than int size.  If each
11064    // enumerator value fits in an int, type it as an int, otherwise type it the
11065    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
11066    // that X has type 'int', not 'unsigned'.
11067
11068    // Determine whether the value fits into an int.
11069    llvm::APSInt InitVal = ECD->getInitVal();
11070
11071    // If it fits into an integer type, force it.  Otherwise force it to match
11072    // the enum decl type.
11073    QualType NewTy;
11074    unsigned NewWidth;
11075    bool NewSign;
11076    if (!getLangOpts().CPlusPlus &&
11077        !Enum->isFixed() &&
11078        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
11079      NewTy = Context.IntTy;
11080      NewWidth = IntWidth;
11081      NewSign = true;
11082    } else if (ECD->getType() == BestType) {
11083      // Already the right type!
11084      if (getLangOpts().CPlusPlus)
11085        // C++ [dcl.enum]p4: Following the closing brace of an
11086        // enum-specifier, each enumerator has the type of its
11087        // enumeration.
11088        ECD->setType(EnumType);
11089      continue;
11090    } else {
11091      NewTy = BestType;
11092      NewWidth = BestWidth;
11093      NewSign = BestType->isSignedIntegerOrEnumerationType();
11094    }
11095
11096    // Adjust the APSInt value.
11097    InitVal = InitVal.extOrTrunc(NewWidth);
11098    InitVal.setIsSigned(NewSign);
11099    ECD->setInitVal(InitVal);
11100
11101    // Adjust the Expr initializer and type.
11102    if (ECD->getInitExpr() &&
11103        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
11104      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
11105                                                CK_IntegralCast,
11106                                                ECD->getInitExpr(),
11107                                                /*base paths*/ 0,
11108                                                VK_RValue));
11109    if (getLangOpts().CPlusPlus)
11110      // C++ [dcl.enum]p4: Following the closing brace of an
11111      // enum-specifier, each enumerator has the type of its
11112      // enumeration.
11113      ECD->setType(EnumType);
11114    else
11115      ECD->setType(NewTy);
11116  }
11117
11118  Enum->completeDefinition(BestType, BestPromotionType,
11119                           NumPositiveBits, NumNegativeBits);
11120
11121  // If we're declaring a function, ensure this decl isn't forgotten about -
11122  // it needs to go into the function scope.
11123  if (InFunctionDeclarator)
11124    DeclsInPrototypeScope.push_back(Enum);
11125
11126  CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType);
11127}
11128
11129Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
11130                                  SourceLocation StartLoc,
11131                                  SourceLocation EndLoc) {
11132  StringLiteral *AsmString = cast<StringLiteral>(expr);
11133
11134  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
11135                                                   AsmString, StartLoc,
11136                                                   EndLoc);
11137  CurContext->addDecl(New);
11138  return New;
11139}
11140
11141DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
11142                                   SourceLocation ImportLoc,
11143                                   ModuleIdPath Path) {
11144  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
11145                                                Module::AllVisible,
11146                                                /*IsIncludeDirective=*/false);
11147  if (!Mod)
11148    return true;
11149
11150  llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
11151  Module *ModCheck = Mod;
11152  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
11153    // If we've run out of module parents, just drop the remaining identifiers.
11154    // We need the length to be consistent.
11155    if (!ModCheck)
11156      break;
11157    ModCheck = ModCheck->Parent;
11158
11159    IdentifierLocs.push_back(Path[I].second);
11160  }
11161
11162  ImportDecl *Import = ImportDecl::Create(Context,
11163                                          Context.getTranslationUnitDecl(),
11164                                          AtLoc.isValid()? AtLoc : ImportLoc,
11165                                          Mod, IdentifierLocs);
11166  Context.getTranslationUnitDecl()->addDecl(Import);
11167  return Import;
11168}
11169
11170void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
11171                                      IdentifierInfo* AliasName,
11172                                      SourceLocation PragmaLoc,
11173                                      SourceLocation NameLoc,
11174                                      SourceLocation AliasNameLoc) {
11175  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
11176                                    LookupOrdinaryName);
11177  AsmLabelAttr *Attr =
11178     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
11179
11180  if (PrevDecl)
11181    PrevDecl->addAttr(Attr);
11182  else
11183    (void)ExtnameUndeclaredIdentifiers.insert(
11184      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
11185}
11186
11187void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
11188                             SourceLocation PragmaLoc,
11189                             SourceLocation NameLoc) {
11190  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
11191
11192  if (PrevDecl) {
11193    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
11194  } else {
11195    (void)WeakUndeclaredIdentifiers.insert(
11196      std::pair<IdentifierInfo*,WeakInfo>
11197        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
11198  }
11199}
11200
11201void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
11202                                IdentifierInfo* AliasName,
11203                                SourceLocation PragmaLoc,
11204                                SourceLocation NameLoc,
11205                                SourceLocation AliasNameLoc) {
11206  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
11207                                    LookupOrdinaryName);
11208  WeakInfo W = WeakInfo(Name, NameLoc);
11209
11210  if (PrevDecl) {
11211    if (!PrevDecl->hasAttr<AliasAttr>())
11212      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
11213        DeclApplyPragmaWeak(TUScope, ND, W);
11214  } else {
11215    (void)WeakUndeclaredIdentifiers.insert(
11216      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
11217  }
11218}
11219
11220Decl *Sema::getObjCDeclContext() const {
11221  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
11222}
11223
11224AvailabilityResult Sema::getCurContextAvailability() const {
11225  const Decl *D = cast<Decl>(getCurObjCLexicalContext());
11226  return D->getAvailability();
11227}
11228