SemaDecl.cpp revision 9cda03ff7fc40b727d0cc44b1702dbae09d63f42
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 "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "TypeLocBuilder.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/DeclTemplate.h"
27#include "clang/AST/EvaluatedExprVisitor.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/CharUnits.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Parse/ParseDiagnostic.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Sema/DelayedDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/HeaderSearch.h"
41#include "clang/Lex/ModuleLoader.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) : AllowInvalidDecl(AllowInvalid) {
64    WantExpressionKeywords = false;
65    WantCXXNamedCasts = false;
66    WantRemainingKeywords = false;
67  }
68
69  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
70    if (NamedDecl *ND = candidate.getCorrectionDecl())
71      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
72          (AllowInvalidDecl || !ND->isInvalidDecl());
73    else
74      return candidate.isKeyword();
75  }
76
77 private:
78  bool AllowInvalidDecl;
79};
80
81}
82
83/// \brief If the identifier refers to a type name within this scope,
84/// return the declaration of that type.
85///
86/// This routine performs ordinary name lookup of the identifier II
87/// within the given scope, with optional C++ scope specifier SS, to
88/// determine whether the name refers to a type. If so, returns an
89/// opaque pointer (actually a QualType) corresponding to that
90/// type. Otherwise, returns NULL.
91///
92/// If name lookup results in an ambiguity, this routine will complain
93/// and then return NULL.
94ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95                             Scope *S, CXXScopeSpec *SS,
96                             bool isClassName, bool HasTrailingDot,
97                             ParsedType ObjectTypePtr,
98                             bool IsCtorOrDtorName,
99                             bool WantNontrivialTypeSourceInfo,
100                             IdentifierInfo **CorrectedII) {
101  // Determine where we will perform name lookup.
102  DeclContext *LookupCtx = 0;
103  if (ObjectTypePtr) {
104    QualType ObjectType = ObjectTypePtr.get();
105    if (ObjectType->isRecordType())
106      LookupCtx = computeDeclContext(ObjectType);
107  } else if (SS && SS->isNotEmpty()) {
108    LookupCtx = computeDeclContext(*SS, false);
109
110    if (!LookupCtx) {
111      if (isDependentScopeSpecifier(*SS)) {
112        // C++ [temp.res]p3:
113        //   A qualified-id that refers to a type and in which the
114        //   nested-name-specifier depends on a template-parameter (14.6.2)
115        //   shall be prefixed by the keyword typename to indicate that the
116        //   qualified-id denotes a type, forming an
117        //   elaborated-type-specifier (7.1.5.3).
118        //
119        // We therefore do not perform any name lookup if the result would
120        // refer to a member of an unknown specialization.
121        if (!isClassName)
122          return ParsedType();
123
124        // We know from the grammar that this name refers to a type,
125        // so build a dependent node to describe the type.
126        if (WantNontrivialTypeSourceInfo)
127          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
128
129        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
130        QualType T =
131          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
132                            II, NameLoc);
133
134          return ParsedType::make(T);
135      }
136
137      return ParsedType();
138    }
139
140    if (!LookupCtx->isDependentContext() &&
141        RequireCompleteDeclContext(*SS, LookupCtx))
142      return ParsedType();
143  }
144
145  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
146  // lookup for class-names.
147  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
148                                      LookupOrdinaryName;
149  LookupResult Result(*this, &II, NameLoc, Kind);
150  if (LookupCtx) {
151    // Perform "qualified" name lookup into the declaration context we
152    // computed, which is either the type of the base of a member access
153    // expression or the declaration context associated with a prior
154    // nested-name-specifier.
155    LookupQualifiedName(Result, LookupCtx);
156
157    if (ObjectTypePtr && Result.empty()) {
158      // C++ [basic.lookup.classref]p3:
159      //   If the unqualified-id is ~type-name, the type-name is looked up
160      //   in the context of the entire postfix-expression. If the type T of
161      //   the object expression is of a class type C, the type-name is also
162      //   looked up in the scope of class C. At least one of the lookups shall
163      //   find a name that refers to (possibly cv-qualified) T.
164      LookupName(Result, S);
165    }
166  } else {
167    // Perform unqualified name lookup.
168    LookupName(Result, S);
169  }
170
171  NamedDecl *IIDecl = 0;
172  switch (Result.getResultKind()) {
173  case LookupResult::NotFound:
174  case LookupResult::NotFoundInCurrentInstantiation:
175    if (CorrectedII) {
176      TypeNameValidatorCCC Validator(true);
177      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
178                                              Kind, S, SS, Validator);
179      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
180      TemplateTy Template;
181      bool MemberOfUnknownSpecialization;
182      UnqualifiedId TemplateName;
183      TemplateName.setIdentifier(NewII, NameLoc);
184      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
185      CXXScopeSpec NewSS, *NewSSPtr = SS;
186      if (SS && NNS) {
187        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
188        NewSSPtr = &NewSS;
189      }
190      if (Correction && (NNS || NewII != &II) &&
191          // Ignore a correction to a template type as the to-be-corrected
192          // identifier is not a template (typo correction for template names
193          // is handled elsewhere).
194          !(getLangOpts().CPlusPlus && NewSSPtr &&
195            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
196                           false, Template, MemberOfUnknownSpecialization))) {
197        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
198                                    isClassName, HasTrailingDot, ObjectTypePtr,
199                                    IsCtorOrDtorName,
200                                    WantNontrivialTypeSourceInfo);
201        if (Ty) {
202          std::string CorrectedStr(Correction.getAsString(getLangOpts()));
203          std::string CorrectedQuotedStr(
204              Correction.getQuoted(getLangOpts()));
205          Diag(NameLoc, diag::err_unknown_typename_suggest)
206              << Result.getLookupName() << CorrectedQuotedStr
207              << FixItHint::CreateReplacement(SourceRange(NameLoc),
208                                              CorrectedStr);
209          if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
210            Diag(FirstDecl->getLocation(), diag::note_previous_decl)
211              << CorrectedQuotedStr;
212
213          if (SS && NNS)
214            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
215          *CorrectedII = NewII;
216          return Ty;
217        }
218      }
219    }
220    // If typo correction failed or was not performed, fall through
221  case LookupResult::FoundOverloaded:
222  case LookupResult::FoundUnresolvedValue:
223    Result.suppressDiagnostics();
224    return ParsedType();
225
226  case LookupResult::Ambiguous:
227    // Recover from type-hiding ambiguities by hiding the type.  We'll
228    // do the lookup again when looking for an object, and we can
229    // diagnose the error then.  If we don't do this, then the error
230    // about hiding the type will be immediately followed by an error
231    // that only makes sense if the identifier was treated like a type.
232    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233      Result.suppressDiagnostics();
234      return ParsedType();
235    }
236
237    // Look to see if we have a type anywhere in the list of results.
238    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
239         Res != ResEnd; ++Res) {
240      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
241        if (!IIDecl ||
242            (*Res)->getLocation().getRawEncoding() <
243              IIDecl->getLocation().getRawEncoding())
244          IIDecl = *Res;
245      }
246    }
247
248    if (!IIDecl) {
249      // None of the entities we found is a type, so there is no way
250      // to even assume that the result is a type. In this case, don't
251      // complain about the ambiguity. The parser will either try to
252      // perform this lookup again (e.g., as an object name), which
253      // will produce the ambiguity, or will complain that it expected
254      // a type name.
255      Result.suppressDiagnostics();
256      return ParsedType();
257    }
258
259    // We found a type within the ambiguous lookup; diagnose the
260    // ambiguity and then return that type. This might be the right
261    // answer, or it might not be, but it suppresses any attempt to
262    // perform the name lookup again.
263    break;
264
265  case LookupResult::Found:
266    IIDecl = Result.getFoundDecl();
267    break;
268  }
269
270  assert(IIDecl && "Didn't find decl");
271
272  QualType T;
273  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
274    DiagnoseUseOfDecl(IIDecl, NameLoc);
275
276    if (T.isNull())
277      T = Context.getTypeDeclType(TD);
278
279    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
280    // constructor or destructor name (in such a case, the scope specifier
281    // will be attached to the enclosing Expr or Decl node).
282    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
283      if (WantNontrivialTypeSourceInfo) {
284        // Construct a type with type-source information.
285        TypeLocBuilder Builder;
286        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
287
288        T = getElaboratedType(ETK_None, *SS, T);
289        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
290        ElabTL.setElaboratedKeywordLoc(SourceLocation());
291        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
292        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
293      } else {
294        T = getElaboratedType(ETK_None, *SS, T);
295      }
296    }
297  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
298    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
299    if (!HasTrailingDot)
300      T = Context.getObjCInterfaceType(IDecl);
301  }
302
303  if (T.isNull()) {
304    // If it's not plausibly a type, suppress diagnostics.
305    Result.suppressDiagnostics();
306    return ParsedType();
307  }
308  return ParsedType::make(T);
309}
310
311/// isTagName() - This method is called *for error recovery purposes only*
312/// to determine if the specified name is a valid tag name ("struct foo").  If
313/// so, this returns the TST for the tag corresponding to it (TST_enum,
314/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
315/// where the user forgot to specify the tag.
316DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
317  // Do a tag name lookup in this scope.
318  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
319  LookupName(R, S, false);
320  R.suppressDiagnostics();
321  if (R.getResultKind() == LookupResult::Found)
322    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
323      switch (TD->getTagKind()) {
324      case TTK_Struct: return DeclSpec::TST_struct;
325      case TTK_Union:  return DeclSpec::TST_union;
326      case TTK_Class:  return DeclSpec::TST_class;
327      case TTK_Enum:   return DeclSpec::TST_enum;
328      }
329    }
330
331  return DeclSpec::TST_unspecified;
332}
333
334/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
335/// if a CXXScopeSpec's type is equal to the type of one of the base classes
336/// then downgrade the missing typename error to a warning.
337/// This is needed for MSVC compatibility; Example:
338/// @code
339/// template<class T> class A {
340/// public:
341///   typedef int TYPE;
342/// };
343/// template<class T> class B : public A<T> {
344/// public:
345///   A<T>::TYPE a; // no typename required because A<T> is a base class.
346/// };
347/// @endcode
348bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
349  if (CurContext->isRecord()) {
350    const Type *Ty = SS->getScopeRep()->getAsType();
351
352    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
353    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
354          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
355      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
356        return true;
357    return S->isFunctionPrototypeScope();
358  }
359  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
360}
361
362bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
363                                   SourceLocation IILoc,
364                                   Scope *S,
365                                   CXXScopeSpec *SS,
366                                   ParsedType &SuggestedType) {
367  // We don't have anything to suggest (yet).
368  SuggestedType = ParsedType();
369
370  // There may have been a typo in the name of the type. Look up typo
371  // results, in case we have something that we can suggest.
372  TypeNameValidatorCCC Validator(false);
373  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
374                                             LookupOrdinaryName, S, SS,
375                                             Validator)) {
376    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
378
379    if (Corrected.isKeyword()) {
380      // We corrected to a keyword.
381      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
382      Diag(IILoc, diag::err_unknown_typename_suggest)
383        << &II << CorrectedQuotedStr;
384    } else {
385      NamedDecl *Result = Corrected.getCorrectionDecl();
386      // We found a similarly-named type or interface; suggest that.
387      if (!SS || !SS->isSet())
388        Diag(IILoc, diag::err_unknown_typename_suggest)
389          << &II << CorrectedQuotedStr
390          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
391      else if (DeclContext *DC = computeDeclContext(*SS, false))
392        Diag(IILoc, diag::err_unknown_nested_typename_suggest)
393          << &II << DC << CorrectedQuotedStr << SS->getRange()
394          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
395      else
396        llvm_unreachable("could not have corrected a typo here");
397
398      Diag(Result->getLocation(), diag::note_previous_decl)
399        << CorrectedQuotedStr;
400
401      SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
402                                  false, false, ParsedType(),
403                                  /*IsCtorOrDtorName=*/false,
404                                  /*NonTrivialTypeSourceInfo=*/true);
405    }
406    return true;
407  }
408
409  if (getLangOpts().CPlusPlus) {
410    // See if II is a class template that the user forgot to pass arguments to.
411    UnqualifiedId Name;
412    Name.setIdentifier(&II, IILoc);
413    CXXScopeSpec EmptySS;
414    TemplateTy TemplateResult;
415    bool MemberOfUnknownSpecialization;
416    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
417                       Name, ParsedType(), true, TemplateResult,
418                       MemberOfUnknownSpecialization) == TNK_Type_template) {
419      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
420      Diag(IILoc, diag::err_template_missing_args) << TplName;
421      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
422        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
423          << TplDecl->getTemplateParameters()->getSourceRange();
424      }
425      return true;
426    }
427  }
428
429  // FIXME: Should we move the logic that tries to recover from a missing tag
430  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
431
432  if (!SS || (!SS->isSet() && !SS->isInvalid()))
433    Diag(IILoc, diag::err_unknown_typename) << &II;
434  else if (DeclContext *DC = computeDeclContext(*SS, false))
435    Diag(IILoc, diag::err_typename_nested_not_found)
436      << &II << DC << SS->getRange();
437  else if (isDependentScopeSpecifier(*SS)) {
438    unsigned DiagID = diag::err_typename_missing;
439    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
440      DiagID = diag::warn_typename_missing;
441
442    Diag(SS->getRange().getBegin(), DiagID)
443      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
444      << SourceRange(SS->getRange().getBegin(), IILoc)
445      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
446    SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
447                                                                         .get();
448  } else {
449    assert(SS && SS->isInvalid() &&
450           "Invalid scope specifier has already been diagnosed");
451  }
452
453  return true;
454}
455
456/// \brief Determine whether the given result set contains either a type name
457/// or
458static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
459  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
460                       NextToken.is(tok::less);
461
462  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
463    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
464      return true;
465
466    if (CheckTemplate && isa<TemplateDecl>(*I))
467      return true;
468  }
469
470  return false;
471}
472
473Sema::NameClassification Sema::ClassifyName(Scope *S,
474                                            CXXScopeSpec &SS,
475                                            IdentifierInfo *&Name,
476                                            SourceLocation NameLoc,
477                                            const Token &NextToken) {
478  DeclarationNameInfo NameInfo(Name, NameLoc);
479  ObjCMethodDecl *CurMethod = getCurMethodDecl();
480
481  if (NextToken.is(tok::coloncolon)) {
482    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
483                                QualType(), false, SS, 0, false);
484
485  }
486
487  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
488  LookupParsedName(Result, S, &SS, !CurMethod);
489
490  // Perform lookup for Objective-C instance variables (including automatically
491  // synthesized instance variables), if we're in an Objective-C method.
492  // FIXME: This lookup really, really needs to be folded in to the normal
493  // unqualified lookup mechanism.
494  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
495    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
496    if (E.get() || E.isInvalid())
497      return E;
498  }
499
500  bool SecondTry = false;
501  bool IsFilteredTemplateName = false;
502
503Corrected:
504  switch (Result.getResultKind()) {
505  case LookupResult::NotFound:
506    // If an unqualified-id is followed by a '(', then we have a function
507    // call.
508    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
509      // In C++, this is an ADL-only call.
510      // FIXME: Reference?
511      if (getLangOpts().CPlusPlus)
512        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
513
514      // C90 6.3.2.2:
515      //   If the expression that precedes the parenthesized argument list in a
516      //   function call consists solely of an identifier, and if no
517      //   declaration is visible for this identifier, the identifier is
518      //   implicitly declared exactly as if, in the innermost block containing
519      //   the function call, the declaration
520      //
521      //     extern int identifier ();
522      //
523      //   appeared.
524      //
525      // We also allow this in C99 as an extension.
526      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
527        Result.addDecl(D);
528        Result.resolveKind();
529        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
530      }
531    }
532
533    // In C, we first see whether there is a tag type by the same name, in
534    // which case it's likely that the user just forget to write "enum",
535    // "struct", or "union".
536    if (!getLangOpts().CPlusPlus && !SecondTry) {
537      Result.clear(LookupTagName);
538      LookupParsedName(Result, S, &SS);
539      if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
540        const char *TagName = 0;
541        const char *FixItTagName = 0;
542        switch (Tag->getTagKind()) {
543          case TTK_Class:
544            TagName = "class";
545            FixItTagName = "class ";
546            break;
547
548          case TTK_Enum:
549            TagName = "enum";
550            FixItTagName = "enum ";
551            break;
552
553          case TTK_Struct:
554            TagName = "struct";
555            FixItTagName = "struct ";
556            break;
557
558          case TTK_Union:
559            TagName = "union";
560            FixItTagName = "union ";
561            break;
562        }
563
564        Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
565          << Name << TagName << getLangOpts().CPlusPlus
566          << FixItHint::CreateInsertion(NameLoc, FixItTagName);
567        break;
568      }
569
570      Result.clear(LookupOrdinaryName);
571    }
572
573    // Perform typo correction to determine if there is another name that is
574    // close to this name.
575    if (!SecondTry) {
576      SecondTry = true;
577      CorrectionCandidateCallback DefaultValidator;
578      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
579                                                 Result.getLookupKind(), S,
580                                                 &SS, DefaultValidator)) {
581        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
582        unsigned QualifiedDiag = diag::err_no_member_suggest;
583        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
585
586        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
587        NamedDecl *UnderlyingFirstDecl
588          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
589        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
590            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
591          UnqualifiedDiag = diag::err_no_template_suggest;
592          QualifiedDiag = diag::err_no_member_template_suggest;
593        } else if (UnderlyingFirstDecl &&
594                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
595                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
596                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
597           UnqualifiedDiag = diag::err_unknown_typename_suggest;
598           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
599         }
600
601        if (SS.isEmpty())
602          Diag(NameLoc, UnqualifiedDiag)
603            << Name << CorrectedQuotedStr
604            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
605        else
606          Diag(NameLoc, QualifiedDiag)
607            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
608            << SS.getRange()
609            << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
610
611        // Update the name, so that the caller has the new name.
612        Name = Corrected.getCorrectionAsIdentifierInfo();
613
614        // Typo correction corrected to a keyword.
615        if (Corrected.isKeyword())
616          return Corrected.getCorrectionAsIdentifierInfo();
617
618        // Also update the LookupResult...
619        // FIXME: This should probably go away at some point
620        Result.clear();
621        Result.setLookupName(Corrected.getCorrection());
622        if (FirstDecl) {
623          Result.addDecl(FirstDecl);
624          Diag(FirstDecl->getLocation(), diag::note_previous_decl)
625            << CorrectedQuotedStr;
626        }
627
628        // If we found an Objective-C instance variable, let
629        // LookupInObjCMethod build the appropriate expression to
630        // reference the ivar.
631        // FIXME: This is a gross hack.
632        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
633          Result.clear();
634          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
635          return move(E);
636        }
637
638        goto Corrected;
639      }
640    }
641
642    // We failed to correct; just fall through and let the parser deal with it.
643    Result.suppressDiagnostics();
644    return NameClassification::Unknown();
645
646  case LookupResult::NotFoundInCurrentInstantiation: {
647    // We performed name lookup into the current instantiation, and there were
648    // dependent bases, so we treat this result the same way as any other
649    // dependent nested-name-specifier.
650
651    // C++ [temp.res]p2:
652    //   A name used in a template declaration or definition and that is
653    //   dependent on a template-parameter is assumed not to name a type
654    //   unless the applicable name lookup finds a type name or the name is
655    //   qualified by the keyword typename.
656    //
657    // FIXME: If the next token is '<', we might want to ask the parser to
658    // perform some heroics to see if we actually have a
659    // template-argument-list, which would indicate a missing 'template'
660    // keyword here.
661    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
662                                     NameInfo, /*TemplateArgs=*/0);
663  }
664
665  case LookupResult::Found:
666  case LookupResult::FoundOverloaded:
667  case LookupResult::FoundUnresolvedValue:
668    break;
669
670  case LookupResult::Ambiguous:
671    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672        hasAnyAcceptableTemplateNames(Result)) {
673      // C++ [temp.local]p3:
674      //   A lookup that finds an injected-class-name (10.2) can result in an
675      //   ambiguity in certain cases (for example, if it is found in more than
676      //   one base class). If all of the injected-class-names that are found
677      //   refer to specializations of the same class template, and if the name
678      //   is followed by a template-argument-list, the reference refers to the
679      //   class template itself and not a specialization thereof, and is not
680      //   ambiguous.
681      //
682      // This filtering can make an ambiguous result into an unambiguous one,
683      // so try again after filtering out template names.
684      FilterAcceptableTemplateNames(Result);
685      if (!Result.isAmbiguous()) {
686        IsFilteredTemplateName = true;
687        break;
688      }
689    }
690
691    // Diagnose the ambiguity and return an error.
692    return NameClassification::Error();
693  }
694
695  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
696      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
697    // C++ [temp.names]p3:
698    //   After name lookup (3.4) finds that a name is a template-name or that
699    //   an operator-function-id or a literal- operator-id refers to a set of
700    //   overloaded functions any member of which is a function template if
701    //   this is followed by a <, the < is always taken as the delimiter of a
702    //   template-argument-list and never as the less-than operator.
703    if (!IsFilteredTemplateName)
704      FilterAcceptableTemplateNames(Result);
705
706    if (!Result.empty()) {
707      bool IsFunctionTemplate;
708      TemplateName Template;
709      if (Result.end() - Result.begin() > 1) {
710        IsFunctionTemplate = true;
711        Template = Context.getOverloadedTemplateName(Result.begin(),
712                                                     Result.end());
713      } else {
714        TemplateDecl *TD
715          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
716        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
717
718        if (SS.isSet() && !SS.isInvalid())
719          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
720                                                    /*TemplateKeyword=*/false,
721                                                      TD);
722        else
723          Template = TemplateName(TD);
724      }
725
726      if (IsFunctionTemplate) {
727        // Function templates always go through overload resolution, at which
728        // point we'll perform the various checks (e.g., accessibility) we need
729        // to based on which function we selected.
730        Result.suppressDiagnostics();
731
732        return NameClassification::FunctionTemplate(Template);
733      }
734
735      return NameClassification::TypeTemplate(Template);
736    }
737  }
738
739  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
740  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
741    DiagnoseUseOfDecl(Type, NameLoc);
742    QualType T = Context.getTypeDeclType(Type);
743    return ParsedType::make(T);
744  }
745
746  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
747  if (!Class) {
748    // FIXME: It's unfortunate that we don't have a Type node for handling this.
749    if (ObjCCompatibleAliasDecl *Alias
750                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
751      Class = Alias->getClassInterface();
752  }
753
754  if (Class) {
755    DiagnoseUseOfDecl(Class, NameLoc);
756
757    if (NextToken.is(tok::period)) {
758      // Interface. <something> is parsed as a property reference expression.
759      // Just return "unknown" as a fall-through for now.
760      Result.suppressDiagnostics();
761      return NameClassification::Unknown();
762    }
763
764    QualType T = Context.getObjCInterfaceType(Class);
765    return ParsedType::make(T);
766  }
767
768  if (!Result.empty() && (*Result.begin())->isCXXClassMember())
769    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
770
771  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
772  return BuildDeclarationNameExpr(SS, Result, ADL);
773}
774
775// Determines the context to return to after temporarily entering a
776// context.  This depends in an unnecessarily complicated way on the
777// exact ordering of callbacks from the parser.
778DeclContext *Sema::getContainingDC(DeclContext *DC) {
779
780  // Functions defined inline within classes aren't parsed until we've
781  // finished parsing the top-level class, so the top-level class is
782  // the context we'll need to return to.
783  if (isa<FunctionDecl>(DC)) {
784    DC = DC->getLexicalParent();
785
786    // A function not defined within a class will always return to its
787    // lexical context.
788    if (!isa<CXXRecordDecl>(DC))
789      return DC;
790
791    // A C++ inline method/friend is parsed *after* the topmost class
792    // it was declared in is fully parsed ("complete");  the topmost
793    // class is the context we need to return to.
794    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
795      DC = RD;
796
797    // Return the declaration context of the topmost class the inline method is
798    // declared in.
799    return DC;
800  }
801
802  return DC->getLexicalParent();
803}
804
805void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
806  assert(getContainingDC(DC) == CurContext &&
807      "The next DeclContext should be lexically contained in the current one.");
808  CurContext = DC;
809  S->setEntity(DC);
810}
811
812void Sema::PopDeclContext() {
813  assert(CurContext && "DeclContext imbalance!");
814
815  CurContext = getContainingDC(CurContext);
816  assert(CurContext && "Popped translation unit!");
817}
818
819/// EnterDeclaratorContext - Used when we must lookup names in the context
820/// of a declarator's nested name specifier.
821///
822void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
823  // C++0x [basic.lookup.unqual]p13:
824  //   A name used in the definition of a static data member of class
825  //   X (after the qualified-id of the static member) is looked up as
826  //   if the name was used in a member function of X.
827  // C++0x [basic.lookup.unqual]p14:
828  //   If a variable member of a namespace is defined outside of the
829  //   scope of its namespace then any name used in the definition of
830  //   the variable member (after the declarator-id) is looked up as
831  //   if the definition of the variable member occurred in its
832  //   namespace.
833  // Both of these imply that we should push a scope whose context
834  // is the semantic context of the declaration.  We can't use
835  // PushDeclContext here because that context is not necessarily
836  // lexically contained in the current context.  Fortunately,
837  // the containing scope should have the appropriate information.
838
839  assert(!S->getEntity() && "scope already has entity");
840
841#ifndef NDEBUG
842  Scope *Ancestor = S->getParent();
843  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
844  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
845#endif
846
847  CurContext = DC;
848  S->setEntity(DC);
849}
850
851void Sema::ExitDeclaratorContext(Scope *S) {
852  assert(S->getEntity() == CurContext && "Context imbalance!");
853
854  // Switch back to the lexical context.  The safety of this is
855  // enforced by an assert in EnterDeclaratorContext.
856  Scope *Ancestor = S->getParent();
857  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
858  CurContext = (DeclContext*) Ancestor->getEntity();
859
860  // We don't need to do anything with the scope, which is going to
861  // disappear.
862}
863
864
865void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
866  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
867  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
868    // We assume that the caller has already called
869    // ActOnReenterTemplateScope
870    FD = TFD->getTemplatedDecl();
871  }
872  if (!FD)
873    return;
874
875  PushDeclContext(S, FD);
876  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
877    ParmVarDecl *Param = FD->getParamDecl(P);
878    // If the parameter has an identifier, then add it to the scope
879    if (Param->getIdentifier()) {
880      S->AddDecl(Param);
881      IdResolver.AddDecl(Param);
882    }
883  }
884}
885
886
887/// \brief Determine whether we allow overloading of the function
888/// PrevDecl with another declaration.
889///
890/// This routine determines whether overloading is possible, not
891/// whether some new function is actually an overload. It will return
892/// true in C++ (where we can always provide overloads) or, as an
893/// extension, in C when the previous function is already an
894/// overloaded function declaration or has the "overloadable"
895/// attribute.
896static bool AllowOverloadingOfFunction(LookupResult &Previous,
897                                       ASTContext &Context) {
898  if (Context.getLangOpts().CPlusPlus)
899    return true;
900
901  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
902    return true;
903
904  return (Previous.getResultKind() == LookupResult::Found
905          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
906}
907
908/// Add this decl to the scope shadowed decl chains.
909void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
910  // Move up the scope chain until we find the nearest enclosing
911  // non-transparent context. The declaration will be introduced into this
912  // scope.
913  while (S->getEntity() &&
914         ((DeclContext *)S->getEntity())->isTransparentContext())
915    S = S->getParent();
916
917  // Add scoped declarations into their context, so that they can be
918  // found later. Declarations without a context won't be inserted
919  // into any context.
920  if (AddToContext)
921    CurContext->addDecl(D);
922
923  // Out-of-line definitions shouldn't be pushed into scope in C++.
924  // Out-of-line variable and function definitions shouldn't even in C.
925  if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
926      D->isOutOfLine() &&
927      !D->getDeclContext()->getRedeclContext()->Equals(
928        D->getLexicalDeclContext()->getRedeclContext()))
929    return;
930
931  // Template instantiations should also not be pushed into scope.
932  if (isa<FunctionDecl>(D) &&
933      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
934    return;
935
936  // If this replaces anything in the current scope,
937  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
938                               IEnd = IdResolver.end();
939  for (; I != IEnd; ++I) {
940    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
941      S->RemoveDecl(*I);
942      IdResolver.RemoveDecl(*I);
943
944      // Should only need to replace one decl.
945      break;
946    }
947  }
948
949  S->AddDecl(D);
950
951  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
952    // Implicitly-generated labels may end up getting generated in an order that
953    // isn't strictly lexical, which breaks name lookup. Be careful to insert
954    // the label at the appropriate place in the identifier chain.
955    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
956      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
957      if (IDC == CurContext) {
958        if (!S->isDeclScope(*I))
959          continue;
960      } else if (IDC->Encloses(CurContext))
961        break;
962    }
963
964    IdResolver.InsertDeclAfter(I, D);
965  } else {
966    IdResolver.AddDecl(D);
967  }
968}
969
970void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
971  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
972    TUScope->AddDecl(D);
973}
974
975bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
976                         bool ExplicitInstantiationOrSpecialization) {
977  return IdResolver.isDeclInScope(D, Ctx, Context, S,
978                                  ExplicitInstantiationOrSpecialization);
979}
980
981Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
982  DeclContext *TargetDC = DC->getPrimaryContext();
983  do {
984    if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
985      if (ScopeDC->getPrimaryContext() == TargetDC)
986        return S;
987  } while ((S = S->getParent()));
988
989  return 0;
990}
991
992static bool isOutOfScopePreviousDeclaration(NamedDecl *,
993                                            DeclContext*,
994                                            ASTContext&);
995
996/// Filters out lookup results that don't fall within the given scope
997/// as determined by isDeclInScope.
998void Sema::FilterLookupForScope(LookupResult &R,
999                                DeclContext *Ctx, Scope *S,
1000                                bool ConsiderLinkage,
1001                                bool ExplicitInstantiationOrSpecialization) {
1002  LookupResult::Filter F = R.makeFilter();
1003  while (F.hasNext()) {
1004    NamedDecl *D = F.next();
1005
1006    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1007      continue;
1008
1009    if (ConsiderLinkage &&
1010        isOutOfScopePreviousDeclaration(D, Ctx, Context))
1011      continue;
1012
1013    F.erase();
1014  }
1015
1016  F.done();
1017}
1018
1019static bool isUsingDecl(NamedDecl *D) {
1020  return isa<UsingShadowDecl>(D) ||
1021         isa<UnresolvedUsingTypenameDecl>(D) ||
1022         isa<UnresolvedUsingValueDecl>(D);
1023}
1024
1025/// Removes using shadow declarations from the lookup results.
1026static void RemoveUsingDecls(LookupResult &R) {
1027  LookupResult::Filter F = R.makeFilter();
1028  while (F.hasNext())
1029    if (isUsingDecl(F.next()))
1030      F.erase();
1031
1032  F.done();
1033}
1034
1035/// \brief Check for this common pattern:
1036/// @code
1037/// class S {
1038///   S(const S&); // DO NOT IMPLEMENT
1039///   void operator=(const S&); // DO NOT IMPLEMENT
1040/// };
1041/// @endcode
1042static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1043  // FIXME: Should check for private access too but access is set after we get
1044  // the decl here.
1045  if (D->doesThisDeclarationHaveABody())
1046    return false;
1047
1048  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1049    return CD->isCopyConstructor();
1050  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1051    return Method->isCopyAssignmentOperator();
1052  return false;
1053}
1054
1055bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1056  assert(D);
1057
1058  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1059    return false;
1060
1061  // Ignore class templates.
1062  if (D->getDeclContext()->isDependentContext() ||
1063      D->getLexicalDeclContext()->isDependentContext())
1064    return false;
1065
1066  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1067    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1068      return false;
1069
1070    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1071      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1072        return false;
1073    } else {
1074      // 'static inline' functions are used in headers; don't warn.
1075      if (FD->getStorageClass() == SC_Static &&
1076          FD->isInlineSpecified())
1077        return false;
1078    }
1079
1080    if (FD->doesThisDeclarationHaveABody() &&
1081        Context.DeclMustBeEmitted(FD))
1082      return false;
1083  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1084    if (!VD->isFileVarDecl() ||
1085        VD->getType().isConstant(Context) ||
1086        Context.DeclMustBeEmitted(VD))
1087      return false;
1088
1089    if (VD->isStaticDataMember() &&
1090        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1091      return false;
1092
1093  } else {
1094    return false;
1095  }
1096
1097  // Only warn for unused decls internal to the translation unit.
1098  if (D->getLinkage() == ExternalLinkage)
1099    return false;
1100
1101  return true;
1102}
1103
1104void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1105  if (!D)
1106    return;
1107
1108  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1109    const FunctionDecl *First = FD->getFirstDeclaration();
1110    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1111      return; // First should already be in the vector.
1112  }
1113
1114  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1115    const VarDecl *First = VD->getFirstDeclaration();
1116    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1117      return; // First should already be in the vector.
1118  }
1119
1120   if (ShouldWarnIfUnusedFileScopedDecl(D))
1121     UnusedFileScopedDecls.push_back(D);
1122 }
1123
1124static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1125  if (D->isInvalidDecl())
1126    return false;
1127
1128  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1129    return false;
1130
1131  if (isa<LabelDecl>(D))
1132    return true;
1133
1134  // White-list anything that isn't a local variable.
1135  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1136      !D->getDeclContext()->isFunctionOrMethod())
1137    return false;
1138
1139  // Types of valid local variables should be complete, so this should succeed.
1140  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1141
1142    // White-list anything with an __attribute__((unused)) type.
1143    QualType Ty = VD->getType();
1144
1145    // Only look at the outermost level of typedef.
1146    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1147      if (TT->getDecl()->hasAttr<UnusedAttr>())
1148        return false;
1149    }
1150
1151    // If we failed to complete the type for some reason, or if the type is
1152    // dependent, don't diagnose the variable.
1153    if (Ty->isIncompleteType() || Ty->isDependentType())
1154      return false;
1155
1156    if (const TagType *TT = Ty->getAs<TagType>()) {
1157      const TagDecl *Tag = TT->getDecl();
1158      if (Tag->hasAttr<UnusedAttr>())
1159        return false;
1160
1161      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1162        if (!RD->hasTrivialDestructor())
1163          return false;
1164
1165        if (const Expr *Init = VD->getInit()) {
1166          const CXXConstructExpr *Construct =
1167            dyn_cast<CXXConstructExpr>(Init);
1168          if (Construct && !Construct->isElidable()) {
1169            CXXConstructorDecl *CD = Construct->getConstructor();
1170            if (!CD->isTrivial())
1171              return false;
1172          }
1173        }
1174      }
1175    }
1176
1177    // TODO: __attribute__((unused)) templates?
1178  }
1179
1180  return true;
1181}
1182
1183static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1184                                     FixItHint &Hint) {
1185  if (isa<LabelDecl>(D)) {
1186    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1187                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1188    if (AfterColon.isInvalid())
1189      return;
1190    Hint = FixItHint::CreateRemoval(CharSourceRange::
1191                                    getCharRange(D->getLocStart(), AfterColon));
1192  }
1193  return;
1194}
1195
1196/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1197/// unless they are marked attr(unused).
1198void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1199  FixItHint Hint;
1200  if (!ShouldDiagnoseUnusedDecl(D))
1201    return;
1202
1203  GenerateFixForUnusedDecl(D, Context, Hint);
1204
1205  unsigned DiagID;
1206  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1207    DiagID = diag::warn_unused_exception_param;
1208  else if (isa<LabelDecl>(D))
1209    DiagID = diag::warn_unused_label;
1210  else
1211    DiagID = diag::warn_unused_variable;
1212
1213  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1214}
1215
1216static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1217  // Verify that we have no forward references left.  If so, there was a goto
1218  // or address of a label taken, but no definition of it.  Label fwd
1219  // definitions are indicated with a null substmt.
1220  if (L->getStmt() == 0)
1221    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1222}
1223
1224void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1225  if (S->decl_empty()) return;
1226  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1227         "Scope shouldn't contain decls!");
1228
1229  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1230       I != E; ++I) {
1231    Decl *TmpD = (*I);
1232    assert(TmpD && "This decl didn't get pushed??");
1233
1234    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1235    NamedDecl *D = cast<NamedDecl>(TmpD);
1236
1237    if (!D->getDeclName()) continue;
1238
1239    // Diagnose unused variables in this scope.
1240    if (!S->hasErrorOccurred())
1241      DiagnoseUnusedDecl(D);
1242
1243    // If this was a forward reference to a label, verify it was defined.
1244    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1245      CheckPoppedLabel(LD, *this);
1246
1247    // Remove this name from our lexical scope.
1248    IdResolver.RemoveDecl(D);
1249  }
1250}
1251
1252void Sema::ActOnStartFunctionDeclarator() {
1253  ++InFunctionDeclarator;
1254}
1255
1256void Sema::ActOnEndFunctionDeclarator() {
1257  assert(InFunctionDeclarator);
1258  --InFunctionDeclarator;
1259}
1260
1261/// \brief Look for an Objective-C class in the translation unit.
1262///
1263/// \param Id The name of the Objective-C class we're looking for. If
1264/// typo-correction fixes this name, the Id will be updated
1265/// to the fixed name.
1266///
1267/// \param IdLoc The location of the name in the translation unit.
1268///
1269/// \param TypoCorrection If true, this routine will attempt typo correction
1270/// if there is no class with the given name.
1271///
1272/// \returns The declaration of the named Objective-C class, or NULL if the
1273/// class could not be found.
1274ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1275                                              SourceLocation IdLoc,
1276                                              bool DoTypoCorrection) {
1277  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1278  // creation from this context.
1279  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1280
1281  if (!IDecl && DoTypoCorrection) {
1282    // Perform typo correction at the given location, but only if we
1283    // find an Objective-C class name.
1284    DeclFilterCCC<ObjCInterfaceDecl> Validator;
1285    if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1286                                       LookupOrdinaryName, TUScope, NULL,
1287                                       Validator)) {
1288      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1289      Diag(IdLoc, diag::err_undef_interface_suggest)
1290        << Id << IDecl->getDeclName()
1291        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1292      Diag(IDecl->getLocation(), diag::note_previous_decl)
1293        << IDecl->getDeclName();
1294
1295      Id = IDecl->getIdentifier();
1296    }
1297  }
1298  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1299  // This routine must always return a class definition, if any.
1300  if (Def && Def->getDefinition())
1301      Def = Def->getDefinition();
1302  return Def;
1303}
1304
1305/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1306/// from S, where a non-field would be declared. This routine copes
1307/// with the difference between C and C++ scoping rules in structs and
1308/// unions. For example, the following code is well-formed in C but
1309/// ill-formed in C++:
1310/// @code
1311/// struct S6 {
1312///   enum { BAR } e;
1313/// };
1314///
1315/// void test_S6() {
1316///   struct S6 a;
1317///   a.e = BAR;
1318/// }
1319/// @endcode
1320/// For the declaration of BAR, this routine will return a different
1321/// scope. The scope S will be the scope of the unnamed enumeration
1322/// within S6. In C++, this routine will return the scope associated
1323/// with S6, because the enumeration's scope is a transparent
1324/// context but structures can contain non-field names. In C, this
1325/// routine will return the translation unit scope, since the
1326/// enumeration's scope is a transparent context and structures cannot
1327/// contain non-field names.
1328Scope *Sema::getNonFieldDeclScope(Scope *S) {
1329  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1330         (S->getEntity() &&
1331          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1332         (S->isClassScope() && !getLangOpts().CPlusPlus))
1333    S = S->getParent();
1334  return S;
1335}
1336
1337/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1338/// file scope.  lazily create a decl for it. ForRedeclaration is true
1339/// if we're creating this built-in in anticipation of redeclaring the
1340/// built-in.
1341NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1342                                     Scope *S, bool ForRedeclaration,
1343                                     SourceLocation Loc) {
1344  Builtin::ID BID = (Builtin::ID)bid;
1345
1346  ASTContext::GetBuiltinTypeError Error;
1347  QualType R = Context.GetBuiltinType(BID, Error);
1348  switch (Error) {
1349  case ASTContext::GE_None:
1350    // Okay
1351    break;
1352
1353  case ASTContext::GE_Missing_stdio:
1354    if (ForRedeclaration)
1355      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1356        << Context.BuiltinInfo.GetName(BID);
1357    return 0;
1358
1359  case ASTContext::GE_Missing_setjmp:
1360    if (ForRedeclaration)
1361      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1362        << Context.BuiltinInfo.GetName(BID);
1363    return 0;
1364
1365  case ASTContext::GE_Missing_ucontext:
1366    if (ForRedeclaration)
1367      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1368        << Context.BuiltinInfo.GetName(BID);
1369    return 0;
1370  }
1371
1372  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1373    Diag(Loc, diag::ext_implicit_lib_function_decl)
1374      << Context.BuiltinInfo.GetName(BID)
1375      << R;
1376    if (Context.BuiltinInfo.getHeaderName(BID) &&
1377        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1378          != DiagnosticsEngine::Ignored)
1379      Diag(Loc, diag::note_please_include_header)
1380        << Context.BuiltinInfo.getHeaderName(BID)
1381        << Context.BuiltinInfo.GetName(BID);
1382  }
1383
1384  FunctionDecl *New = FunctionDecl::Create(Context,
1385                                           Context.getTranslationUnitDecl(),
1386                                           Loc, Loc, II, R, /*TInfo=*/0,
1387                                           SC_Extern,
1388                                           SC_None, false,
1389                                           /*hasPrototype=*/true);
1390  New->setImplicit();
1391
1392  // Create Decl objects for each parameter, adding them to the
1393  // FunctionDecl.
1394  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1395    SmallVector<ParmVarDecl*, 16> Params;
1396    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1397      ParmVarDecl *parm =
1398        ParmVarDecl::Create(Context, New, SourceLocation(),
1399                            SourceLocation(), 0,
1400                            FT->getArgType(i), /*TInfo=*/0,
1401                            SC_None, SC_None, 0);
1402      parm->setScopeInfo(0, i);
1403      Params.push_back(parm);
1404    }
1405    New->setParams(Params);
1406  }
1407
1408  AddKnownFunctionAttributes(New);
1409
1410  // TUScope is the translation-unit scope to insert this function into.
1411  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1412  // relate Scopes to DeclContexts, and probably eliminate CurContext
1413  // entirely, but we're not there yet.
1414  DeclContext *SavedContext = CurContext;
1415  CurContext = Context.getTranslationUnitDecl();
1416  PushOnScopeChains(New, TUScope);
1417  CurContext = SavedContext;
1418  return New;
1419}
1420
1421bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1422  QualType OldType;
1423  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1424    OldType = OldTypedef->getUnderlyingType();
1425  else
1426    OldType = Context.getTypeDeclType(Old);
1427  QualType NewType = New->getUnderlyingType();
1428
1429  if (NewType->isVariablyModifiedType()) {
1430    // Must not redefine a typedef with a variably-modified type.
1431    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1432    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1433      << Kind << NewType;
1434    if (Old->getLocation().isValid())
1435      Diag(Old->getLocation(), diag::note_previous_definition);
1436    New->setInvalidDecl();
1437    return true;
1438  }
1439
1440  if (OldType != NewType &&
1441      !OldType->isDependentType() &&
1442      !NewType->isDependentType() &&
1443      !Context.hasSameType(OldType, NewType)) {
1444    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1445    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1446      << Kind << NewType << OldType;
1447    if (Old->getLocation().isValid())
1448      Diag(Old->getLocation(), diag::note_previous_definition);
1449    New->setInvalidDecl();
1450    return true;
1451  }
1452  return false;
1453}
1454
1455/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1456/// same name and scope as a previous declaration 'Old'.  Figure out
1457/// how to resolve this situation, merging decls or emitting
1458/// diagnostics as appropriate. If there was an error, set New to be invalid.
1459///
1460void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1461  // If the new decl is known invalid already, don't bother doing any
1462  // merging checks.
1463  if (New->isInvalidDecl()) return;
1464
1465  // Allow multiple definitions for ObjC built-in typedefs.
1466  // FIXME: Verify the underlying types are equivalent!
1467  if (getLangOpts().ObjC1) {
1468    const IdentifierInfo *TypeID = New->getIdentifier();
1469    switch (TypeID->getLength()) {
1470    default: break;
1471    case 2:
1472      if (!TypeID->isStr("id"))
1473        break;
1474      Context.setObjCIdRedefinitionType(New->getUnderlyingType());
1475      // Install the built-in type for 'id', ignoring the current definition.
1476      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1477      return;
1478    case 5:
1479      if (!TypeID->isStr("Class"))
1480        break;
1481      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1482      // Install the built-in type for 'Class', ignoring the current definition.
1483      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1484      return;
1485    case 3:
1486      if (!TypeID->isStr("SEL"))
1487        break;
1488      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1489      // Install the built-in type for 'SEL', ignoring the current definition.
1490      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1491      return;
1492    }
1493    // Fall through - the typedef name was not a builtin type.
1494  }
1495
1496  // Verify the old decl was also a type.
1497  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1498  if (!Old) {
1499    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1500      << New->getDeclName();
1501
1502    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1503    if (OldD->getLocation().isValid())
1504      Diag(OldD->getLocation(), diag::note_previous_definition);
1505
1506    return New->setInvalidDecl();
1507  }
1508
1509  // If the old declaration is invalid, just give up here.
1510  if (Old->isInvalidDecl())
1511    return New->setInvalidDecl();
1512
1513  // If the typedef types are not identical, reject them in all languages and
1514  // with any extensions enabled.
1515  if (isIncompatibleTypedef(Old, New))
1516    return;
1517
1518  // The types match.  Link up the redeclaration chain if the old
1519  // declaration was a typedef.
1520  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1521    New->setPreviousDeclaration(Typedef);
1522
1523  if (getLangOpts().MicrosoftExt)
1524    return;
1525
1526  if (getLangOpts().CPlusPlus) {
1527    // C++ [dcl.typedef]p2:
1528    //   In a given non-class scope, a typedef specifier can be used to
1529    //   redefine the name of any type declared in that scope to refer
1530    //   to the type to which it already refers.
1531    if (!isa<CXXRecordDecl>(CurContext))
1532      return;
1533
1534    // C++0x [dcl.typedef]p4:
1535    //   In a given class scope, a typedef specifier can be used to redefine
1536    //   any class-name declared in that scope that is not also a typedef-name
1537    //   to refer to the type to which it already refers.
1538    //
1539    // This wording came in via DR424, which was a correction to the
1540    // wording in DR56, which accidentally banned code like:
1541    //
1542    //   struct S {
1543    //     typedef struct A { } A;
1544    //   };
1545    //
1546    // in the C++03 standard. We implement the C++0x semantics, which
1547    // allow the above but disallow
1548    //
1549    //   struct S {
1550    //     typedef int I;
1551    //     typedef int I;
1552    //   };
1553    //
1554    // since that was the intent of DR56.
1555    if (!isa<TypedefNameDecl>(Old))
1556      return;
1557
1558    Diag(New->getLocation(), diag::err_redefinition)
1559      << New->getDeclName();
1560    Diag(Old->getLocation(), diag::note_previous_definition);
1561    return New->setInvalidDecl();
1562  }
1563
1564  // Modules always permit redefinition of typedefs, as does C11.
1565  if (getLangOpts().Modules || getLangOpts().C11)
1566    return;
1567
1568  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1569  // is normally mapped to an error, but can be controlled with
1570  // -Wtypedef-redefinition.  If either the original or the redefinition is
1571  // in a system header, don't emit this for compatibility with GCC.
1572  if (getDiagnostics().getSuppressSystemWarnings() &&
1573      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1574       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1575    return;
1576
1577  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1578    << New->getDeclName();
1579  Diag(Old->getLocation(), diag::note_previous_definition);
1580  return;
1581}
1582
1583/// DeclhasAttr - returns true if decl Declaration already has the target
1584/// attribute.
1585static bool
1586DeclHasAttr(const Decl *D, const Attr *A) {
1587  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1588  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1589  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1590    if ((*i)->getKind() == A->getKind()) {
1591      if (Ann) {
1592        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1593          return true;
1594        continue;
1595      }
1596      // FIXME: Don't hardcode this check
1597      if (OA && isa<OwnershipAttr>(*i))
1598        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1599      return true;
1600    }
1601
1602  return false;
1603}
1604
1605/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1606void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1607                               bool MergeDeprecation) {
1608  if (!Old->hasAttrs())
1609    return;
1610
1611  bool foundAny = New->hasAttrs();
1612
1613  // Ensure that any moving of objects within the allocated map is done before
1614  // we process them.
1615  if (!foundAny) New->setAttrs(AttrVec());
1616
1617  for (specific_attr_iterator<InheritableAttr>
1618         i = Old->specific_attr_begin<InheritableAttr>(),
1619         e = Old->specific_attr_end<InheritableAttr>();
1620       i != e; ++i) {
1621    // Ignore deprecated/unavailable/availability attributes if requested.
1622    if (!MergeDeprecation &&
1623        (isa<DeprecatedAttr>(*i) ||
1624         isa<UnavailableAttr>(*i) ||
1625         isa<AvailabilityAttr>(*i)))
1626      continue;
1627
1628    if (!DeclHasAttr(New, *i)) {
1629      InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
1630      newAttr->setInherited(true);
1631      New->addAttr(newAttr);
1632      foundAny = true;
1633    }
1634  }
1635
1636  if (!foundAny) New->dropAttrs();
1637}
1638
1639/// mergeParamDeclAttributes - Copy attributes from the old parameter
1640/// to the new one.
1641static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1642                                     const ParmVarDecl *oldDecl,
1643                                     ASTContext &C) {
1644  if (!oldDecl->hasAttrs())
1645    return;
1646
1647  bool foundAny = newDecl->hasAttrs();
1648
1649  // Ensure that any moving of objects within the allocated map is
1650  // done before we process them.
1651  if (!foundAny) newDecl->setAttrs(AttrVec());
1652
1653  for (specific_attr_iterator<InheritableParamAttr>
1654       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1655       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1656    if (!DeclHasAttr(newDecl, *i)) {
1657      InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1658      newAttr->setInherited(true);
1659      newDecl->addAttr(newAttr);
1660      foundAny = true;
1661    }
1662  }
1663
1664  if (!foundAny) newDecl->dropAttrs();
1665}
1666
1667namespace {
1668
1669/// Used in MergeFunctionDecl to keep track of function parameters in
1670/// C.
1671struct GNUCompatibleParamWarning {
1672  ParmVarDecl *OldParm;
1673  ParmVarDecl *NewParm;
1674  QualType PromotedType;
1675};
1676
1677}
1678
1679/// getSpecialMember - get the special member enum for a method.
1680Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1681  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1682    if (Ctor->isDefaultConstructor())
1683      return Sema::CXXDefaultConstructor;
1684
1685    if (Ctor->isCopyConstructor())
1686      return Sema::CXXCopyConstructor;
1687
1688    if (Ctor->isMoveConstructor())
1689      return Sema::CXXMoveConstructor;
1690  } else if (isa<CXXDestructorDecl>(MD)) {
1691    return Sema::CXXDestructor;
1692  } else if (MD->isCopyAssignmentOperator()) {
1693    return Sema::CXXCopyAssignment;
1694  } else if (MD->isMoveAssignmentOperator()) {
1695    return Sema::CXXMoveAssignment;
1696  }
1697
1698  return Sema::CXXInvalid;
1699}
1700
1701/// canRedefineFunction - checks if a function can be redefined. Currently,
1702/// only extern inline functions can be redefined, and even then only in
1703/// GNU89 mode.
1704static bool canRedefineFunction(const FunctionDecl *FD,
1705                                const LangOptions& LangOpts) {
1706  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1707          !LangOpts.CPlusPlus &&
1708          FD->isInlineSpecified() &&
1709          FD->getStorageClass() == SC_Extern);
1710}
1711
1712/// MergeFunctionDecl - We just parsed a function 'New' from
1713/// declarator D which has the same name and scope as a previous
1714/// declaration 'Old'.  Figure out how to resolve this situation,
1715/// merging decls or emitting diagnostics as appropriate.
1716///
1717/// In C++, New and Old must be declarations that are not
1718/// overloaded. Use IsOverload to determine whether New and Old are
1719/// overloaded, and to select the Old declaration that New should be
1720/// merged with.
1721///
1722/// Returns true if there was an error, false otherwise.
1723bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1724  // Verify the old decl was also a function.
1725  FunctionDecl *Old = 0;
1726  if (FunctionTemplateDecl *OldFunctionTemplate
1727        = dyn_cast<FunctionTemplateDecl>(OldD))
1728    Old = OldFunctionTemplate->getTemplatedDecl();
1729  else
1730    Old = dyn_cast<FunctionDecl>(OldD);
1731  if (!Old) {
1732    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1733      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1734      Diag(Shadow->getTargetDecl()->getLocation(),
1735           diag::note_using_decl_target);
1736      Diag(Shadow->getUsingDecl()->getLocation(),
1737           diag::note_using_decl) << 0;
1738      return true;
1739    }
1740
1741    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1742      << New->getDeclName();
1743    Diag(OldD->getLocation(), diag::note_previous_definition);
1744    return true;
1745  }
1746
1747  // Determine whether the previous declaration was a definition,
1748  // implicit declaration, or a declaration.
1749  diag::kind PrevDiag;
1750  if (Old->isThisDeclarationADefinition())
1751    PrevDiag = diag::note_previous_definition;
1752  else if (Old->isImplicit())
1753    PrevDiag = diag::note_previous_implicit_declaration;
1754  else
1755    PrevDiag = diag::note_previous_declaration;
1756
1757  QualType OldQType = Context.getCanonicalType(Old->getType());
1758  QualType NewQType = Context.getCanonicalType(New->getType());
1759
1760  // Don't complain about this if we're in GNU89 mode and the old function
1761  // is an extern inline function.
1762  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1763      New->getStorageClass() == SC_Static &&
1764      Old->getStorageClass() != SC_Static &&
1765      !canRedefineFunction(Old, getLangOpts())) {
1766    if (getLangOpts().MicrosoftExt) {
1767      Diag(New->getLocation(), diag::warn_static_non_static) << New;
1768      Diag(Old->getLocation(), PrevDiag);
1769    } else {
1770      Diag(New->getLocation(), diag::err_static_non_static) << New;
1771      Diag(Old->getLocation(), PrevDiag);
1772      return true;
1773    }
1774  }
1775
1776  // If a function is first declared with a calling convention, but is
1777  // later declared or defined without one, the second decl assumes the
1778  // calling convention of the first.
1779  //
1780  // For the new decl, we have to look at the NON-canonical type to tell the
1781  // difference between a function that really doesn't have a calling
1782  // convention and one that is declared cdecl. That's because in
1783  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1784  // because it is the default calling convention.
1785  //
1786  // Note also that we DO NOT return at this point, because we still have
1787  // other tests to run.
1788  const FunctionType *OldType = cast<FunctionType>(OldQType);
1789  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1790  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1791  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1792  bool RequiresAdjustment = false;
1793  if (OldTypeInfo.getCC() != CC_Default &&
1794      NewTypeInfo.getCC() == CC_Default) {
1795    NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1796    RequiresAdjustment = true;
1797  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1798                                     NewTypeInfo.getCC())) {
1799    // Calling conventions really aren't compatible, so complain.
1800    Diag(New->getLocation(), diag::err_cconv_change)
1801      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1802      << (OldTypeInfo.getCC() == CC_Default)
1803      << (OldTypeInfo.getCC() == CC_Default ? "" :
1804          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1805    Diag(Old->getLocation(), diag::note_previous_declaration);
1806    return true;
1807  }
1808
1809  // FIXME: diagnose the other way around?
1810  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1811    NewTypeInfo = NewTypeInfo.withNoReturn(true);
1812    RequiresAdjustment = true;
1813  }
1814
1815  // Merge regparm attribute.
1816  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1817      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1818    if (NewTypeInfo.getHasRegParm()) {
1819      Diag(New->getLocation(), diag::err_regparm_mismatch)
1820        << NewType->getRegParmType()
1821        << OldType->getRegParmType();
1822      Diag(Old->getLocation(), diag::note_previous_declaration);
1823      return true;
1824    }
1825
1826    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1827    RequiresAdjustment = true;
1828  }
1829
1830  // Merge ns_returns_retained attribute.
1831  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1832    if (NewTypeInfo.getProducesResult()) {
1833      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1834      Diag(Old->getLocation(), diag::note_previous_declaration);
1835      return true;
1836    }
1837
1838    NewTypeInfo = NewTypeInfo.withProducesResult(true);
1839    RequiresAdjustment = true;
1840  }
1841
1842  if (RequiresAdjustment) {
1843    NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1844    New->setType(QualType(NewType, 0));
1845    NewQType = Context.getCanonicalType(New->getType());
1846  }
1847
1848  if (getLangOpts().CPlusPlus) {
1849    // (C++98 13.1p2):
1850    //   Certain function declarations cannot be overloaded:
1851    //     -- Function declarations that differ only in the return type
1852    //        cannot be overloaded.
1853    QualType OldReturnType = OldType->getResultType();
1854    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1855    QualType ResQT;
1856    if (OldReturnType != NewReturnType) {
1857      if (NewReturnType->isObjCObjectPointerType()
1858          && OldReturnType->isObjCObjectPointerType())
1859        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1860      if (ResQT.isNull()) {
1861        if (New->isCXXClassMember() && New->isOutOfLine())
1862          Diag(New->getLocation(),
1863               diag::err_member_def_does_not_match_ret_type) << New;
1864        else
1865          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1866        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1867        return true;
1868      }
1869      else
1870        NewQType = ResQT;
1871    }
1872
1873    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1874    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1875    if (OldMethod && NewMethod) {
1876      // Preserve triviality.
1877      NewMethod->setTrivial(OldMethod->isTrivial());
1878
1879      // MSVC allows explicit template specialization at class scope:
1880      // 2 CXMethodDecls referring to the same function will be injected.
1881      // We don't want a redeclartion error.
1882      bool IsClassScopeExplicitSpecialization =
1883                              OldMethod->isFunctionTemplateSpecialization() &&
1884                              NewMethod->isFunctionTemplateSpecialization();
1885      bool isFriend = NewMethod->getFriendObjectKind();
1886
1887      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1888          !IsClassScopeExplicitSpecialization) {
1889        //    -- Member function declarations with the same name and the
1890        //       same parameter types cannot be overloaded if any of them
1891        //       is a static member function declaration.
1892        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1893          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1894          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1895          return true;
1896        }
1897
1898        // C++ [class.mem]p1:
1899        //   [...] A member shall not be declared twice in the
1900        //   member-specification, except that a nested class or member
1901        //   class template can be declared and then later defined.
1902        unsigned NewDiag;
1903        if (isa<CXXConstructorDecl>(OldMethod))
1904          NewDiag = diag::err_constructor_redeclared;
1905        else if (isa<CXXDestructorDecl>(NewMethod))
1906          NewDiag = diag::err_destructor_redeclared;
1907        else if (isa<CXXConversionDecl>(NewMethod))
1908          NewDiag = diag::err_conv_function_redeclared;
1909        else
1910          NewDiag = diag::err_member_redeclared;
1911
1912        Diag(New->getLocation(), NewDiag);
1913        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1914
1915      // Complain if this is an explicit declaration of a special
1916      // member that was initially declared implicitly.
1917      //
1918      // As an exception, it's okay to befriend such methods in order
1919      // to permit the implicit constructor/destructor/operator calls.
1920      } else if (OldMethod->isImplicit()) {
1921        if (isFriend) {
1922          NewMethod->setImplicit();
1923        } else {
1924          Diag(NewMethod->getLocation(),
1925               diag::err_definition_of_implicitly_declared_member)
1926            << New << getSpecialMember(OldMethod);
1927          return true;
1928        }
1929      } else if (OldMethod->isExplicitlyDefaulted()) {
1930        Diag(NewMethod->getLocation(),
1931             diag::err_definition_of_explicitly_defaulted_member)
1932          << getSpecialMember(OldMethod);
1933        return true;
1934      }
1935    }
1936
1937    // (C++98 8.3.5p3):
1938    //   All declarations for a function shall agree exactly in both the
1939    //   return type and the parameter-type-list.
1940    // We also want to respect all the extended bits except noreturn.
1941
1942    // noreturn should now match unless the old type info didn't have it.
1943    QualType OldQTypeForComparison = OldQType;
1944    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1945      assert(OldQType == QualType(OldType, 0));
1946      const FunctionType *OldTypeForComparison
1947        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1948      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1949      assert(OldQTypeForComparison.isCanonical());
1950    }
1951
1952    if (OldQTypeForComparison == NewQType)
1953      return MergeCompatibleFunctionDecls(New, Old, S);
1954
1955    // Fall through for conflicting redeclarations and redefinitions.
1956  }
1957
1958  // C: Function types need to be compatible, not identical. This handles
1959  // duplicate function decls like "void f(int); void f(enum X);" properly.
1960  if (!getLangOpts().CPlusPlus &&
1961      Context.typesAreCompatible(OldQType, NewQType)) {
1962    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1963    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1964    const FunctionProtoType *OldProto = 0;
1965    if (isa<FunctionNoProtoType>(NewFuncType) &&
1966        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1967      // The old declaration provided a function prototype, but the
1968      // new declaration does not. Merge in the prototype.
1969      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1970      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1971                                                 OldProto->arg_type_end());
1972      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1973                                         ParamTypes.data(), ParamTypes.size(),
1974                                         OldProto->getExtProtoInfo());
1975      New->setType(NewQType);
1976      New->setHasInheritedPrototype();
1977
1978      // Synthesize a parameter for each argument type.
1979      SmallVector<ParmVarDecl*, 16> Params;
1980      for (FunctionProtoType::arg_type_iterator
1981             ParamType = OldProto->arg_type_begin(),
1982             ParamEnd = OldProto->arg_type_end();
1983           ParamType != ParamEnd; ++ParamType) {
1984        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1985                                                 SourceLocation(),
1986                                                 SourceLocation(), 0,
1987                                                 *ParamType, /*TInfo=*/0,
1988                                                 SC_None, SC_None,
1989                                                 0);
1990        Param->setScopeInfo(0, Params.size());
1991        Param->setImplicit();
1992        Params.push_back(Param);
1993      }
1994
1995      New->setParams(Params);
1996    }
1997
1998    return MergeCompatibleFunctionDecls(New, Old, S);
1999  }
2000
2001  // GNU C permits a K&R definition to follow a prototype declaration
2002  // if the declared types of the parameters in the K&R definition
2003  // match the types in the prototype declaration, even when the
2004  // promoted types of the parameters from the K&R definition differ
2005  // from the types in the prototype. GCC then keeps the types from
2006  // the prototype.
2007  //
2008  // If a variadic prototype is followed by a non-variadic K&R definition,
2009  // the K&R definition becomes variadic.  This is sort of an edge case, but
2010  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2011  // C99 6.9.1p8.
2012  if (!getLangOpts().CPlusPlus &&
2013      Old->hasPrototype() && !New->hasPrototype() &&
2014      New->getType()->getAs<FunctionProtoType>() &&
2015      Old->getNumParams() == New->getNumParams()) {
2016    SmallVector<QualType, 16> ArgTypes;
2017    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2018    const FunctionProtoType *OldProto
2019      = Old->getType()->getAs<FunctionProtoType>();
2020    const FunctionProtoType *NewProto
2021      = New->getType()->getAs<FunctionProtoType>();
2022
2023    // Determine whether this is the GNU C extension.
2024    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2025                                               NewProto->getResultType());
2026    bool LooseCompatible = !MergedReturn.isNull();
2027    for (unsigned Idx = 0, End = Old->getNumParams();
2028         LooseCompatible && Idx != End; ++Idx) {
2029      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2030      ParmVarDecl *NewParm = New->getParamDecl(Idx);
2031      if (Context.typesAreCompatible(OldParm->getType(),
2032                                     NewProto->getArgType(Idx))) {
2033        ArgTypes.push_back(NewParm->getType());
2034      } else if (Context.typesAreCompatible(OldParm->getType(),
2035                                            NewParm->getType(),
2036                                            /*CompareUnqualified=*/true)) {
2037        GNUCompatibleParamWarning Warn
2038          = { OldParm, NewParm, NewProto->getArgType(Idx) };
2039        Warnings.push_back(Warn);
2040        ArgTypes.push_back(NewParm->getType());
2041      } else
2042        LooseCompatible = false;
2043    }
2044
2045    if (LooseCompatible) {
2046      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2047        Diag(Warnings[Warn].NewParm->getLocation(),
2048             diag::ext_param_promoted_not_compatible_with_prototype)
2049          << Warnings[Warn].PromotedType
2050          << Warnings[Warn].OldParm->getType();
2051        if (Warnings[Warn].OldParm->getLocation().isValid())
2052          Diag(Warnings[Warn].OldParm->getLocation(),
2053               diag::note_previous_declaration);
2054      }
2055
2056      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2057                                           ArgTypes.size(),
2058                                           OldProto->getExtProtoInfo()));
2059      return MergeCompatibleFunctionDecls(New, Old, S);
2060    }
2061
2062    // Fall through to diagnose conflicting types.
2063  }
2064
2065  // A function that has already been declared has been redeclared or defined
2066  // with a different type- show appropriate diagnostic
2067  if (unsigned BuiltinID = Old->getBuiltinID()) {
2068    // The user has declared a builtin function with an incompatible
2069    // signature.
2070    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2071      // The function the user is redeclaring is a library-defined
2072      // function like 'malloc' or 'printf'. Warn about the
2073      // redeclaration, then pretend that we don't know about this
2074      // library built-in.
2075      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2076      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2077        << Old << Old->getType();
2078      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2079      Old->setInvalidDecl();
2080      return false;
2081    }
2082
2083    PrevDiag = diag::note_previous_builtin_declaration;
2084  }
2085
2086  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2087  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2088  return true;
2089}
2090
2091/// \brief Completes the merge of two function declarations that are
2092/// known to be compatible.
2093///
2094/// This routine handles the merging of attributes and other
2095/// properties of function declarations form the old declaration to
2096/// the new declaration, once we know that New is in fact a
2097/// redeclaration of Old.
2098///
2099/// \returns false
2100bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2101                                        Scope *S) {
2102  // Merge the attributes
2103  mergeDeclAttributes(New, Old);
2104
2105  // Merge the storage class.
2106  if (Old->getStorageClass() != SC_Extern &&
2107      Old->getStorageClass() != SC_None)
2108    New->setStorageClass(Old->getStorageClass());
2109
2110  // Merge "pure" flag.
2111  if (Old->isPure())
2112    New->setPure();
2113
2114  // Merge attributes from the parameters.  These can mismatch with K&R
2115  // declarations.
2116  if (New->getNumParams() == Old->getNumParams())
2117    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2118      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2119                               Context);
2120
2121  if (getLangOpts().CPlusPlus)
2122    return MergeCXXFunctionDecl(New, Old, S);
2123
2124  return false;
2125}
2126
2127
2128void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2129                                ObjCMethodDecl *oldMethod) {
2130  // We don't want to merge unavailable and deprecated attributes
2131  // except from interface to implementation.
2132  bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2133
2134  // Merge the attributes.
2135  mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
2136
2137  // Merge attributes from the parameters.
2138  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2139  for (ObjCMethodDecl::param_iterator
2140         ni = newMethod->param_begin(), ne = newMethod->param_end();
2141       ni != ne; ++ni, ++oi)
2142    mergeParamDeclAttributes(*ni, *oi, Context);
2143
2144  CheckObjCMethodOverride(newMethod, oldMethod, true);
2145}
2146
2147/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2148/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2149/// emitting diagnostics as appropriate.
2150///
2151/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2152/// to here in AddInitializerToDecl. We can't check them before the initializer
2153/// is attached.
2154void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2155  if (New->isInvalidDecl() || Old->isInvalidDecl())
2156    return;
2157
2158  QualType MergedT;
2159  if (getLangOpts().CPlusPlus) {
2160    AutoType *AT = New->getType()->getContainedAutoType();
2161    if (AT && !AT->isDeduced()) {
2162      // We don't know what the new type is until the initializer is attached.
2163      return;
2164    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2165      // These could still be something that needs exception specs checked.
2166      return MergeVarDeclExceptionSpecs(New, Old);
2167    }
2168    // C++ [basic.link]p10:
2169    //   [...] the types specified by all declarations referring to a given
2170    //   object or function shall be identical, except that declarations for an
2171    //   array object can specify array types that differ by the presence or
2172    //   absence of a major array bound (8.3.4).
2173    else if (Old->getType()->isIncompleteArrayType() &&
2174             New->getType()->isArrayType()) {
2175      CanQual<ArrayType> OldArray
2176        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2177      CanQual<ArrayType> NewArray
2178        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2179      if (OldArray->getElementType() == NewArray->getElementType())
2180        MergedT = New->getType();
2181    } else if (Old->getType()->isArrayType() &&
2182             New->getType()->isIncompleteArrayType()) {
2183      CanQual<ArrayType> OldArray
2184        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2185      CanQual<ArrayType> NewArray
2186        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2187      if (OldArray->getElementType() == NewArray->getElementType())
2188        MergedT = Old->getType();
2189    } else if (New->getType()->isObjCObjectPointerType()
2190               && Old->getType()->isObjCObjectPointerType()) {
2191        MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2192                                                        Old->getType());
2193    }
2194  } else {
2195    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2196  }
2197  if (MergedT.isNull()) {
2198    Diag(New->getLocation(), diag::err_redefinition_different_type)
2199      << New->getDeclName();
2200    Diag(Old->getLocation(), diag::note_previous_definition);
2201    return New->setInvalidDecl();
2202  }
2203  New->setType(MergedT);
2204}
2205
2206/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2207/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2208/// situation, merging decls or emitting diagnostics as appropriate.
2209///
2210/// Tentative definition rules (C99 6.9.2p2) are checked by
2211/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2212/// definitions here, since the initializer hasn't been attached.
2213///
2214void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2215  // If the new decl is already invalid, don't do any other checking.
2216  if (New->isInvalidDecl())
2217    return;
2218
2219  // Verify the old decl was also a variable.
2220  VarDecl *Old = 0;
2221  if (!Previous.isSingleResult() ||
2222      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2223    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2224      << New->getDeclName();
2225    Diag(Previous.getRepresentativeDecl()->getLocation(),
2226         diag::note_previous_definition);
2227    return New->setInvalidDecl();
2228  }
2229
2230  // C++ [class.mem]p1:
2231  //   A member shall not be declared twice in the member-specification [...]
2232  //
2233  // Here, we need only consider static data members.
2234  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2235    Diag(New->getLocation(), diag::err_duplicate_member)
2236      << New->getIdentifier();
2237    Diag(Old->getLocation(), diag::note_previous_declaration);
2238    New->setInvalidDecl();
2239  }
2240
2241  mergeDeclAttributes(New, Old);
2242  // Warn if an already-declared variable is made a weak_import in a subsequent
2243  // declaration
2244  if (New->getAttr<WeakImportAttr>() &&
2245      Old->getStorageClass() == SC_None &&
2246      !Old->getAttr<WeakImportAttr>()) {
2247    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2248    Diag(Old->getLocation(), diag::note_previous_definition);
2249    // Remove weak_import attribute on new declaration.
2250    New->dropAttr<WeakImportAttr>();
2251  }
2252
2253  // Merge the types.
2254  MergeVarDeclTypes(New, Old);
2255  if (New->isInvalidDecl())
2256    return;
2257
2258  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2259  if (New->getStorageClass() == SC_Static &&
2260      (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2261    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2262    Diag(Old->getLocation(), diag::note_previous_definition);
2263    return New->setInvalidDecl();
2264  }
2265  // C99 6.2.2p4:
2266  //   For an identifier declared with the storage-class specifier
2267  //   extern in a scope in which a prior declaration of that
2268  //   identifier is visible,23) if the prior declaration specifies
2269  //   internal or external linkage, the linkage of the identifier at
2270  //   the later declaration is the same as the linkage specified at
2271  //   the prior declaration. If no prior declaration is visible, or
2272  //   if the prior declaration specifies no linkage, then the
2273  //   identifier has external linkage.
2274  if (New->hasExternalStorage() && Old->hasLinkage())
2275    /* Okay */;
2276  else if (New->getStorageClass() != SC_Static &&
2277           Old->getStorageClass() == SC_Static) {
2278    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2279    Diag(Old->getLocation(), diag::note_previous_definition);
2280    return New->setInvalidDecl();
2281  }
2282
2283  // Check if extern is followed by non-extern and vice-versa.
2284  if (New->hasExternalStorage() &&
2285      !Old->hasLinkage() && Old->isLocalVarDecl()) {
2286    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2287    Diag(Old->getLocation(), diag::note_previous_definition);
2288    return New->setInvalidDecl();
2289  }
2290  if (Old->hasExternalStorage() &&
2291      !New->hasLinkage() && New->isLocalVarDecl()) {
2292    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2293    Diag(Old->getLocation(), diag::note_previous_definition);
2294    return New->setInvalidDecl();
2295  }
2296
2297  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2298
2299  // FIXME: The test for external storage here seems wrong? We still
2300  // need to check for mismatches.
2301  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2302      // Don't complain about out-of-line definitions of static members.
2303      !(Old->getLexicalDeclContext()->isRecord() &&
2304        !New->getLexicalDeclContext()->isRecord())) {
2305    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2306    Diag(Old->getLocation(), diag::note_previous_definition);
2307    return New->setInvalidDecl();
2308  }
2309
2310  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2311    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2312    Diag(Old->getLocation(), diag::note_previous_definition);
2313  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2314    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2315    Diag(Old->getLocation(), diag::note_previous_definition);
2316  }
2317
2318  // C++ doesn't have tentative definitions, so go right ahead and check here.
2319  const VarDecl *Def;
2320  if (getLangOpts().CPlusPlus &&
2321      New->isThisDeclarationADefinition() == VarDecl::Definition &&
2322      (Def = Old->getDefinition())) {
2323    Diag(New->getLocation(), diag::err_redefinition)
2324      << New->getDeclName();
2325    Diag(Def->getLocation(), diag::note_previous_definition);
2326    New->setInvalidDecl();
2327    return;
2328  }
2329  // c99 6.2.2 P4.
2330  // For an identifier declared with the storage-class specifier extern in a
2331  // scope in which a prior declaration of that identifier is visible, if
2332  // the prior declaration specifies internal or external linkage, the linkage
2333  // of the identifier at the later declaration is the same as the linkage
2334  // specified at the prior declaration.
2335  // FIXME. revisit this code.
2336  if (New->hasExternalStorage() &&
2337      Old->getLinkage() == InternalLinkage &&
2338      New->getDeclContext() == Old->getDeclContext())
2339    New->setStorageClass(Old->getStorageClass());
2340
2341  // Keep a chain of previous declarations.
2342  New->setPreviousDeclaration(Old);
2343
2344  // Inherit access appropriately.
2345  New->setAccess(Old->getAccess());
2346}
2347
2348/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2349/// no declarator (e.g. "struct foo;") is parsed.
2350Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2351                                       DeclSpec &DS) {
2352  return ParsedFreeStandingDeclSpec(S, AS, DS,
2353                                    MultiTemplateParamsArg(*this, 0, 0));
2354}
2355
2356/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2357/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2358/// parameters to cope with template friend declarations.
2359Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2360                                       DeclSpec &DS,
2361                                       MultiTemplateParamsArg TemplateParams) {
2362  Decl *TagD = 0;
2363  TagDecl *Tag = 0;
2364  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2365      DS.getTypeSpecType() == DeclSpec::TST_struct ||
2366      DS.getTypeSpecType() == DeclSpec::TST_union ||
2367      DS.getTypeSpecType() == DeclSpec::TST_enum) {
2368    TagD = DS.getRepAsDecl();
2369
2370    if (!TagD) // We probably had an error
2371      return 0;
2372
2373    // Note that the above type specs guarantee that the
2374    // type rep is a Decl, whereas in many of the others
2375    // it's a Type.
2376    if (isa<TagDecl>(TagD))
2377      Tag = cast<TagDecl>(TagD);
2378    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2379      Tag = CTD->getTemplatedDecl();
2380  }
2381
2382  if (Tag) {
2383    Tag->setFreeStanding();
2384    if (Tag->isInvalidDecl())
2385      return Tag;
2386  }
2387
2388  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2389    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2390    // or incomplete types shall not be restrict-qualified."
2391    if (TypeQuals & DeclSpec::TQ_restrict)
2392      Diag(DS.getRestrictSpecLoc(),
2393           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2394           << DS.getSourceRange();
2395  }
2396
2397  if (DS.isConstexprSpecified()) {
2398    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2399    // and definitions of functions and variables.
2400    if (Tag)
2401      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2402        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2403            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2404            DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2405    else
2406      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2407    // Don't emit warnings after this error.
2408    return TagD;
2409  }
2410
2411  if (DS.isFriendSpecified()) {
2412    // If we're dealing with a decl but not a TagDecl, assume that
2413    // whatever routines created it handled the friendship aspect.
2414    if (TagD && !Tag)
2415      return 0;
2416    return ActOnFriendTypeDecl(S, DS, TemplateParams);
2417  }
2418
2419  // Track whether we warned about the fact that there aren't any
2420  // declarators.
2421  bool emittedWarning = false;
2422
2423  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2424    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2425        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2426      if (getLangOpts().CPlusPlus ||
2427          Record->getDeclContext()->isRecord())
2428        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2429
2430      Diag(DS.getLocStart(), diag::ext_no_declarators)
2431        << DS.getSourceRange();
2432      emittedWarning = true;
2433    }
2434  }
2435
2436  // Check for Microsoft C extension: anonymous struct.
2437  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2438      CurContext->isRecord() &&
2439      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2440    // Handle 2 kinds of anonymous struct:
2441    //   struct STRUCT;
2442    // and
2443    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2444    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2445    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2446        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2447         DS.getRepAsType().get()->isStructureType())) {
2448      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2449        << DS.getSourceRange();
2450      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2451    }
2452  }
2453
2454  if (getLangOpts().CPlusPlus &&
2455      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2456    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2457      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2458          !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2459        Diag(Enum->getLocation(), diag::ext_no_declarators)
2460          << DS.getSourceRange();
2461        emittedWarning = true;
2462      }
2463
2464  // Skip all the checks below if we have a type error.
2465  if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2466
2467  if (!DS.isMissingDeclaratorOk()) {
2468    // Warn about typedefs of enums without names, since this is an
2469    // extension in both Microsoft and GNU.
2470    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2471        Tag && isa<EnumDecl>(Tag)) {
2472      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2473        << DS.getSourceRange();
2474      return Tag;
2475    }
2476
2477    Diag(DS.getLocStart(), diag::ext_no_declarators)
2478      << DS.getSourceRange();
2479    emittedWarning = true;
2480  }
2481
2482  // We're going to complain about a bunch of spurious specifiers;
2483  // only do this if we're declaring a tag, because otherwise we
2484  // should be getting diag::ext_no_declarators.
2485  if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2486    return TagD;
2487
2488  // Note that a linkage-specification sets a storage class, but
2489  // 'extern "C" struct foo;' is actually valid and not theoretically
2490  // useless.
2491  if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2492    if (!DS.isExternInLinkageSpec())
2493      Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2494        << DeclSpec::getSpecifierName(scs);
2495
2496  if (DS.isThreadSpecified())
2497    Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2498  if (DS.getTypeQualifiers()) {
2499    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2500      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2501    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2502      Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2503    // Restrict is covered above.
2504  }
2505  if (DS.isInlineSpecified())
2506    Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2507  if (DS.isVirtualSpecified())
2508    Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2509  if (DS.isExplicitSpecified())
2510    Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2511
2512  if (DS.isModulePrivateSpecified() &&
2513      Tag && Tag->getDeclContext()->isFunctionOrMethod())
2514    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2515      << Tag->getTagKind()
2516      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2517
2518  // Warn about ignored type attributes, for example:
2519  // __attribute__((aligned)) struct A;
2520  // Attributes should be placed after tag to apply to type declaration.
2521  if (!DS.getAttributes().empty()) {
2522    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2523    if (TypeSpecType == DeclSpec::TST_class ||
2524        TypeSpecType == DeclSpec::TST_struct ||
2525        TypeSpecType == DeclSpec::TST_union ||
2526        TypeSpecType == DeclSpec::TST_enum) {
2527      AttributeList* attrs = DS.getAttributes().getList();
2528      while (attrs) {
2529        Diag(attrs->getScopeLoc(),
2530             diag::warn_declspec_attribute_ignored)
2531        << attrs->getName()
2532        << (TypeSpecType == DeclSpec::TST_class ? 0 :
2533            TypeSpecType == DeclSpec::TST_struct ? 1 :
2534            TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2535        attrs = attrs->getNext();
2536      }
2537    }
2538  }
2539
2540  return TagD;
2541}
2542
2543/// We are trying to inject an anonymous member into the given scope;
2544/// check if there's an existing declaration that can't be overloaded.
2545///
2546/// \return true if this is a forbidden redeclaration
2547static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2548                                         Scope *S,
2549                                         DeclContext *Owner,
2550                                         DeclarationName Name,
2551                                         SourceLocation NameLoc,
2552                                         unsigned diagnostic) {
2553  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2554                 Sema::ForRedeclaration);
2555  if (!SemaRef.LookupName(R, S)) return false;
2556
2557  if (R.getAsSingle<TagDecl>())
2558    return false;
2559
2560  // Pick a representative declaration.
2561  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2562  assert(PrevDecl && "Expected a non-null Decl");
2563
2564  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2565    return false;
2566
2567  SemaRef.Diag(NameLoc, diagnostic) << Name;
2568  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2569
2570  return true;
2571}
2572
2573/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2574/// anonymous struct or union AnonRecord into the owning context Owner
2575/// and scope S. This routine will be invoked just after we realize
2576/// that an unnamed union or struct is actually an anonymous union or
2577/// struct, e.g.,
2578///
2579/// @code
2580/// union {
2581///   int i;
2582///   float f;
2583/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2584///    // f into the surrounding scope.x
2585/// @endcode
2586///
2587/// This routine is recursive, injecting the names of nested anonymous
2588/// structs/unions into the owning context and scope as well.
2589static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2590                                                DeclContext *Owner,
2591                                                RecordDecl *AnonRecord,
2592                                                AccessSpecifier AS,
2593                              SmallVector<NamedDecl*, 2> &Chaining,
2594                                                      bool MSAnonStruct) {
2595  unsigned diagKind
2596    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2597                            : diag::err_anonymous_struct_member_redecl;
2598
2599  bool Invalid = false;
2600
2601  // Look every FieldDecl and IndirectFieldDecl with a name.
2602  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2603                               DEnd = AnonRecord->decls_end();
2604       D != DEnd; ++D) {
2605    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2606        cast<NamedDecl>(*D)->getDeclName()) {
2607      ValueDecl *VD = cast<ValueDecl>(*D);
2608      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2609                                       VD->getLocation(), diagKind)) {
2610        // C++ [class.union]p2:
2611        //   The names of the members of an anonymous union shall be
2612        //   distinct from the names of any other entity in the
2613        //   scope in which the anonymous union is declared.
2614        Invalid = true;
2615      } else {
2616        // C++ [class.union]p2:
2617        //   For the purpose of name lookup, after the anonymous union
2618        //   definition, the members of the anonymous union are
2619        //   considered to have been defined in the scope in which the
2620        //   anonymous union is declared.
2621        unsigned OldChainingSize = Chaining.size();
2622        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2623          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2624               PE = IF->chain_end(); PI != PE; ++PI)
2625            Chaining.push_back(*PI);
2626        else
2627          Chaining.push_back(VD);
2628
2629        assert(Chaining.size() >= 2);
2630        NamedDecl **NamedChain =
2631          new (SemaRef.Context)NamedDecl*[Chaining.size()];
2632        for (unsigned i = 0; i < Chaining.size(); i++)
2633          NamedChain[i] = Chaining[i];
2634
2635        IndirectFieldDecl* IndirectField =
2636          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2637                                    VD->getIdentifier(), VD->getType(),
2638                                    NamedChain, Chaining.size());
2639
2640        IndirectField->setAccess(AS);
2641        IndirectField->setImplicit();
2642        SemaRef.PushOnScopeChains(IndirectField, S);
2643
2644        // That includes picking up the appropriate access specifier.
2645        if (AS != AS_none) IndirectField->setAccess(AS);
2646
2647        Chaining.resize(OldChainingSize);
2648      }
2649    }
2650  }
2651
2652  return Invalid;
2653}
2654
2655/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2656/// a VarDecl::StorageClass. Any error reporting is up to the caller:
2657/// illegal input values are mapped to SC_None.
2658static StorageClass
2659StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2660  switch (StorageClassSpec) {
2661  case DeclSpec::SCS_unspecified:    return SC_None;
2662  case DeclSpec::SCS_extern:         return SC_Extern;
2663  case DeclSpec::SCS_static:         return SC_Static;
2664  case DeclSpec::SCS_auto:           return SC_Auto;
2665  case DeclSpec::SCS_register:       return SC_Register;
2666  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2667    // Illegal SCSs map to None: error reporting is up to the caller.
2668  case DeclSpec::SCS_mutable:        // Fall through.
2669  case DeclSpec::SCS_typedef:        return SC_None;
2670  }
2671  llvm_unreachable("unknown storage class specifier");
2672}
2673
2674/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2675/// a StorageClass. Any error reporting is up to the caller:
2676/// illegal input values are mapped to SC_None.
2677static StorageClass
2678StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2679  switch (StorageClassSpec) {
2680  case DeclSpec::SCS_unspecified:    return SC_None;
2681  case DeclSpec::SCS_extern:         return SC_Extern;
2682  case DeclSpec::SCS_static:         return SC_Static;
2683  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2684    // Illegal SCSs map to None: error reporting is up to the caller.
2685  case DeclSpec::SCS_auto:           // Fall through.
2686  case DeclSpec::SCS_mutable:        // Fall through.
2687  case DeclSpec::SCS_register:       // Fall through.
2688  case DeclSpec::SCS_typedef:        return SC_None;
2689  }
2690  llvm_unreachable("unknown storage class specifier");
2691}
2692
2693/// BuildAnonymousStructOrUnion - Handle the declaration of an
2694/// anonymous structure or union. Anonymous unions are a C++ feature
2695/// (C++ [class.union]) and a C11 feature; anonymous structures
2696/// are a C11 feature and GNU C++ extension.
2697Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2698                                             AccessSpecifier AS,
2699                                             RecordDecl *Record) {
2700  DeclContext *Owner = Record->getDeclContext();
2701
2702  // Diagnose whether this anonymous struct/union is an extension.
2703  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2704    Diag(Record->getLocation(), diag::ext_anonymous_union);
2705  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2706    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
2707  else if (!Record->isUnion() && !getLangOpts().C11)
2708    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
2709
2710  // C and C++ require different kinds of checks for anonymous
2711  // structs/unions.
2712  bool Invalid = false;
2713  if (getLangOpts().CPlusPlus) {
2714    const char* PrevSpec = 0;
2715    unsigned DiagID;
2716    if (Record->isUnion()) {
2717      // C++ [class.union]p6:
2718      //   Anonymous unions declared in a named namespace or in the
2719      //   global namespace shall be declared static.
2720      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2721          (isa<TranslationUnitDecl>(Owner) ||
2722           (isa<NamespaceDecl>(Owner) &&
2723            cast<NamespaceDecl>(Owner)->getDeclName()))) {
2724        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2725          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
2726
2727        // Recover by adding 'static'.
2728        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2729                               PrevSpec, DiagID);
2730      }
2731      // C++ [class.union]p6:
2732      //   A storage class is not allowed in a declaration of an
2733      //   anonymous union in a class scope.
2734      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2735               isa<RecordDecl>(Owner)) {
2736        Diag(DS.getStorageClassSpecLoc(),
2737             diag::err_anonymous_union_with_storage_spec)
2738          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2739
2740        // Recover by removing the storage specifier.
2741        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2742                               SourceLocation(),
2743                               PrevSpec, DiagID);
2744      }
2745    }
2746
2747    // Ignore const/volatile/restrict qualifiers.
2748    if (DS.getTypeQualifiers()) {
2749      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2750        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2751          << Record->isUnion() << 0
2752          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2753      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2754        Diag(DS.getVolatileSpecLoc(),
2755             diag::ext_anonymous_struct_union_qualified)
2756          << Record->isUnion() << 1
2757          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2758      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2759        Diag(DS.getRestrictSpecLoc(),
2760             diag::ext_anonymous_struct_union_qualified)
2761          << Record->isUnion() << 2
2762          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2763
2764      DS.ClearTypeQualifiers();
2765    }
2766
2767    // C++ [class.union]p2:
2768    //   The member-specification of an anonymous union shall only
2769    //   define non-static data members. [Note: nested types and
2770    //   functions cannot be declared within an anonymous union. ]
2771    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2772                                 MemEnd = Record->decls_end();
2773         Mem != MemEnd; ++Mem) {
2774      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2775        // C++ [class.union]p3:
2776        //   An anonymous union shall not have private or protected
2777        //   members (clause 11).
2778        assert(FD->getAccess() != AS_none);
2779        if (FD->getAccess() != AS_public) {
2780          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2781            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2782          Invalid = true;
2783        }
2784
2785        // C++ [class.union]p1
2786        //   An object of a class with a non-trivial constructor, a non-trivial
2787        //   copy constructor, a non-trivial destructor, or a non-trivial copy
2788        //   assignment operator cannot be a member of a union, nor can an
2789        //   array of such objects.
2790        if (CheckNontrivialField(FD))
2791          Invalid = true;
2792      } else if ((*Mem)->isImplicit()) {
2793        // Any implicit members are fine.
2794      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2795        // This is a type that showed up in an
2796        // elaborated-type-specifier inside the anonymous struct or
2797        // union, but which actually declares a type outside of the
2798        // anonymous struct or union. It's okay.
2799      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2800        if (!MemRecord->isAnonymousStructOrUnion() &&
2801            MemRecord->getDeclName()) {
2802          // Visual C++ allows type definition in anonymous struct or union.
2803          if (getLangOpts().MicrosoftExt)
2804            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2805              << (int)Record->isUnion();
2806          else {
2807            // This is a nested type declaration.
2808            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2809              << (int)Record->isUnion();
2810            Invalid = true;
2811          }
2812        }
2813      } else if (isa<AccessSpecDecl>(*Mem)) {
2814        // Any access specifier is fine.
2815      } else {
2816        // We have something that isn't a non-static data
2817        // member. Complain about it.
2818        unsigned DK = diag::err_anonymous_record_bad_member;
2819        if (isa<TypeDecl>(*Mem))
2820          DK = diag::err_anonymous_record_with_type;
2821        else if (isa<FunctionDecl>(*Mem))
2822          DK = diag::err_anonymous_record_with_function;
2823        else if (isa<VarDecl>(*Mem))
2824          DK = diag::err_anonymous_record_with_static;
2825
2826        // Visual C++ allows type definition in anonymous struct or union.
2827        if (getLangOpts().MicrosoftExt &&
2828            DK == diag::err_anonymous_record_with_type)
2829          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
2830            << (int)Record->isUnion();
2831        else {
2832          Diag((*Mem)->getLocation(), DK)
2833              << (int)Record->isUnion();
2834          Invalid = true;
2835        }
2836      }
2837    }
2838  }
2839
2840  if (!Record->isUnion() && !Owner->isRecord()) {
2841    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2842      << (int)getLangOpts().CPlusPlus;
2843    Invalid = true;
2844  }
2845
2846  // Mock up a declarator.
2847  Declarator Dc(DS, Declarator::MemberContext);
2848  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2849  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2850
2851  // Create a declaration for this anonymous struct/union.
2852  NamedDecl *Anon = 0;
2853  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2854    Anon = FieldDecl::Create(Context, OwningClass,
2855                             DS.getLocStart(),
2856                             Record->getLocation(),
2857                             /*IdentifierInfo=*/0,
2858                             Context.getTypeDeclType(Record),
2859                             TInfo,
2860                             /*BitWidth=*/0, /*Mutable=*/false,
2861                             /*HasInit=*/false);
2862    Anon->setAccess(AS);
2863    if (getLangOpts().CPlusPlus)
2864      FieldCollector->Add(cast<FieldDecl>(Anon));
2865  } else {
2866    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2867    assert(SCSpec != DeclSpec::SCS_typedef &&
2868           "Parser allowed 'typedef' as storage class VarDecl.");
2869    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2870    if (SCSpec == DeclSpec::SCS_mutable) {
2871      // mutable can only appear on non-static class members, so it's always
2872      // an error here
2873      Diag(Record->getLocation(), diag::err_mutable_nonmember);
2874      Invalid = true;
2875      SC = SC_None;
2876    }
2877    SCSpec = DS.getStorageClassSpecAsWritten();
2878    VarDecl::StorageClass SCAsWritten
2879      = StorageClassSpecToVarDeclStorageClass(SCSpec);
2880
2881    Anon = VarDecl::Create(Context, Owner,
2882                           DS.getLocStart(),
2883                           Record->getLocation(), /*IdentifierInfo=*/0,
2884                           Context.getTypeDeclType(Record),
2885                           TInfo, SC, SCAsWritten);
2886
2887    // Default-initialize the implicit variable. This initialization will be
2888    // trivial in almost all cases, except if a union member has an in-class
2889    // initializer:
2890    //   union { int n = 0; };
2891    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
2892  }
2893  Anon->setImplicit();
2894
2895  // Add the anonymous struct/union object to the current
2896  // context. We'll be referencing this object when we refer to one of
2897  // its members.
2898  Owner->addDecl(Anon);
2899
2900  // Inject the members of the anonymous struct/union into the owning
2901  // context and into the identifier resolver chain for name lookup
2902  // purposes.
2903  SmallVector<NamedDecl*, 2> Chain;
2904  Chain.push_back(Anon);
2905
2906  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2907                                          Chain, false))
2908    Invalid = true;
2909
2910  // Mark this as an anonymous struct/union type. Note that we do not
2911  // do this until after we have already checked and injected the
2912  // members of this anonymous struct/union type, because otherwise
2913  // the members could be injected twice: once by DeclContext when it
2914  // builds its lookup table, and once by
2915  // InjectAnonymousStructOrUnionMembers.
2916  Record->setAnonymousStructOrUnion(true);
2917
2918  if (Invalid)
2919    Anon->setInvalidDecl();
2920
2921  return Anon;
2922}
2923
2924/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2925/// Microsoft C anonymous structure.
2926/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2927/// Example:
2928///
2929/// struct A { int a; };
2930/// struct B { struct A; int b; };
2931///
2932/// void foo() {
2933///   B var;
2934///   var.a = 3;
2935/// }
2936///
2937Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2938                                           RecordDecl *Record) {
2939
2940  // If there is no Record, get the record via the typedef.
2941  if (!Record)
2942    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2943
2944  // Mock up a declarator.
2945  Declarator Dc(DS, Declarator::TypeNameContext);
2946  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2947  assert(TInfo && "couldn't build declarator info for anonymous struct");
2948
2949  // Create a declaration for this anonymous struct.
2950  NamedDecl* Anon = FieldDecl::Create(Context,
2951                             cast<RecordDecl>(CurContext),
2952                             DS.getLocStart(),
2953                             DS.getLocStart(),
2954                             /*IdentifierInfo=*/0,
2955                             Context.getTypeDeclType(Record),
2956                             TInfo,
2957                             /*BitWidth=*/0, /*Mutable=*/false,
2958                             /*HasInit=*/false);
2959  Anon->setImplicit();
2960
2961  // Add the anonymous struct object to the current context.
2962  CurContext->addDecl(Anon);
2963
2964  // Inject the members of the anonymous struct into the current
2965  // context and into the identifier resolver chain for name lookup
2966  // purposes.
2967  SmallVector<NamedDecl*, 2> Chain;
2968  Chain.push_back(Anon);
2969
2970  RecordDecl *RecordDef = Record->getDefinition();
2971  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2972                                                        RecordDef, AS_none,
2973                                                        Chain, true))
2974    Anon->setInvalidDecl();
2975
2976  return Anon;
2977}
2978
2979/// GetNameForDeclarator - Determine the full declaration name for the
2980/// given Declarator.
2981DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2982  return GetNameFromUnqualifiedId(D.getName());
2983}
2984
2985/// \brief Retrieves the declaration name from a parsed unqualified-id.
2986DeclarationNameInfo
2987Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2988  DeclarationNameInfo NameInfo;
2989  NameInfo.setLoc(Name.StartLocation);
2990
2991  switch (Name.getKind()) {
2992
2993  case UnqualifiedId::IK_ImplicitSelfParam:
2994  case UnqualifiedId::IK_Identifier:
2995    NameInfo.setName(Name.Identifier);
2996    NameInfo.setLoc(Name.StartLocation);
2997    return NameInfo;
2998
2999  case UnqualifiedId::IK_OperatorFunctionId:
3000    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3001                                           Name.OperatorFunctionId.Operator));
3002    NameInfo.setLoc(Name.StartLocation);
3003    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3004      = Name.OperatorFunctionId.SymbolLocations[0];
3005    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3006      = Name.EndLocation.getRawEncoding();
3007    return NameInfo;
3008
3009  case UnqualifiedId::IK_LiteralOperatorId:
3010    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3011                                                           Name.Identifier));
3012    NameInfo.setLoc(Name.StartLocation);
3013    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3014    return NameInfo;
3015
3016  case UnqualifiedId::IK_ConversionFunctionId: {
3017    TypeSourceInfo *TInfo;
3018    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3019    if (Ty.isNull())
3020      return DeclarationNameInfo();
3021    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3022                                               Context.getCanonicalType(Ty)));
3023    NameInfo.setLoc(Name.StartLocation);
3024    NameInfo.setNamedTypeInfo(TInfo);
3025    return NameInfo;
3026  }
3027
3028  case UnqualifiedId::IK_ConstructorName: {
3029    TypeSourceInfo *TInfo;
3030    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3031    if (Ty.isNull())
3032      return DeclarationNameInfo();
3033    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3034                                              Context.getCanonicalType(Ty)));
3035    NameInfo.setLoc(Name.StartLocation);
3036    NameInfo.setNamedTypeInfo(TInfo);
3037    return NameInfo;
3038  }
3039
3040  case UnqualifiedId::IK_ConstructorTemplateId: {
3041    // In well-formed code, we can only have a constructor
3042    // template-id that refers to the current context, so go there
3043    // to find the actual type being constructed.
3044    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3045    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3046      return DeclarationNameInfo();
3047
3048    // Determine the type of the class being constructed.
3049    QualType CurClassType = Context.getTypeDeclType(CurClass);
3050
3051    // FIXME: Check two things: that the template-id names the same type as
3052    // CurClassType, and that the template-id does not occur when the name
3053    // was qualified.
3054
3055    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3056                                    Context.getCanonicalType(CurClassType)));
3057    NameInfo.setLoc(Name.StartLocation);
3058    // FIXME: should we retrieve TypeSourceInfo?
3059    NameInfo.setNamedTypeInfo(0);
3060    return NameInfo;
3061  }
3062
3063  case UnqualifiedId::IK_DestructorName: {
3064    TypeSourceInfo *TInfo;
3065    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3066    if (Ty.isNull())
3067      return DeclarationNameInfo();
3068    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3069                                              Context.getCanonicalType(Ty)));
3070    NameInfo.setLoc(Name.StartLocation);
3071    NameInfo.setNamedTypeInfo(TInfo);
3072    return NameInfo;
3073  }
3074
3075  case UnqualifiedId::IK_TemplateId: {
3076    TemplateName TName = Name.TemplateId->Template.get();
3077    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3078    return Context.getNameForTemplate(TName, TNameLoc);
3079  }
3080
3081  } // switch (Name.getKind())
3082
3083  llvm_unreachable("Unknown name kind");
3084}
3085
3086static QualType getCoreType(QualType Ty) {
3087  do {
3088    if (Ty->isPointerType() || Ty->isReferenceType())
3089      Ty = Ty->getPointeeType();
3090    else if (Ty->isArrayType())
3091      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3092    else
3093      return Ty.withoutLocalFastQualifiers();
3094  } while (true);
3095}
3096
3097/// hasSimilarParameters - Determine whether the C++ functions Declaration
3098/// and Definition have "nearly" matching parameters. This heuristic is
3099/// used to improve diagnostics in the case where an out-of-line function
3100/// definition doesn't match any declaration within the class or namespace.
3101/// Also sets Params to the list of indices to the parameters that differ
3102/// between the declaration and the definition. If hasSimilarParameters
3103/// returns true and Params is empty, then all of the parameters match.
3104static bool hasSimilarParameters(ASTContext &Context,
3105                                     FunctionDecl *Declaration,
3106                                     FunctionDecl *Definition,
3107                                     llvm::SmallVectorImpl<unsigned> &Params) {
3108  Params.clear();
3109  if (Declaration->param_size() != Definition->param_size())
3110    return false;
3111  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3112    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3113    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3114
3115    // The parameter types are identical
3116    if (Context.hasSameType(DefParamTy, DeclParamTy))
3117      continue;
3118
3119    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3120    QualType DefParamBaseTy = getCoreType(DefParamTy);
3121    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3122    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3123
3124    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3125        (DeclTyName && DeclTyName == DefTyName))
3126      Params.push_back(Idx);
3127    else  // The two parameters aren't even close
3128      return false;
3129  }
3130
3131  return true;
3132}
3133
3134/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3135/// declarator needs to be rebuilt in the current instantiation.
3136/// Any bits of declarator which appear before the name are valid for
3137/// consideration here.  That's specifically the type in the decl spec
3138/// and the base type in any member-pointer chunks.
3139static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3140                                                    DeclarationName Name) {
3141  // The types we specifically need to rebuild are:
3142  //   - typenames, typeofs, and decltypes
3143  //   - types which will become injected class names
3144  // Of course, we also need to rebuild any type referencing such a
3145  // type.  It's safest to just say "dependent", but we call out a
3146  // few cases here.
3147
3148  DeclSpec &DS = D.getMutableDeclSpec();
3149  switch (DS.getTypeSpecType()) {
3150  case DeclSpec::TST_typename:
3151  case DeclSpec::TST_typeofType:
3152  case DeclSpec::TST_decltype:
3153  case DeclSpec::TST_underlyingType:
3154  case DeclSpec::TST_atomic: {
3155    // Grab the type from the parser.
3156    TypeSourceInfo *TSI = 0;
3157    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3158    if (T.isNull() || !T->isDependentType()) break;
3159
3160    // Make sure there's a type source info.  This isn't really much
3161    // of a waste; most dependent types should have type source info
3162    // attached already.
3163    if (!TSI)
3164      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3165
3166    // Rebuild the type in the current instantiation.
3167    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3168    if (!TSI) return true;
3169
3170    // Store the new type back in the decl spec.
3171    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3172    DS.UpdateTypeRep(LocType);
3173    break;
3174  }
3175
3176  case DeclSpec::TST_typeofExpr: {
3177    Expr *E = DS.getRepAsExpr();
3178    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3179    if (Result.isInvalid()) return true;
3180    DS.UpdateExprRep(Result.get());
3181    break;
3182  }
3183
3184  default:
3185    // Nothing to do for these decl specs.
3186    break;
3187  }
3188
3189  // It doesn't matter what order we do this in.
3190  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3191    DeclaratorChunk &Chunk = D.getTypeObject(I);
3192
3193    // The only type information in the declarator which can come
3194    // before the declaration name is the base type of a member
3195    // pointer.
3196    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3197      continue;
3198
3199    // Rebuild the scope specifier in-place.
3200    CXXScopeSpec &SS = Chunk.Mem.Scope();
3201    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3202      return true;
3203  }
3204
3205  return false;
3206}
3207
3208Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3209  D.setFunctionDefinitionKind(FDK_Declaration);
3210  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3211
3212  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3213      Dcl->getDeclContext()->isFileContext())
3214    Dcl->setTopLevelDeclInObjCContainer();
3215
3216  return Dcl;
3217}
3218
3219/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3220///   If T is the name of a class, then each of the following shall have a
3221///   name different from T:
3222///     - every static data member of class T;
3223///     - every member function of class T
3224///     - every member of class T that is itself a type;
3225/// \returns true if the declaration name violates these rules.
3226bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3227                                   DeclarationNameInfo NameInfo) {
3228  DeclarationName Name = NameInfo.getName();
3229
3230  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3231    if (Record->getIdentifier() && Record->getDeclName() == Name) {
3232      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3233      return true;
3234    }
3235
3236  return false;
3237}
3238
3239Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3240                             MultiTemplateParamsArg TemplateParamLists) {
3241  // TODO: consider using NameInfo for diagnostic.
3242  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3243  DeclarationName Name = NameInfo.getName();
3244
3245  // All of these full declarators require an identifier.  If it doesn't have
3246  // one, the ParsedFreeStandingDeclSpec action should be used.
3247  if (!Name) {
3248    if (!D.isInvalidType())  // Reject this if we think it is valid.
3249      Diag(D.getDeclSpec().getLocStart(),
3250           diag::err_declarator_need_ident)
3251        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3252    return 0;
3253  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3254    return 0;
3255
3256  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3257  // we find one that is.
3258  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3259         (S->getFlags() & Scope::TemplateParamScope) != 0)
3260    S = S->getParent();
3261
3262  DeclContext *DC = CurContext;
3263  if (D.getCXXScopeSpec().isInvalid())
3264    D.setInvalidType();
3265  else if (D.getCXXScopeSpec().isSet()) {
3266    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3267                                        UPPC_DeclarationQualifier))
3268      return 0;
3269
3270    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3271    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3272    if (!DC) {
3273      // If we could not compute the declaration context, it's because the
3274      // declaration context is dependent but does not refer to a class,
3275      // class template, or class template partial specialization. Complain
3276      // and return early, to avoid the coming semantic disaster.
3277      Diag(D.getIdentifierLoc(),
3278           diag::err_template_qualified_declarator_no_match)
3279        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3280        << D.getCXXScopeSpec().getRange();
3281      return 0;
3282    }
3283    bool IsDependentContext = DC->isDependentContext();
3284
3285    if (!IsDependentContext &&
3286        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3287      return 0;
3288
3289    if (isa<CXXRecordDecl>(DC)) {
3290      if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3291        Diag(D.getIdentifierLoc(),
3292             diag::err_member_def_undefined_record)
3293          << Name << DC << D.getCXXScopeSpec().getRange();
3294        D.setInvalidType();
3295      } else if (isa<CXXRecordDecl>(CurContext) &&
3296                 !D.getDeclSpec().isFriendSpecified()) {
3297        // The user provided a superfluous scope specifier inside a class
3298        // definition:
3299        //
3300        // class X {
3301        //   void X::f();
3302        // };
3303        if (CurContext->Equals(DC)) {
3304          Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3305            << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3306        } else {
3307          Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3308            << Name << D.getCXXScopeSpec().getRange();
3309
3310          // C++ constructors and destructors with incorrect scopes can break
3311          // our AST invariants by having the wrong underlying types. If
3312          // that's the case, then drop this declaration entirely.
3313          if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3314               Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3315              !Context.hasSameType(Name.getCXXNameType(),
3316                 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))))
3317            return 0;
3318        }
3319
3320        // Pretend that this qualifier was not here.
3321        D.getCXXScopeSpec().clear();
3322      }
3323    }
3324
3325    // Check whether we need to rebuild the type of the given
3326    // declaration in the current instantiation.
3327    if (EnteringContext && IsDependentContext &&
3328        TemplateParamLists.size() != 0) {
3329      ContextRAII SavedContext(*this, DC);
3330      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3331        D.setInvalidType();
3332    }
3333  }
3334
3335  if (DiagnoseClassNameShadow(DC, NameInfo))
3336    // If this is a typedef, we'll end up spewing multiple diagnostics.
3337    // Just return early; it's safer.
3338    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3339      return 0;
3340
3341  NamedDecl *New;
3342
3343  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3344  QualType R = TInfo->getType();
3345
3346  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3347                                      UPPC_DeclarationType))
3348    D.setInvalidType();
3349
3350  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3351                        ForRedeclaration);
3352
3353  // See if this is a redefinition of a variable in the same scope.
3354  if (!D.getCXXScopeSpec().isSet()) {
3355    bool IsLinkageLookup = false;
3356
3357    // If the declaration we're planning to build will be a function
3358    // or object with linkage, then look for another declaration with
3359    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3360    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3361      /* Do nothing*/;
3362    else if (R->isFunctionType()) {
3363      if (CurContext->isFunctionOrMethod() ||
3364          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3365        IsLinkageLookup = true;
3366    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3367      IsLinkageLookup = true;
3368    else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3369             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3370      IsLinkageLookup = true;
3371
3372    if (IsLinkageLookup)
3373      Previous.clear(LookupRedeclarationWithLinkage);
3374
3375    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3376  } else { // Something like "int foo::x;"
3377    LookupQualifiedName(Previous, DC);
3378
3379    // Don't consider using declarations as previous declarations for
3380    // out-of-line members.
3381    RemoveUsingDecls(Previous);
3382
3383    // C++ 7.3.1.2p2:
3384    // Members (including explicit specializations of templates) of a named
3385    // namespace can also be defined outside that namespace by explicit
3386    // qualification of the name being defined, provided that the entity being
3387    // defined was already declared in the namespace and the definition appears
3388    // after the point of declaration in a namespace that encloses the
3389    // declarations namespace.
3390    //
3391    // Note that we only check the context at this point. We don't yet
3392    // have enough information to make sure that PrevDecl is actually
3393    // the declaration we want to match. For example, given:
3394    //
3395    //   class X {
3396    //     void f();
3397    //     void f(float);
3398    //   };
3399    //
3400    //   void X::f(int) { } // ill-formed
3401    //
3402    // In this case, PrevDecl will point to the overload set
3403    // containing the two f's declared in X, but neither of them
3404    // matches.
3405
3406    // First check whether we named the global scope.
3407    if (isa<TranslationUnitDecl>(DC)) {
3408      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
3409        << Name << D.getCXXScopeSpec().getRange();
3410    } else {
3411      DeclContext *Cur = CurContext;
3412      while (isa<LinkageSpecDecl>(Cur))
3413        Cur = Cur->getParent();
3414      if (!Cur->Encloses(DC)) {
3415        // The qualifying scope doesn't enclose the original declaration.
3416        // Emit diagnostic based on current scope.
3417        SourceLocation L = D.getIdentifierLoc();
3418        SourceRange R = D.getCXXScopeSpec().getRange();
3419        if (isa<FunctionDecl>(Cur))
3420          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3421        else
3422          Diag(L, diag::err_invalid_declarator_scope)
3423            << Name << cast<NamedDecl>(DC) << R;
3424        D.setInvalidType();
3425      }
3426
3427      // C++11 8.3p1:
3428      // ... "The nested-name-specifier of the qualified declarator-id shall
3429      // not begin with a decltype-specifer"
3430      NestedNameSpecifierLoc SpecLoc =
3431            D.getCXXScopeSpec().getWithLocInContext(Context);
3432      assert(SpecLoc && "A non-empty CXXScopeSpec should have a non-empty "
3433                        "NestedNameSpecifierLoc");
3434      while (SpecLoc.getPrefix())
3435        SpecLoc = SpecLoc.getPrefix();
3436      if (dyn_cast_or_null<DecltypeType>(
3437            SpecLoc.getNestedNameSpecifier()->getAsType()))
3438        Diag(SpecLoc.getBeginLoc(), diag::err_decltype_in_declarator)
3439          << SpecLoc.getTypeLoc().getSourceRange();
3440    }
3441  }
3442
3443  if (Previous.isSingleResult() &&
3444      Previous.getFoundDecl()->isTemplateParameter()) {
3445    // Maybe we will complain about the shadowed template parameter.
3446    if (!D.isInvalidType())
3447      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3448                                      Previous.getFoundDecl());
3449
3450    // Just pretend that we didn't see the previous declaration.
3451    Previous.clear();
3452  }
3453
3454  // In C++, the previous declaration we find might be a tag type
3455  // (class or enum). In this case, the new declaration will hide the
3456  // tag type. Note that this does does not apply if we're declaring a
3457  // typedef (C++ [dcl.typedef]p4).
3458  if (Previous.isSingleTagDecl() &&
3459      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3460    Previous.clear();
3461
3462  bool AddToScope = true;
3463  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3464    if (TemplateParamLists.size()) {
3465      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3466      return 0;
3467    }
3468
3469    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3470  } else if (R->isFunctionType()) {
3471    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3472                                  move(TemplateParamLists),
3473                                  AddToScope);
3474  } else {
3475    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3476                                  move(TemplateParamLists));
3477  }
3478
3479  if (New == 0)
3480    return 0;
3481
3482  // If this has an identifier and is not an invalid redeclaration or
3483  // function template specialization, add it to the scope stack.
3484  if (New->getDeclName() && AddToScope &&
3485       !(D.isRedeclaration() && New->isInvalidDecl()))
3486    PushOnScopeChains(New, S);
3487
3488  return New;
3489}
3490
3491/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3492/// types into constant array types in certain situations which would otherwise
3493/// be errors (for GCC compatibility).
3494static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3495                                                    ASTContext &Context,
3496                                                    bool &SizeIsNegative,
3497                                                    llvm::APSInt &Oversized) {
3498  // This method tries to turn a variable array into a constant
3499  // array even when the size isn't an ICE.  This is necessary
3500  // for compatibility with code that depends on gcc's buggy
3501  // constant expression folding, like struct {char x[(int)(char*)2];}
3502  SizeIsNegative = false;
3503  Oversized = 0;
3504
3505  if (T->isDependentType())
3506    return QualType();
3507
3508  QualifierCollector Qs;
3509  const Type *Ty = Qs.strip(T);
3510
3511  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3512    QualType Pointee = PTy->getPointeeType();
3513    QualType FixedType =
3514        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3515                                            Oversized);
3516    if (FixedType.isNull()) return FixedType;
3517    FixedType = Context.getPointerType(FixedType);
3518    return Qs.apply(Context, FixedType);
3519  }
3520  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3521    QualType Inner = PTy->getInnerType();
3522    QualType FixedType =
3523        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3524                                            Oversized);
3525    if (FixedType.isNull()) return FixedType;
3526    FixedType = Context.getParenType(FixedType);
3527    return Qs.apply(Context, FixedType);
3528  }
3529
3530  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3531  if (!VLATy)
3532    return QualType();
3533  // FIXME: We should probably handle this case
3534  if (VLATy->getElementType()->isVariablyModifiedType())
3535    return QualType();
3536
3537  llvm::APSInt Res;
3538  if (!VLATy->getSizeExpr() ||
3539      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3540    return QualType();
3541
3542  // Check whether the array size is negative.
3543  if (Res.isSigned() && Res.isNegative()) {
3544    SizeIsNegative = true;
3545    return QualType();
3546  }
3547
3548  // Check whether the array is too large to be addressed.
3549  unsigned ActiveSizeBits
3550    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3551                                              Res);
3552  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3553    Oversized = Res;
3554    return QualType();
3555  }
3556
3557  return Context.getConstantArrayType(VLATy->getElementType(),
3558                                      Res, ArrayType::Normal, 0);
3559}
3560
3561/// \brief Register the given locally-scoped external C declaration so
3562/// that it can be found later for redeclarations
3563void
3564Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3565                                       const LookupResult &Previous,
3566                                       Scope *S) {
3567  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3568         "Decl is not a locally-scoped decl!");
3569  // Note that we have a locally-scoped external with this name.
3570  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3571
3572  if (!Previous.isSingleResult())
3573    return;
3574
3575  NamedDecl *PrevDecl = Previous.getFoundDecl();
3576
3577  // If there was a previous declaration of this variable, it may be
3578  // in our identifier chain. Update the identifier chain with the new
3579  // declaration.
3580  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3581    // The previous declaration was found on the identifer resolver
3582    // chain, so remove it from its scope.
3583
3584    if (S->isDeclScope(PrevDecl)) {
3585      // Special case for redeclarations in the SAME scope.
3586      // Because this declaration is going to be added to the identifier chain
3587      // later, we should temporarily take it OFF the chain.
3588      IdResolver.RemoveDecl(ND);
3589
3590    } else {
3591      // Find the scope for the original declaration.
3592      while (S && !S->isDeclScope(PrevDecl))
3593        S = S->getParent();
3594    }
3595
3596    if (S)
3597      S->RemoveDecl(PrevDecl);
3598  }
3599}
3600
3601llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3602Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3603  if (ExternalSource) {
3604    // Load locally-scoped external decls from the external source.
3605    SmallVector<NamedDecl *, 4> Decls;
3606    ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3607    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3608      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3609        = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3610      if (Pos == LocallyScopedExternalDecls.end())
3611        LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3612    }
3613  }
3614
3615  return LocallyScopedExternalDecls.find(Name);
3616}
3617
3618/// \brief Diagnose function specifiers on a declaration of an identifier that
3619/// does not identify a function.
3620void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3621  // FIXME: We should probably indicate the identifier in question to avoid
3622  // confusion for constructs like "inline int a(), b;"
3623  if (D.getDeclSpec().isInlineSpecified())
3624    Diag(D.getDeclSpec().getInlineSpecLoc(),
3625         diag::err_inline_non_function);
3626
3627  if (D.getDeclSpec().isVirtualSpecified())
3628    Diag(D.getDeclSpec().getVirtualSpecLoc(),
3629         diag::err_virtual_non_function);
3630
3631  if (D.getDeclSpec().isExplicitSpecified())
3632    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3633         diag::err_explicit_non_function);
3634}
3635
3636NamedDecl*
3637Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3638                             TypeSourceInfo *TInfo, LookupResult &Previous) {
3639  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3640  if (D.getCXXScopeSpec().isSet()) {
3641    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3642      << D.getCXXScopeSpec().getRange();
3643    D.setInvalidType();
3644    // Pretend we didn't see the scope specifier.
3645    DC = CurContext;
3646    Previous.clear();
3647  }
3648
3649  if (getLangOpts().CPlusPlus) {
3650    // Check that there are no default arguments (C++ only).
3651    CheckExtraCXXDefaultArguments(D);
3652  }
3653
3654  DiagnoseFunctionSpecifiers(D);
3655
3656  if (D.getDeclSpec().isThreadSpecified())
3657    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3658  if (D.getDeclSpec().isConstexprSpecified())
3659    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3660      << 1;
3661
3662  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3663    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3664      << D.getName().getSourceRange();
3665    return 0;
3666  }
3667
3668  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
3669  if (!NewTD) return 0;
3670
3671  // Handle attributes prior to checking for duplicates in MergeVarDecl
3672  ProcessDeclAttributes(S, NewTD, D);
3673
3674  CheckTypedefForVariablyModifiedType(S, NewTD);
3675
3676  bool Redeclaration = D.isRedeclaration();
3677  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3678  D.setRedeclaration(Redeclaration);
3679  return ND;
3680}
3681
3682void
3683Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
3684  // C99 6.7.7p2: If a typedef name specifies a variably modified type
3685  // then it shall have block scope.
3686  // Note that variably modified types must be fixed before merging the decl so
3687  // that redeclarations will match.
3688  QualType T = NewTD->getUnderlyingType();
3689  if (T->isVariablyModifiedType()) {
3690    getCurFunction()->setHasBranchProtectedScope();
3691
3692    if (S->getFnParent() == 0) {
3693      bool SizeIsNegative;
3694      llvm::APSInt Oversized;
3695      QualType FixedTy =
3696          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3697                                              Oversized);
3698      if (!FixedTy.isNull()) {
3699        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
3700        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
3701      } else {
3702        if (SizeIsNegative)
3703          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
3704        else if (T->isVariableArrayType())
3705          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
3706        else if (Oversized.getBoolValue())
3707          Diag(NewTD->getLocation(), diag::err_array_too_large)
3708            << Oversized.toString(10);
3709        else
3710          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
3711        NewTD->setInvalidDecl();
3712      }
3713    }
3714  }
3715}
3716
3717
3718/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3719/// declares a typedef-name, either using the 'typedef' type specifier or via
3720/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3721NamedDecl*
3722Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3723                           LookupResult &Previous, bool &Redeclaration) {
3724  // Merge the decl with the existing one if appropriate. If the decl is
3725  // in an outer scope, it isn't the same thing.
3726  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
3727                       /*ExplicitInstantiationOrSpecialization=*/false);
3728  if (!Previous.empty()) {
3729    Redeclaration = true;
3730    MergeTypedefNameDecl(NewTD, Previous);
3731  }
3732
3733  // If this is the C FILE type, notify the AST context.
3734  if (IdentifierInfo *II = NewTD->getIdentifier())
3735    if (!NewTD->isInvalidDecl() &&
3736        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
3737      if (II->isStr("FILE"))
3738        Context.setFILEDecl(NewTD);
3739      else if (II->isStr("jmp_buf"))
3740        Context.setjmp_bufDecl(NewTD);
3741      else if (II->isStr("sigjmp_buf"))
3742        Context.setsigjmp_bufDecl(NewTD);
3743      else if (II->isStr("ucontext_t"))
3744        Context.setucontext_tDecl(NewTD);
3745      else if (II->isStr("__builtin_va_list"))
3746        Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
3747    }
3748
3749  return NewTD;
3750}
3751
3752/// \brief Determines whether the given declaration is an out-of-scope
3753/// previous declaration.
3754///
3755/// This routine should be invoked when name lookup has found a
3756/// previous declaration (PrevDecl) that is not in the scope where a
3757/// new declaration by the same name is being introduced. If the new
3758/// declaration occurs in a local scope, previous declarations with
3759/// linkage may still be considered previous declarations (C99
3760/// 6.2.2p4-5, C++ [basic.link]p6).
3761///
3762/// \param PrevDecl the previous declaration found by name
3763/// lookup
3764///
3765/// \param DC the context in which the new declaration is being
3766/// declared.
3767///
3768/// \returns true if PrevDecl is an out-of-scope previous declaration
3769/// for a new delcaration with the same name.
3770static bool
3771isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3772                                ASTContext &Context) {
3773  if (!PrevDecl)
3774    return false;
3775
3776  if (!PrevDecl->hasLinkage())
3777    return false;
3778
3779  if (Context.getLangOpts().CPlusPlus) {
3780    // C++ [basic.link]p6:
3781    //   If there is a visible declaration of an entity with linkage
3782    //   having the same name and type, ignoring entities declared
3783    //   outside the innermost enclosing namespace scope, the block
3784    //   scope declaration declares that same entity and receives the
3785    //   linkage of the previous declaration.
3786    DeclContext *OuterContext = DC->getRedeclContext();
3787    if (!OuterContext->isFunctionOrMethod())
3788      // This rule only applies to block-scope declarations.
3789      return false;
3790
3791    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3792    if (PrevOuterContext->isRecord())
3793      // We found a member function: ignore it.
3794      return false;
3795
3796    // Find the innermost enclosing namespace for the new and
3797    // previous declarations.
3798    OuterContext = OuterContext->getEnclosingNamespaceContext();
3799    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
3800
3801    // The previous declaration is in a different namespace, so it
3802    // isn't the same function.
3803    if (!OuterContext->Equals(PrevOuterContext))
3804      return false;
3805  }
3806
3807  return true;
3808}
3809
3810static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3811  CXXScopeSpec &SS = D.getCXXScopeSpec();
3812  if (!SS.isSet()) return;
3813  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
3814}
3815
3816bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3817  QualType type = decl->getType();
3818  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3819  if (lifetime == Qualifiers::OCL_Autoreleasing) {
3820    // Various kinds of declaration aren't allowed to be __autoreleasing.
3821    unsigned kind = -1U;
3822    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3823      if (var->hasAttr<BlocksAttr>())
3824        kind = 0; // __block
3825      else if (!var->hasLocalStorage())
3826        kind = 1; // global
3827    } else if (isa<ObjCIvarDecl>(decl)) {
3828      kind = 3; // ivar
3829    } else if (isa<FieldDecl>(decl)) {
3830      kind = 2; // field
3831    }
3832
3833    if (kind != -1U) {
3834      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3835        << kind;
3836    }
3837  } else if (lifetime == Qualifiers::OCL_None) {
3838    // Try to infer lifetime.
3839    if (!type->isObjCLifetimeType())
3840      return false;
3841
3842    lifetime = type->getObjCARCImplicitLifetime();
3843    type = Context.getLifetimeQualifiedType(type, lifetime);
3844    decl->setType(type);
3845  }
3846
3847  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3848    // Thread-local variables cannot have lifetime.
3849    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3850        var->isThreadSpecified()) {
3851      Diag(var->getLocation(), diag::err_arc_thread_ownership)
3852        << var->getType();
3853      return true;
3854    }
3855  }
3856
3857  return false;
3858}
3859
3860NamedDecl*
3861Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3862                              TypeSourceInfo *TInfo, LookupResult &Previous,
3863                              MultiTemplateParamsArg TemplateParamLists) {
3864  QualType R = TInfo->getType();
3865  DeclarationName Name = GetNameForDeclarator(D).getName();
3866
3867  // Check that there are no default arguments (C++ only).
3868  if (getLangOpts().CPlusPlus)
3869    CheckExtraCXXDefaultArguments(D);
3870
3871  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3872  assert(SCSpec != DeclSpec::SCS_typedef &&
3873         "Parser allowed 'typedef' as storage class VarDecl.");
3874  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3875  if (SCSpec == DeclSpec::SCS_mutable) {
3876    // mutable can only appear on non-static class members, so it's always
3877    // an error here
3878    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
3879    D.setInvalidType();
3880    SC = SC_None;
3881  }
3882  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3883  VarDecl::StorageClass SCAsWritten
3884    = StorageClassSpecToVarDeclStorageClass(SCSpec);
3885
3886  IdentifierInfo *II = Name.getAsIdentifierInfo();
3887  if (!II) {
3888    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3889      << Name;
3890    return 0;
3891  }
3892
3893  DiagnoseFunctionSpecifiers(D);
3894
3895  if (!DC->isRecord() && S->getFnParent() == 0) {
3896    // C99 6.9p2: The storage-class specifiers auto and register shall not
3897    // appear in the declaration specifiers in an external declaration.
3898    if (SC == SC_Auto || SC == SC_Register) {
3899
3900      // If this is a register variable with an asm label specified, then this
3901      // is a GNU extension.
3902      if (SC == SC_Register && D.getAsmLabel())
3903        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3904      else
3905        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
3906      D.setInvalidType();
3907    }
3908  }
3909
3910  if (getLangOpts().OpenCL) {
3911    // Set up the special work-group-local storage class for variables in the
3912    // OpenCL __local address space.
3913    if (R.getAddressSpace() == LangAS::opencl_local)
3914      SC = SC_OpenCLWorkGroupLocal;
3915  }
3916
3917  bool isExplicitSpecialization = false;
3918  VarDecl *NewVD;
3919  if (!getLangOpts().CPlusPlus) {
3920    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
3921                            D.getIdentifierLoc(), II,
3922                            R, TInfo, SC, SCAsWritten);
3923
3924    if (D.isInvalidType())
3925      NewVD->setInvalidDecl();
3926  } else {
3927    if (DC->isRecord() && !CurContext->isRecord()) {
3928      // This is an out-of-line definition of a static data member.
3929      if (SC == SC_Static) {
3930        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3931             diag::err_static_out_of_line)
3932          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3933      } else if (SC == SC_None)
3934        SC = SC_Static;
3935    }
3936    if (SC == SC_Static && CurContext->isRecord()) {
3937      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3938        if (RD->isLocalClass())
3939          Diag(D.getIdentifierLoc(),
3940               diag::err_static_data_member_not_allowed_in_local_class)
3941            << Name << RD->getDeclName();
3942
3943        // C++98 [class.union]p1: If a union contains a static data member,
3944        // the program is ill-formed. C++11 drops this restriction.
3945        if (RD->isUnion())
3946          Diag(D.getIdentifierLoc(),
3947               getLangOpts().CPlusPlus0x
3948                 ? diag::warn_cxx98_compat_static_data_member_in_union
3949                 : diag::ext_static_data_member_in_union) << Name;
3950        // We conservatively disallow static data members in anonymous structs.
3951        else if (!RD->getDeclName())
3952          Diag(D.getIdentifierLoc(),
3953               diag::err_static_data_member_not_allowed_in_anon_struct)
3954            << Name << RD->isUnion();
3955      }
3956    }
3957
3958    // Match up the template parameter lists with the scope specifier, then
3959    // determine whether we have a template or a template specialization.
3960    isExplicitSpecialization = false;
3961    bool Invalid = false;
3962    if (TemplateParameterList *TemplateParams
3963        = MatchTemplateParametersToScopeSpecifier(
3964                                  D.getDeclSpec().getLocStart(),
3965                                                  D.getIdentifierLoc(),
3966                                                  D.getCXXScopeSpec(),
3967                                                  TemplateParamLists.get(),
3968                                                  TemplateParamLists.size(),
3969                                                  /*never a friend*/ false,
3970                                                  isExplicitSpecialization,
3971                                                  Invalid)) {
3972      if (TemplateParams->size() > 0) {
3973        // There is no such thing as a variable template.
3974        Diag(D.getIdentifierLoc(), diag::err_template_variable)
3975          << II
3976          << SourceRange(TemplateParams->getTemplateLoc(),
3977                         TemplateParams->getRAngleLoc());
3978        return 0;
3979      } else {
3980        // There is an extraneous 'template<>' for this variable. Complain
3981        // about it, but allow the declaration of the variable.
3982        Diag(TemplateParams->getTemplateLoc(),
3983             diag::err_template_variable_noparams)
3984          << II
3985          << SourceRange(TemplateParams->getTemplateLoc(),
3986                         TemplateParams->getRAngleLoc());
3987      }
3988    }
3989
3990    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
3991                            D.getIdentifierLoc(), II,
3992                            R, TInfo, SC, SCAsWritten);
3993
3994    // If this decl has an auto type in need of deduction, make a note of the
3995    // Decl so we can diagnose uses of it in its own initializer.
3996    if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3997        R->getContainedAutoType())
3998      ParsingInitForAutoVars.insert(NewVD);
3999
4000    if (D.isInvalidType() || Invalid)
4001      NewVD->setInvalidDecl();
4002
4003    SetNestedNameSpecifier(NewVD, D);
4004
4005    if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4006      NewVD->setTemplateParameterListsInfo(Context,
4007                                           TemplateParamLists.size(),
4008                                           TemplateParamLists.release());
4009    }
4010
4011    if (D.getDeclSpec().isConstexprSpecified())
4012      NewVD->setConstexpr(true);
4013  }
4014
4015  // Set the lexical context. If the declarator has a C++ scope specifier, the
4016  // lexical context will be different from the semantic context.
4017  NewVD->setLexicalDeclContext(CurContext);
4018
4019  if (D.getDeclSpec().isThreadSpecified()) {
4020    if (NewVD->hasLocalStorage())
4021      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4022    else if (!Context.getTargetInfo().isTLSSupported())
4023      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4024    else
4025      NewVD->setThreadSpecified(true);
4026  }
4027
4028  if (D.getDeclSpec().isModulePrivateSpecified()) {
4029    if (isExplicitSpecialization)
4030      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4031        << 2
4032        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4033    else if (NewVD->hasLocalStorage())
4034      Diag(NewVD->getLocation(), diag::err_module_private_local)
4035        << 0 << NewVD->getDeclName()
4036        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4037        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4038    else
4039      NewVD->setModulePrivate();
4040  }
4041
4042  // Handle attributes prior to checking for duplicates in MergeVarDecl
4043  ProcessDeclAttributes(S, NewVD, D);
4044
4045  // In auto-retain/release, infer strong retension for variables of
4046  // retainable type.
4047  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4048    NewVD->setInvalidDecl();
4049
4050  // Handle GNU asm-label extension (encoded as an attribute).
4051  if (Expr *E = (Expr*)D.getAsmLabel()) {
4052    // The parser guarantees this is a string.
4053    StringLiteral *SE = cast<StringLiteral>(E);
4054    StringRef Label = SE->getString();
4055    if (S->getFnParent() != 0) {
4056      switch (SC) {
4057      case SC_None:
4058      case SC_Auto:
4059        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4060        break;
4061      case SC_Register:
4062        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4063          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4064        break;
4065      case SC_Static:
4066      case SC_Extern:
4067      case SC_PrivateExtern:
4068      case SC_OpenCLWorkGroupLocal:
4069        break;
4070      }
4071    }
4072
4073    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4074                                                Context, Label));
4075  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4076    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4077      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4078    if (I != ExtnameUndeclaredIdentifiers.end()) {
4079      NewVD->addAttr(I->second);
4080      ExtnameUndeclaredIdentifiers.erase(I);
4081    }
4082  }
4083
4084  // Diagnose shadowed variables before filtering for scope.
4085  if (!D.getCXXScopeSpec().isSet())
4086    CheckShadow(S, NewVD, Previous);
4087
4088  // Don't consider existing declarations that are in a different
4089  // scope and are out-of-semantic-context declarations (if the new
4090  // declaration has linkage).
4091  FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4092                       isExplicitSpecialization);
4093
4094  if (!getLangOpts().CPlusPlus) {
4095    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4096  } else {
4097    // Merge the decl with the existing one if appropriate.
4098    if (!Previous.empty()) {
4099      if (Previous.isSingleResult() &&
4100          isa<FieldDecl>(Previous.getFoundDecl()) &&
4101          D.getCXXScopeSpec().isSet()) {
4102        // The user tried to define a non-static data member
4103        // out-of-line (C++ [dcl.meaning]p1).
4104        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4105          << D.getCXXScopeSpec().getRange();
4106        Previous.clear();
4107        NewVD->setInvalidDecl();
4108      }
4109    } else if (D.getCXXScopeSpec().isSet()) {
4110      // No previous declaration in the qualifying scope.
4111      Diag(D.getIdentifierLoc(), diag::err_no_member)
4112        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4113        << D.getCXXScopeSpec().getRange();
4114      NewVD->setInvalidDecl();
4115    }
4116
4117    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4118
4119    // This is an explicit specialization of a static data member. Check it.
4120    if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4121        CheckMemberSpecialization(NewVD, Previous))
4122      NewVD->setInvalidDecl();
4123  }
4124
4125  // attributes declared post-definition are currently ignored
4126  // FIXME: This should be handled in attribute merging, not
4127  // here.
4128  if (Previous.isSingleResult()) {
4129    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4130    if (Def && (Def = Def->getDefinition()) &&
4131        Def != NewVD && D.hasAttributes()) {
4132      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4133      Diag(Def->getLocation(), diag::note_previous_definition);
4134    }
4135  }
4136
4137  // If this is a locally-scoped extern C variable, update the map of
4138  // such variables.
4139  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4140      !NewVD->isInvalidDecl())
4141    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4142
4143  // If there's a #pragma GCC visibility in scope, and this isn't a class
4144  // member, set the visibility of this variable.
4145  if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4146    AddPushedVisibilityAttribute(NewVD);
4147
4148  MarkUnusedFileScopedDecl(NewVD);
4149
4150  return NewVD;
4151}
4152
4153/// \brief Diagnose variable or built-in function shadowing.  Implements
4154/// -Wshadow.
4155///
4156/// This method is called whenever a VarDecl is added to a "useful"
4157/// scope.
4158///
4159/// \param S the scope in which the shadowing name is being declared
4160/// \param R the lookup of the name
4161///
4162void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4163  // Return if warning is ignored.
4164  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4165        DiagnosticsEngine::Ignored)
4166    return;
4167
4168  // Don't diagnose declarations at file scope.
4169  if (D->hasGlobalStorage())
4170    return;
4171
4172  DeclContext *NewDC = D->getDeclContext();
4173
4174  // Only diagnose if we're shadowing an unambiguous field or variable.
4175  if (R.getResultKind() != LookupResult::Found)
4176    return;
4177
4178  NamedDecl* ShadowedDecl = R.getFoundDecl();
4179  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4180    return;
4181
4182  // Fields are not shadowed by variables in C++ static methods.
4183  if (isa<FieldDecl>(ShadowedDecl))
4184    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4185      if (MD->isStatic())
4186        return;
4187
4188  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4189    if (shadowedVar->isExternC()) {
4190      // For shadowing external vars, make sure that we point to the global
4191      // declaration, not a locally scoped extern declaration.
4192      for (VarDecl::redecl_iterator
4193             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4194           I != E; ++I)
4195        if (I->isFileVarDecl()) {
4196          ShadowedDecl = *I;
4197          break;
4198        }
4199    }
4200
4201  DeclContext *OldDC = ShadowedDecl->getDeclContext();
4202
4203  // Only warn about certain kinds of shadowing for class members.
4204  if (NewDC && NewDC->isRecord()) {
4205    // In particular, don't warn about shadowing non-class members.
4206    if (!OldDC->isRecord())
4207      return;
4208
4209    // TODO: should we warn about static data members shadowing
4210    // static data members from base classes?
4211
4212    // TODO: don't diagnose for inaccessible shadowed members.
4213    // This is hard to do perfectly because we might friend the
4214    // shadowing context, but that's just a false negative.
4215  }
4216
4217  // Determine what kind of declaration we're shadowing.
4218  unsigned Kind;
4219  if (isa<RecordDecl>(OldDC)) {
4220    if (isa<FieldDecl>(ShadowedDecl))
4221      Kind = 3; // field
4222    else
4223      Kind = 2; // static data member
4224  } else if (OldDC->isFileContext())
4225    Kind = 1; // global
4226  else
4227    Kind = 0; // local
4228
4229  DeclarationName Name = R.getLookupName();
4230
4231  // Emit warning and note.
4232  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4233  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4234}
4235
4236/// \brief Check -Wshadow without the advantage of a previous lookup.
4237void Sema::CheckShadow(Scope *S, VarDecl *D) {
4238  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4239        DiagnosticsEngine::Ignored)
4240    return;
4241
4242  LookupResult R(*this, D->getDeclName(), D->getLocation(),
4243                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4244  LookupName(R, S);
4245  CheckShadow(S, D, R);
4246}
4247
4248/// \brief Perform semantic checking on a newly-created variable
4249/// declaration.
4250///
4251/// This routine performs all of the type-checking required for a
4252/// variable declaration once it has been built. It is used both to
4253/// check variables after they have been parsed and their declarators
4254/// have been translated into a declaration, and to check variables
4255/// that have been instantiated from a template.
4256///
4257/// Sets NewVD->isInvalidDecl() if an error was encountered.
4258///
4259/// Returns true if the variable declaration is a redeclaration.
4260bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4261                                    LookupResult &Previous) {
4262  // If the decl is already known invalid, don't check it.
4263  if (NewVD->isInvalidDecl())
4264    return false;
4265
4266  QualType T = NewVD->getType();
4267
4268  if (T->isObjCObjectType()) {
4269    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4270      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4271    T = Context.getObjCObjectPointerType(T);
4272    NewVD->setType(T);
4273  }
4274
4275  // Emit an error if an address space was applied to decl with local storage.
4276  // This includes arrays of objects with address space qualifiers, but not
4277  // automatic variables that point to other address spaces.
4278  // ISO/IEC TR 18037 S5.1.2
4279  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4280    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4281    NewVD->setInvalidDecl();
4282    return false;
4283  }
4284
4285  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4286      && !NewVD->hasAttr<BlocksAttr>()) {
4287    if (getLangOpts().getGC() != LangOptions::NonGC)
4288      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4289    else
4290      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4291  }
4292
4293  bool isVM = T->isVariablyModifiedType();
4294  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4295      NewVD->hasAttr<BlocksAttr>())
4296    getCurFunction()->setHasBranchProtectedScope();
4297
4298  if ((isVM && NewVD->hasLinkage()) ||
4299      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4300    bool SizeIsNegative;
4301    llvm::APSInt Oversized;
4302    QualType FixedTy =
4303        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4304                                            Oversized);
4305
4306    if (FixedTy.isNull() && T->isVariableArrayType()) {
4307      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4308      // FIXME: This won't give the correct result for
4309      // int a[10][n];
4310      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4311
4312      if (NewVD->isFileVarDecl())
4313        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4314        << SizeRange;
4315      else if (NewVD->getStorageClass() == SC_Static)
4316        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4317        << SizeRange;
4318      else
4319        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4320        << SizeRange;
4321      NewVD->setInvalidDecl();
4322      return false;
4323    }
4324
4325    if (FixedTy.isNull()) {
4326      if (NewVD->isFileVarDecl())
4327        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4328      else
4329        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4330      NewVD->setInvalidDecl();
4331      return false;
4332    }
4333
4334    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4335    NewVD->setType(FixedTy);
4336  }
4337
4338  if (Previous.empty() && NewVD->isExternC()) {
4339    // Since we did not find anything by this name and we're declaring
4340    // an extern "C" variable, look for a non-visible extern "C"
4341    // declaration with the same name.
4342    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4343      = findLocallyScopedExternalDecl(NewVD->getDeclName());
4344    if (Pos != LocallyScopedExternalDecls.end())
4345      Previous.addDecl(Pos->second);
4346  }
4347
4348  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4349    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4350      << T;
4351    NewVD->setInvalidDecl();
4352    return false;
4353  }
4354
4355  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4356    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4357    NewVD->setInvalidDecl();
4358    return false;
4359  }
4360
4361  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4362    Diag(NewVD->getLocation(), diag::err_block_on_vm);
4363    NewVD->setInvalidDecl();
4364    return false;
4365  }
4366
4367  if (NewVD->isConstexpr() && !T->isDependentType() &&
4368      RequireLiteralType(NewVD->getLocation(), T,
4369                         PDiag(diag::err_constexpr_var_non_literal))) {
4370    NewVD->setInvalidDecl();
4371    return false;
4372  }
4373
4374  if (!Previous.empty()) {
4375    MergeVarDecl(NewVD, Previous);
4376    return true;
4377  }
4378  return false;
4379}
4380
4381/// \brief Data used with FindOverriddenMethod
4382struct FindOverriddenMethodData {
4383  Sema *S;
4384  CXXMethodDecl *Method;
4385};
4386
4387/// \brief Member lookup function that determines whether a given C++
4388/// method overrides a method in a base class, to be used with
4389/// CXXRecordDecl::lookupInBases().
4390static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4391                                 CXXBasePath &Path,
4392                                 void *UserData) {
4393  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4394
4395  FindOverriddenMethodData *Data
4396    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4397
4398  DeclarationName Name = Data->Method->getDeclName();
4399
4400  // FIXME: Do we care about other names here too?
4401  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4402    // We really want to find the base class destructor here.
4403    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4404    CanQualType CT = Data->S->Context.getCanonicalType(T);
4405
4406    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4407  }
4408
4409  for (Path.Decls = BaseRecord->lookup(Name);
4410       Path.Decls.first != Path.Decls.second;
4411       ++Path.Decls.first) {
4412    NamedDecl *D = *Path.Decls.first;
4413    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4414      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4415        return true;
4416    }
4417  }
4418
4419  return false;
4420}
4421
4422/// AddOverriddenMethods - See if a method overrides any in the base classes,
4423/// and if so, check that it's a valid override and remember it.
4424bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4425  // Look for virtual methods in base classes that this method might override.
4426  CXXBasePaths Paths;
4427  FindOverriddenMethodData Data;
4428  Data.Method = MD;
4429  Data.S = this;
4430  bool AddedAny = false;
4431  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4432    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4433         E = Paths.found_decls_end(); I != E; ++I) {
4434      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4435        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4436        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4437            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4438            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4439          AddedAny = true;
4440        }
4441      }
4442    }
4443  }
4444
4445  return AddedAny;
4446}
4447
4448namespace {
4449  // Struct for holding all of the extra arguments needed by
4450  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4451  struct ActOnFDArgs {
4452    Scope *S;
4453    Declarator &D;
4454    MultiTemplateParamsArg TemplateParamLists;
4455    bool AddToScope;
4456  };
4457}
4458
4459namespace {
4460
4461// Callback to only accept typo corrections that have a non-zero edit distance.
4462// Also only accept corrections that have the same parent decl.
4463class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4464 public:
4465  DifferentNameValidatorCCC(CXXRecordDecl *Parent)
4466      : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4467
4468  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4469    if (candidate.getEditDistance() == 0)
4470      return false;
4471
4472    if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4473      CXXRecordDecl *Parent = MD->getParent();
4474      return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4475    }
4476
4477    return !ExpectedParent;
4478  }
4479
4480 private:
4481  CXXRecordDecl *ExpectedParent;
4482};
4483
4484}
4485
4486/// \brief Generate diagnostics for an invalid function redeclaration.
4487///
4488/// This routine handles generating the diagnostic messages for an invalid
4489/// function redeclaration, including finding possible similar declarations
4490/// or performing typo correction if there are no previous declarations with
4491/// the same name.
4492///
4493/// Returns a NamedDecl iff typo correction was performed and substituting in
4494/// the new declaration name does not cause new errors.
4495static NamedDecl* DiagnoseInvalidRedeclaration(
4496    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4497    ActOnFDArgs &ExtraArgs) {
4498  NamedDecl *Result = NULL;
4499  DeclarationName Name = NewFD->getDeclName();
4500  DeclContext *NewDC = NewFD->getDeclContext();
4501  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4502                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4503  llvm::SmallVector<unsigned, 1> MismatchedParams;
4504  llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4505  TypoCorrection Correction;
4506  bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4507                       ExtraArgs.D.getDeclSpec().isFriendSpecified());
4508  unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4509                                  : diag::err_member_def_does_not_match;
4510
4511  NewFD->setInvalidDecl();
4512  SemaRef.LookupQualifiedName(Prev, NewDC);
4513  assert(!Prev.isAmbiguous() &&
4514         "Cannot have an ambiguity in previous-declaration lookup");
4515  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4516  DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
4517  if (!Prev.empty()) {
4518    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4519         Func != FuncEnd; ++Func) {
4520      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4521      if (FD &&
4522          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4523        // Add 1 to the index so that 0 can mean the mismatch didn't
4524        // involve a parameter
4525        unsigned ParamNum =
4526            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4527        NearMatches.push_back(std::make_pair(FD, ParamNum));
4528      }
4529    }
4530  // If the qualified name lookup yielded nothing, try typo correction
4531  } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4532                                         Prev.getLookupKind(), 0, 0,
4533                                         Validator, NewDC))) {
4534    // Trap errors.
4535    Sema::SFINAETrap Trap(SemaRef);
4536
4537    // Set up everything for the call to ActOnFunctionDeclarator
4538    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4539                              ExtraArgs.D.getIdentifierLoc());
4540    Previous.clear();
4541    Previous.setLookupName(Correction.getCorrection());
4542    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4543                                    CDeclEnd = Correction.end();
4544         CDecl != CDeclEnd; ++CDecl) {
4545      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4546      if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4547                                     MismatchedParams)) {
4548        Previous.addDecl(FD);
4549      }
4550    }
4551    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4552    // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4553    // pieces need to verify the typo-corrected C++ declaraction and hopefully
4554    // eliminate the need for the parameter pack ExtraArgs.
4555    Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D,
4556                                             NewFD->getDeclContext(),
4557                                             NewFD->getTypeSourceInfo(),
4558                                             Previous,
4559                                             ExtraArgs.TemplateParamLists,
4560                                             ExtraArgs.AddToScope);
4561    if (Trap.hasErrorOccurred()) {
4562      // Pretend the typo correction never occurred
4563      ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4564                                ExtraArgs.D.getIdentifierLoc());
4565      ExtraArgs.D.setRedeclaration(wasRedeclaration);
4566      Previous.clear();
4567      Previous.setLookupName(Name);
4568      Result = NULL;
4569    } else {
4570      for (LookupResult::iterator Func = Previous.begin(),
4571                               FuncEnd = Previous.end();
4572           Func != FuncEnd; ++Func) {
4573        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4574          NearMatches.push_back(std::make_pair(FD, 0));
4575      }
4576    }
4577    if (NearMatches.empty()) {
4578      // Ignore the correction if it didn't yield any close FunctionDecl matches
4579      Correction = TypoCorrection();
4580    } else {
4581      DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4582                             : diag::err_member_def_does_not_match_suggest;
4583    }
4584  }
4585
4586  if (Correction)
4587    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4588        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
4589        << FixItHint::CreateReplacement(
4590            NewFD->getLocation(),
4591            Correction.getAsString(SemaRef.getLangOpts()));
4592  else
4593    SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4594        << Name << NewDC << NewFD->getLocation();
4595
4596  bool NewFDisConst = false;
4597  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4598    NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4599
4600  for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4601       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4602       NearMatch != NearMatchEnd; ++NearMatch) {
4603    FunctionDecl *FD = NearMatch->first;
4604    bool FDisConst = false;
4605    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4606      FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
4607
4608    if (unsigned Idx = NearMatch->second) {
4609      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4610      SemaRef.Diag(FDParam->getTypeSpecStartLoc(),
4611             diag::note_member_def_close_param_match)
4612          << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4613    } else if (Correction) {
4614      SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
4615          << Correction.getQuoted(SemaRef.getLangOpts());
4616    } else if (FDisConst != NewFDisConst) {
4617      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
4618          << NewFDisConst << FD->getSourceRange().getEnd();
4619    } else
4620      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
4621  }
4622  return Result;
4623}
4624
4625static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4626                                                          Declarator &D) {
4627  switch (D.getDeclSpec().getStorageClassSpec()) {
4628  default: llvm_unreachable("Unknown storage class!");
4629  case DeclSpec::SCS_auto:
4630  case DeclSpec::SCS_register:
4631  case DeclSpec::SCS_mutable:
4632    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4633                 diag::err_typecheck_sclass_func);
4634    D.setInvalidType();
4635    break;
4636  case DeclSpec::SCS_unspecified: break;
4637  case DeclSpec::SCS_extern: return SC_Extern;
4638  case DeclSpec::SCS_static: {
4639    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4640      // C99 6.7.1p5:
4641      //   The declaration of an identifier for a function that has
4642      //   block scope shall have no explicit storage-class specifier
4643      //   other than extern
4644      // See also (C++ [dcl.stc]p4).
4645      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4646                   diag::err_static_block_func);
4647      break;
4648    } else
4649      return SC_Static;
4650  }
4651  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4652  }
4653
4654  // No explicit storage class has already been returned
4655  return SC_None;
4656}
4657
4658static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4659                                           DeclContext *DC, QualType &R,
4660                                           TypeSourceInfo *TInfo,
4661                                           FunctionDecl::StorageClass SC,
4662                                           bool &IsVirtualOkay) {
4663  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4664  DeclarationName Name = NameInfo.getName();
4665
4666  FunctionDecl *NewFD = 0;
4667  bool isInline = D.getDeclSpec().isInlineSpecified();
4668  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4669  FunctionDecl::StorageClass SCAsWritten
4670    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4671
4672  if (!SemaRef.getLangOpts().CPlusPlus) {
4673    // Determine whether the function was written with a
4674    // prototype. This true when:
4675    //   - there is a prototype in the declarator, or
4676    //   - the type R of the function is some kind of typedef or other reference
4677    //     to a type name (which eventually refers to a function type).
4678    bool HasPrototype =
4679      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4680      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4681
4682    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
4683                                 D.getLocStart(), NameInfo, R,
4684                                 TInfo, SC, SCAsWritten, isInline,
4685                                 HasPrototype);
4686    if (D.isInvalidType())
4687      NewFD->setInvalidDecl();
4688
4689    // Set the lexical context.
4690    NewFD->setLexicalDeclContext(SemaRef.CurContext);
4691
4692    return NewFD;
4693  }
4694
4695  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4696  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4697
4698  // Check that the return type is not an abstract class type.
4699  // For record types, this is done by the AbstractClassUsageDiagnoser once
4700  // the class has been completely parsed.
4701  if (!DC->isRecord() &&
4702      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4703                                     R->getAs<FunctionType>()->getResultType(),
4704                                     diag::err_abstract_type_in_decl,
4705                                     SemaRef.AbstractReturnType))
4706    D.setInvalidType();
4707
4708  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4709    // This is a C++ constructor declaration.
4710    assert(DC->isRecord() &&
4711           "Constructors can only be declared in a member context");
4712
4713    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4714    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4715                                      D.getLocStart(), NameInfo,
4716                                      R, TInfo, isExplicit, isInline,
4717                                      /*isImplicitlyDeclared=*/false,
4718                                      isConstexpr);
4719
4720  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4721    // This is a C++ destructor declaration.
4722    if (DC->isRecord()) {
4723      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4724      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4725      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4726                                        SemaRef.Context, Record,
4727                                        D.getLocStart(),
4728                                        NameInfo, R, TInfo, isInline,
4729                                        /*isImplicitlyDeclared=*/false);
4730
4731      // If the class is complete, then we now create the implicit exception
4732      // specification. If the class is incomplete or dependent, we can't do
4733      // it yet.
4734      if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
4735          Record->getDefinition() && !Record->isBeingDefined() &&
4736          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4737        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4738      }
4739
4740      IsVirtualOkay = true;
4741      return NewDD;
4742
4743    } else {
4744      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4745      D.setInvalidType();
4746
4747      // Create a FunctionDecl to satisfy the function definition parsing
4748      // code path.
4749      return FunctionDecl::Create(SemaRef.Context, DC,
4750                                  D.getLocStart(),
4751                                  D.getIdentifierLoc(), Name, R, TInfo,
4752                                  SC, SCAsWritten, isInline,
4753                                  /*hasPrototype=*/true, isConstexpr);
4754    }
4755
4756  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4757    if (!DC->isRecord()) {
4758      SemaRef.Diag(D.getIdentifierLoc(),
4759           diag::err_conv_function_not_member);
4760      return 0;
4761    }
4762
4763    SemaRef.CheckConversionDeclarator(D, R, SC);
4764    IsVirtualOkay = true;
4765    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4766                                     D.getLocStart(), NameInfo,
4767                                     R, TInfo, isInline, isExplicit,
4768                                     isConstexpr, SourceLocation());
4769
4770  } else if (DC->isRecord()) {
4771    // If the name of the function is the same as the name of the record,
4772    // then this must be an invalid constructor that has a return type.
4773    // (The parser checks for a return type and makes the declarator a
4774    // constructor if it has no return type).
4775    if (Name.getAsIdentifierInfo() &&
4776        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4777      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4778        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4779        << SourceRange(D.getIdentifierLoc());
4780      return 0;
4781    }
4782
4783    bool isStatic = SC == SC_Static;
4784
4785    // [class.free]p1:
4786    // Any allocation function for a class T is a static member
4787    // (even if not explicitly declared static).
4788    if (Name.getCXXOverloadedOperator() == OO_New ||
4789        Name.getCXXOverloadedOperator() == OO_Array_New)
4790      isStatic = true;
4791
4792    // [class.free]p6 Any deallocation function for a class X is a static member
4793    // (even if not explicitly declared static).
4794    if (Name.getCXXOverloadedOperator() == OO_Delete ||
4795        Name.getCXXOverloadedOperator() == OO_Array_Delete)
4796      isStatic = true;
4797
4798    IsVirtualOkay = !isStatic;
4799
4800    // This is a C++ method declaration.
4801    return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4802                                 D.getLocStart(), NameInfo, R,
4803                                 TInfo, isStatic, SCAsWritten, isInline,
4804                                 isConstexpr, SourceLocation());
4805
4806  } else {
4807    // Determine whether the function was written with a
4808    // prototype. This true when:
4809    //   - we're in C++ (where every function has a prototype),
4810    return FunctionDecl::Create(SemaRef.Context, DC,
4811                                D.getLocStart(),
4812                                NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4813                                true/*HasPrototype*/, isConstexpr);
4814  }
4815}
4816
4817NamedDecl*
4818Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4819                              TypeSourceInfo *TInfo, LookupResult &Previous,
4820                              MultiTemplateParamsArg TemplateParamLists,
4821                              bool &AddToScope) {
4822  QualType R = TInfo->getType();
4823
4824  assert(R.getTypePtr()->isFunctionType());
4825
4826  // TODO: consider using NameInfo for diagnostic.
4827  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4828  DeclarationName Name = NameInfo.getName();
4829  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
4830
4831  if (D.getDeclSpec().isThreadSpecified())
4832    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4833
4834  // Do not allow returning a objc interface by-value.
4835  if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
4836    Diag(D.getIdentifierLoc(),
4837         diag::err_object_cannot_be_passed_returned_by_value) << 0
4838    << R->getAs<FunctionType>()->getResultType()
4839    << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4840
4841    QualType T = R->getAs<FunctionType>()->getResultType();
4842    T = Context.getObjCObjectPointerType(T);
4843    if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4844      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4845      R = Context.getFunctionType(T, FPT->arg_type_begin(),
4846                                  FPT->getNumArgs(), EPI);
4847    }
4848    else if (isa<FunctionNoProtoType>(R))
4849      R = Context.getFunctionNoProtoType(T);
4850  }
4851
4852  bool isFriend = false;
4853  FunctionTemplateDecl *FunctionTemplate = 0;
4854  bool isExplicitSpecialization = false;
4855  bool isFunctionTemplateSpecialization = false;
4856  bool isDependentClassScopeExplicitSpecialization = false;
4857  bool isVirtualOkay = false;
4858
4859  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4860                                              isVirtualOkay);
4861  if (!NewFD) return 0;
4862
4863  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4864    NewFD->setTopLevelDeclInObjCContainer();
4865
4866  if (getLangOpts().CPlusPlus) {
4867    bool isInline = D.getDeclSpec().isInlineSpecified();
4868    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4869    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4870    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4871    isFriend = D.getDeclSpec().isFriendSpecified();
4872    if (isFriend && !isInline && D.isFunctionDefinition()) {
4873      // C++ [class.friend]p5
4874      //   A function can be defined in a friend declaration of a
4875      //   class . . . . Such a function is implicitly inline.
4876      NewFD->setImplicitlyInline();
4877    }
4878
4879    SetNestedNameSpecifier(NewFD, D);
4880    isExplicitSpecialization = false;
4881    isFunctionTemplateSpecialization = false;
4882    if (D.isInvalidType())
4883      NewFD->setInvalidDecl();
4884
4885    // Set the lexical context. If the declarator has a C++
4886    // scope specifier, or is the object of a friend declaration, the
4887    // lexical context will be different from the semantic context.
4888    NewFD->setLexicalDeclContext(CurContext);
4889
4890    // Match up the template parameter lists with the scope specifier, then
4891    // determine whether we have a template or a template specialization.
4892    bool Invalid = false;
4893    if (TemplateParameterList *TemplateParams
4894          = MatchTemplateParametersToScopeSpecifier(
4895                                  D.getDeclSpec().getLocStart(),
4896                                  D.getIdentifierLoc(),
4897                                  D.getCXXScopeSpec(),
4898                                  TemplateParamLists.get(),
4899                                  TemplateParamLists.size(),
4900                                  isFriend,
4901                                  isExplicitSpecialization,
4902                                  Invalid)) {
4903      if (TemplateParams->size() > 0) {
4904        // This is a function template
4905
4906        // Check that we can declare a template here.
4907        if (CheckTemplateDeclScope(S, TemplateParams))
4908          return 0;
4909
4910        // A destructor cannot be a template.
4911        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4912          Diag(NewFD->getLocation(), diag::err_destructor_template);
4913          return 0;
4914        }
4915
4916        // If we're adding a template to a dependent context, we may need to
4917        // rebuilding some of the types used within the template parameter list,
4918        // now that we know what the current instantiation is.
4919        if (DC->isDependentContext()) {
4920          ContextRAII SavedContext(*this, DC);
4921          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4922            Invalid = true;
4923        }
4924
4925
4926        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4927                                                        NewFD->getLocation(),
4928                                                        Name, TemplateParams,
4929                                                        NewFD);
4930        FunctionTemplate->setLexicalDeclContext(CurContext);
4931        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4932
4933        // For source fidelity, store the other template param lists.
4934        if (TemplateParamLists.size() > 1) {
4935          NewFD->setTemplateParameterListsInfo(Context,
4936                                               TemplateParamLists.size() - 1,
4937                                               TemplateParamLists.release());
4938        }
4939      } else {
4940        // This is a function template specialization.
4941        isFunctionTemplateSpecialization = true;
4942        // For source fidelity, store all the template param lists.
4943        NewFD->setTemplateParameterListsInfo(Context,
4944                                             TemplateParamLists.size(),
4945                                             TemplateParamLists.release());
4946
4947        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4948        if (isFriend) {
4949          // We want to remove the "template<>", found here.
4950          SourceRange RemoveRange = TemplateParams->getSourceRange();
4951
4952          // If we remove the template<> and the name is not a
4953          // template-id, we're actually silently creating a problem:
4954          // the friend declaration will refer to an untemplated decl,
4955          // and clearly the user wants a template specialization.  So
4956          // we need to insert '<>' after the name.
4957          SourceLocation InsertLoc;
4958          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4959            InsertLoc = D.getName().getSourceRange().getEnd();
4960            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4961          }
4962
4963          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4964            << Name << RemoveRange
4965            << FixItHint::CreateRemoval(RemoveRange)
4966            << FixItHint::CreateInsertion(InsertLoc, "<>");
4967        }
4968      }
4969    }
4970    else {
4971      // All template param lists were matched against the scope specifier:
4972      // this is NOT (an explicit specialization of) a template.
4973      if (TemplateParamLists.size() > 0)
4974        // For source fidelity, store all the template param lists.
4975        NewFD->setTemplateParameterListsInfo(Context,
4976                                             TemplateParamLists.size(),
4977                                             TemplateParamLists.release());
4978    }
4979
4980    if (Invalid) {
4981      NewFD->setInvalidDecl();
4982      if (FunctionTemplate)
4983        FunctionTemplate->setInvalidDecl();
4984    }
4985
4986    // If we see "T var();" at block scope, where T is a class type, it is
4987    // probably an attempt to initialize a variable, not a function declaration.
4988    // We don't catch this case earlier, since there is no ambiguity here.
4989    if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
4990        CurContext->isFunctionOrMethod() &&
4991        D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
4992        D.getDeclSpec().getStorageClassSpecAsWritten()
4993          == DeclSpec::SCS_unspecified) {
4994      QualType T = R->getAs<FunctionType>()->getResultType();
4995      DeclaratorChunk &C = D.getTypeObject(0);
4996      if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
4997          !C.Fun.TrailingReturnType &&
4998          C.Fun.getExceptionSpecType() == EST_None) {
4999        SourceRange ParenRange(C.Loc, C.EndLoc);
5000        Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5001
5002        // If the declaration looks like:
5003        //   T var1,
5004        //   f();
5005        // and name lookup finds a function named 'f', then the ',' was
5006        // probably intended to be a ';'.
5007        if (!D.isFirstDeclarator() && D.getIdentifier()) {
5008          FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5009          FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5010          if (Comma.getFileID() != Name.getFileID() ||
5011              Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5012            LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5013                                LookupOrdinaryName);
5014            if (LookupName(Result, S))
5015              Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5016                << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5017          }
5018        }
5019        const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5020        // Empty parens mean value-initialization, and no parens mean default
5021        // initialization. These are equivalent if the default constructor is
5022        // user-provided, or if zero-initialization is a no-op.
5023        if (RD && RD->hasDefinition() &&
5024            (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
5025          Diag(C.Loc, diag::note_empty_parens_default_ctor)
5026            << FixItHint::CreateRemoval(ParenRange);
5027        else if (const char *Init = getFixItZeroInitializerForType(T))
5028          Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5029            << FixItHint::CreateReplacement(ParenRange, Init);
5030        else if (LangOpts.CPlusPlus0x)
5031          Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5032            << FixItHint::CreateReplacement(ParenRange, "{}");
5033      }
5034    }
5035
5036    // C++ [dcl.fct.spec]p5:
5037    //   The virtual specifier shall only be used in declarations of
5038    //   nonstatic class member functions that appear within a
5039    //   member-specification of a class declaration; see 10.3.
5040    //
5041    if (isVirtual && !NewFD->isInvalidDecl()) {
5042      if (!isVirtualOkay) {
5043        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5044             diag::err_virtual_non_function);
5045      } else if (!CurContext->isRecord()) {
5046        // 'virtual' was specified outside of the class.
5047        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5048             diag::err_virtual_out_of_class)
5049          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5050      } else if (NewFD->getDescribedFunctionTemplate()) {
5051        // C++ [temp.mem]p3:
5052        //  A member function template shall not be virtual.
5053        Diag(D.getDeclSpec().getVirtualSpecLoc(),
5054             diag::err_virtual_member_function_template)
5055          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5056      } else {
5057        // Okay: Add virtual to the method.
5058        NewFD->setVirtualAsWritten(true);
5059      }
5060    }
5061
5062    // C++ [dcl.fct.spec]p3:
5063    //  The inline specifier shall not appear on a block scope function
5064    //  declaration.
5065    if (isInline && !NewFD->isInvalidDecl()) {
5066      if (CurContext->isFunctionOrMethod()) {
5067        // 'inline' is not allowed on block scope function declaration.
5068        Diag(D.getDeclSpec().getInlineSpecLoc(),
5069             diag::err_inline_declaration_block_scope) << Name
5070          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5071      }
5072    }
5073
5074    // C++ [dcl.fct.spec]p6:
5075    //  The explicit specifier shall be used only in the declaration of a
5076    //  constructor or conversion function within its class definition;
5077    //  see 12.3.1 and 12.3.2.
5078    if (isExplicit && !NewFD->isInvalidDecl()) {
5079      if (!CurContext->isRecord()) {
5080        // 'explicit' was specified outside of the class.
5081        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5082             diag::err_explicit_out_of_class)
5083          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5084      } else if (!isa<CXXConstructorDecl>(NewFD) &&
5085                 !isa<CXXConversionDecl>(NewFD)) {
5086        // 'explicit' was specified on a function that wasn't a constructor
5087        // or conversion function.
5088        Diag(D.getDeclSpec().getExplicitSpecLoc(),
5089             diag::err_explicit_non_ctor_or_conv_function)
5090          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5091      }
5092    }
5093
5094    if (isConstexpr) {
5095      // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5096      // are implicitly inline.
5097      NewFD->setImplicitlyInline();
5098
5099      // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5100      // be either constructors or to return a literal type. Therefore,
5101      // destructors cannot be declared constexpr.
5102      if (isa<CXXDestructorDecl>(NewFD))
5103        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5104    }
5105
5106    // If __module_private__ was specified, mark the function accordingly.
5107    if (D.getDeclSpec().isModulePrivateSpecified()) {
5108      if (isFunctionTemplateSpecialization) {
5109        SourceLocation ModulePrivateLoc
5110          = D.getDeclSpec().getModulePrivateSpecLoc();
5111        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5112          << 0
5113          << FixItHint::CreateRemoval(ModulePrivateLoc);
5114      } else {
5115        NewFD->setModulePrivate();
5116        if (FunctionTemplate)
5117          FunctionTemplate->setModulePrivate();
5118      }
5119    }
5120
5121    if (isFriend) {
5122      // For now, claim that the objects have no previous declaration.
5123      if (FunctionTemplate) {
5124        FunctionTemplate->setObjectOfFriendDecl(false);
5125        FunctionTemplate->setAccess(AS_public);
5126      }
5127      NewFD->setObjectOfFriendDecl(false);
5128      NewFD->setAccess(AS_public);
5129    }
5130
5131    // If a function is defined as defaulted or deleted, mark it as such now.
5132    switch (D.getFunctionDefinitionKind()) {
5133      case FDK_Declaration:
5134      case FDK_Definition:
5135        break;
5136
5137      case FDK_Defaulted:
5138        NewFD->setDefaulted();
5139        break;
5140
5141      case FDK_Deleted:
5142        NewFD->setDeletedAsWritten();
5143        break;
5144    }
5145
5146    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5147        D.isFunctionDefinition()) {
5148      // C++ [class.mfct]p2:
5149      //   A member function may be defined (8.4) in its class definition, in
5150      //   which case it is an inline member function (7.1.2)
5151      NewFD->setImplicitlyInline();
5152    }
5153
5154    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5155        !CurContext->isRecord()) {
5156      // C++ [class.static]p1:
5157      //   A data or function member of a class may be declared static
5158      //   in a class definition, in which case it is a static member of
5159      //   the class.
5160
5161      // Complain about the 'static' specifier if it's on an out-of-line
5162      // member function definition.
5163      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5164           diag::err_static_out_of_line)
5165        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5166    }
5167  }
5168
5169  // Filter out previous declarations that don't match the scope.
5170  FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5171                       isExplicitSpecialization ||
5172                       isFunctionTemplateSpecialization);
5173
5174  // Handle GNU asm-label extension (encoded as an attribute).
5175  if (Expr *E = (Expr*) D.getAsmLabel()) {
5176    // The parser guarantees this is a string.
5177    StringLiteral *SE = cast<StringLiteral>(E);
5178    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5179                                                SE->getString()));
5180  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5181    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5182      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5183    if (I != ExtnameUndeclaredIdentifiers.end()) {
5184      NewFD->addAttr(I->second);
5185      ExtnameUndeclaredIdentifiers.erase(I);
5186    }
5187  }
5188
5189  // Copy the parameter declarations from the declarator D to the function
5190  // declaration NewFD, if they are available.  First scavenge them into Params.
5191  SmallVector<ParmVarDecl*, 16> Params;
5192  if (D.isFunctionDeclarator()) {
5193    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5194
5195    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5196    // function that takes no arguments, not a function that takes a
5197    // single void argument.
5198    // We let through "const void" here because Sema::GetTypeForDeclarator
5199    // already checks for that case.
5200    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5201        FTI.ArgInfo[0].Param &&
5202        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5203      // Empty arg list, don't push any params.
5204      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5205
5206      // In C++, the empty parameter-type-list must be spelled "void"; a
5207      // typedef of void is not permitted.
5208      if (getLangOpts().CPlusPlus &&
5209          Param->getType().getUnqualifiedType() != Context.VoidTy) {
5210        bool IsTypeAlias = false;
5211        if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5212          IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5213        else if (const TemplateSpecializationType *TST =
5214                   Param->getType()->getAs<TemplateSpecializationType>())
5215          IsTypeAlias = TST->isTypeAlias();
5216        Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5217          << IsTypeAlias;
5218      }
5219    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5220      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5221        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5222        assert(Param->getDeclContext() != NewFD && "Was set before ?");
5223        Param->setDeclContext(NewFD);
5224        Params.push_back(Param);
5225
5226        if (Param->isInvalidDecl())
5227          NewFD->setInvalidDecl();
5228      }
5229    }
5230
5231  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5232    // When we're declaring a function with a typedef, typeof, etc as in the
5233    // following example, we'll need to synthesize (unnamed)
5234    // parameters for use in the declaration.
5235    //
5236    // @code
5237    // typedef void fn(int);
5238    // fn f;
5239    // @endcode
5240
5241    // Synthesize a parameter for each argument type.
5242    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5243         AE = FT->arg_type_end(); AI != AE; ++AI) {
5244      ParmVarDecl *Param =
5245        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5246      Param->setScopeInfo(0, Params.size());
5247      Params.push_back(Param);
5248    }
5249  } else {
5250    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5251           "Should not need args for typedef of non-prototype fn");
5252  }
5253
5254  // Finally, we know we have the right number of parameters, install them.
5255  NewFD->setParams(Params);
5256
5257  // Find all anonymous symbols defined during the declaration of this function
5258  // and add to NewFD. This lets us track decls such 'enum Y' in:
5259  //
5260  //   void f(enum Y {AA} x) {}
5261  //
5262  // which would otherwise incorrectly end up in the translation unit scope.
5263  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5264  DeclsInPrototypeScope.clear();
5265
5266  // Process the non-inheritable attributes on this declaration.
5267  ProcessDeclAttributes(S, NewFD, D,
5268                        /*NonInheritable=*/true, /*Inheritable=*/false);
5269
5270  // Functions returning a variably modified type violate C99 6.7.5.2p2
5271  // because all functions have linkage.
5272  if (!NewFD->isInvalidDecl() &&
5273      NewFD->getResultType()->isVariablyModifiedType()) {
5274    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5275    NewFD->setInvalidDecl();
5276  }
5277
5278  if (!getLangOpts().CPlusPlus) {
5279    // Perform semantic checking on the function declaration.
5280    bool isExplicitSpecialization=false;
5281    if (!NewFD->isInvalidDecl()) {
5282      if (NewFD->isMain())
5283        CheckMain(NewFD, D.getDeclSpec());
5284      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5285                                                  isExplicitSpecialization));
5286    }
5287    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5288            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5289           "previous declaration set still overloaded");
5290  } else {
5291    // If the declarator is a template-id, translate the parser's template
5292    // argument list into our AST format.
5293    bool HasExplicitTemplateArgs = false;
5294    TemplateArgumentListInfo TemplateArgs;
5295    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5296      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5297      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5298      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5299      ASTTemplateArgsPtr TemplateArgsPtr(*this,
5300                                         TemplateId->getTemplateArgs(),
5301                                         TemplateId->NumArgs);
5302      translateTemplateArguments(TemplateArgsPtr,
5303                                 TemplateArgs);
5304      TemplateArgsPtr.release();
5305
5306      HasExplicitTemplateArgs = true;
5307
5308      if (NewFD->isInvalidDecl()) {
5309        HasExplicitTemplateArgs = false;
5310      } else if (FunctionTemplate) {
5311        // Function template with explicit template arguments.
5312        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5313          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5314
5315        HasExplicitTemplateArgs = false;
5316      } else if (!isFunctionTemplateSpecialization &&
5317                 !D.getDeclSpec().isFriendSpecified()) {
5318        // We have encountered something that the user meant to be a
5319        // specialization (because it has explicitly-specified template
5320        // arguments) but that was not introduced with a "template<>" (or had
5321        // too few of them).
5322        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5323          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5324          << FixItHint::CreateInsertion(
5325                                    D.getDeclSpec().getLocStart(),
5326                                        "template<> ");
5327        isFunctionTemplateSpecialization = true;
5328      } else {
5329        // "friend void foo<>(int);" is an implicit specialization decl.
5330        isFunctionTemplateSpecialization = true;
5331      }
5332    } else if (isFriend && isFunctionTemplateSpecialization) {
5333      // This combination is only possible in a recovery case;  the user
5334      // wrote something like:
5335      //   template <> friend void foo(int);
5336      // which we're recovering from as if the user had written:
5337      //   friend void foo<>(int);
5338      // Go ahead and fake up a template id.
5339      HasExplicitTemplateArgs = true;
5340        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5341      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5342    }
5343
5344    // If it's a friend (and only if it's a friend), it's possible
5345    // that either the specialized function type or the specialized
5346    // template is dependent, and therefore matching will fail.  In
5347    // this case, don't check the specialization yet.
5348    bool InstantiationDependent = false;
5349    if (isFunctionTemplateSpecialization && isFriend &&
5350        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5351         TemplateSpecializationType::anyDependentTemplateArguments(
5352            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5353            InstantiationDependent))) {
5354      assert(HasExplicitTemplateArgs &&
5355             "friend function specialization without template args");
5356      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5357                                                       Previous))
5358        NewFD->setInvalidDecl();
5359    } else if (isFunctionTemplateSpecialization) {
5360      if (CurContext->isDependentContext() && CurContext->isRecord()
5361          && !isFriend) {
5362        isDependentClassScopeExplicitSpecialization = true;
5363        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5364          diag::ext_function_specialization_in_class :
5365          diag::err_function_specialization_in_class)
5366          << NewFD->getDeclName();
5367      } else if (CheckFunctionTemplateSpecialization(NewFD,
5368                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5369                                                     Previous))
5370        NewFD->setInvalidDecl();
5371
5372      // C++ [dcl.stc]p1:
5373      //   A storage-class-specifier shall not be specified in an explicit
5374      //   specialization (14.7.3)
5375      if (SC != SC_None) {
5376        if (SC != NewFD->getStorageClass())
5377          Diag(NewFD->getLocation(),
5378               diag::err_explicit_specialization_inconsistent_storage_class)
5379            << SC
5380            << FixItHint::CreateRemoval(
5381                                      D.getDeclSpec().getStorageClassSpecLoc());
5382
5383        else
5384          Diag(NewFD->getLocation(),
5385               diag::ext_explicit_specialization_storage_class)
5386            << FixItHint::CreateRemoval(
5387                                      D.getDeclSpec().getStorageClassSpecLoc());
5388      }
5389
5390    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5391      if (CheckMemberSpecialization(NewFD, Previous))
5392          NewFD->setInvalidDecl();
5393    }
5394
5395    // Perform semantic checking on the function declaration.
5396    if (!isDependentClassScopeExplicitSpecialization) {
5397      if (NewFD->isInvalidDecl()) {
5398        // If this is a class member, mark the class invalid immediately.
5399        // This avoids some consistency errors later.
5400        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5401          methodDecl->getParent()->setInvalidDecl();
5402      } else {
5403        if (NewFD->isMain())
5404          CheckMain(NewFD, D.getDeclSpec());
5405        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5406                                                    isExplicitSpecialization));
5407      }
5408    }
5409
5410    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5411            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5412           "previous declaration set still overloaded");
5413
5414    NamedDecl *PrincipalDecl = (FunctionTemplate
5415                                ? cast<NamedDecl>(FunctionTemplate)
5416                                : NewFD);
5417
5418    if (isFriend && D.isRedeclaration()) {
5419      AccessSpecifier Access = AS_public;
5420      if (!NewFD->isInvalidDecl())
5421        Access = NewFD->getPreviousDecl()->getAccess();
5422
5423      NewFD->setAccess(Access);
5424      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5425
5426      PrincipalDecl->setObjectOfFriendDecl(true);
5427    }
5428
5429    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5430        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5431      PrincipalDecl->setNonMemberOperator();
5432
5433    // If we have a function template, check the template parameter
5434    // list. This will check and merge default template arguments.
5435    if (FunctionTemplate) {
5436      FunctionTemplateDecl *PrevTemplate =
5437                                     FunctionTemplate->getPreviousDecl();
5438      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5439                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5440                            D.getDeclSpec().isFriendSpecified()
5441                              ? (D.isFunctionDefinition()
5442                                   ? TPC_FriendFunctionTemplateDefinition
5443                                   : TPC_FriendFunctionTemplate)
5444                              : (D.getCXXScopeSpec().isSet() &&
5445                                 DC && DC->isRecord() &&
5446                                 DC->isDependentContext())
5447                                  ? TPC_ClassTemplateMember
5448                                  : TPC_FunctionTemplate);
5449    }
5450
5451    if (NewFD->isInvalidDecl()) {
5452      // Ignore all the rest of this.
5453    } else if (!D.isRedeclaration()) {
5454      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5455                                       AddToScope };
5456      // Fake up an access specifier if it's supposed to be a class member.
5457      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5458        NewFD->setAccess(AS_public);
5459
5460      // Qualified decls generally require a previous declaration.
5461      if (D.getCXXScopeSpec().isSet()) {
5462        // ...with the major exception of templated-scope or
5463        // dependent-scope friend declarations.
5464
5465        // TODO: we currently also suppress this check in dependent
5466        // contexts because (1) the parameter depth will be off when
5467        // matching friend templates and (2) we might actually be
5468        // selecting a friend based on a dependent factor.  But there
5469        // are situations where these conditions don't apply and we
5470        // can actually do this check immediately.
5471        if (isFriend &&
5472            (TemplateParamLists.size() ||
5473             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5474             CurContext->isDependentContext())) {
5475          // ignore these
5476        } else {
5477          // The user tried to provide an out-of-line definition for a
5478          // function that is a member of a class or namespace, but there
5479          // was no such member function declared (C++ [class.mfct]p2,
5480          // C++ [namespace.memdef]p2). For example:
5481          //
5482          // class X {
5483          //   void f() const;
5484          // };
5485          //
5486          // void X::f() { } // ill-formed
5487          //
5488          // Complain about this problem, and attempt to suggest close
5489          // matches (e.g., those that differ only in cv-qualifiers and
5490          // whether the parameter types are references).
5491
5492          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5493                                                               NewFD,
5494                                                               ExtraArgs)) {
5495            AddToScope = ExtraArgs.AddToScope;
5496            return Result;
5497          }
5498        }
5499
5500        // Unqualified local friend declarations are required to resolve
5501        // to something.
5502      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5503        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5504                                                             NewFD,
5505                                                             ExtraArgs)) {
5506          AddToScope = ExtraArgs.AddToScope;
5507          return Result;
5508        }
5509      }
5510
5511    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5512               !isFriend && !isFunctionTemplateSpecialization &&
5513               !isExplicitSpecialization) {
5514      // An out-of-line member function declaration must also be a
5515      // definition (C++ [dcl.meaning]p1).
5516      // Note that this is not the case for explicit specializations of
5517      // function templates or member functions of class templates, per
5518      // C++ [temp.expl.spec]p2. We also allow these declarations as an
5519      // extension for compatibility with old SWIG code which likes to
5520      // generate them.
5521      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5522        << D.getCXXScopeSpec().getRange();
5523    }
5524  }
5525
5526
5527  // Handle attributes. We need to have merged decls when handling attributes
5528  // (for example to check for conflicts, etc).
5529  // FIXME: This needs to happen before we merge declarations. Then,
5530  // let attribute merging cope with attribute conflicts.
5531  ProcessDeclAttributes(S, NewFD, D,
5532                        /*NonInheritable=*/false, /*Inheritable=*/true);
5533
5534  // attributes declared post-definition are currently ignored
5535  // FIXME: This should happen during attribute merging
5536  if (D.isRedeclaration() && Previous.isSingleResult()) {
5537    const FunctionDecl *Def;
5538    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5539    if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5540      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5541      Diag(Def->getLocation(), diag::note_previous_definition);
5542    }
5543  }
5544
5545  AddKnownFunctionAttributes(NewFD);
5546
5547  if (NewFD->hasAttr<OverloadableAttr>() &&
5548      !NewFD->getType()->getAs<FunctionProtoType>()) {
5549    Diag(NewFD->getLocation(),
5550         diag::err_attribute_overloadable_no_prototype)
5551      << NewFD;
5552
5553    // Turn this into a variadic function with no parameters.
5554    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5555    FunctionProtoType::ExtProtoInfo EPI;
5556    EPI.Variadic = true;
5557    EPI.ExtInfo = FT->getExtInfo();
5558
5559    QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5560    NewFD->setType(R);
5561  }
5562
5563  // If there's a #pragma GCC visibility in scope, and this isn't a class
5564  // member, set the visibility of this function.
5565  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5566    AddPushedVisibilityAttribute(NewFD);
5567
5568  // If there's a #pragma clang arc_cf_code_audited in scope, consider
5569  // marking the function.
5570  AddCFAuditedAttribute(NewFD);
5571
5572  // If this is a locally-scoped extern C function, update the
5573  // map of such names.
5574  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5575      && !NewFD->isInvalidDecl())
5576    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5577
5578  // Set this FunctionDecl's range up to the right paren.
5579  NewFD->setRangeEnd(D.getSourceRange().getEnd());
5580
5581  if (getLangOpts().CPlusPlus) {
5582    if (FunctionTemplate) {
5583      if (NewFD->isInvalidDecl())
5584        FunctionTemplate->setInvalidDecl();
5585      return FunctionTemplate;
5586    }
5587  }
5588
5589  MarkUnusedFileScopedDecl(NewFD);
5590
5591  if (getLangOpts().CUDA)
5592    if (IdentifierInfo *II = NewFD->getIdentifier())
5593      if (!NewFD->isInvalidDecl() &&
5594          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5595        if (II->isStr("cudaConfigureCall")) {
5596          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5597            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5598
5599          Context.setcudaConfigureCallDecl(NewFD);
5600        }
5601      }
5602
5603  // Here we have an function template explicit specialization at class scope.
5604  // The actually specialization will be postponed to template instatiation
5605  // time via the ClassScopeFunctionSpecializationDecl node.
5606  if (isDependentClassScopeExplicitSpecialization) {
5607    ClassScopeFunctionSpecializationDecl *NewSpec =
5608                         ClassScopeFunctionSpecializationDecl::Create(
5609                                Context, CurContext,  SourceLocation(),
5610                                cast<CXXMethodDecl>(NewFD));
5611    CurContext->addDecl(NewSpec);
5612    AddToScope = false;
5613  }
5614
5615  return NewFD;
5616}
5617
5618/// \brief Perform semantic checking of a new function declaration.
5619///
5620/// Performs semantic analysis of the new function declaration
5621/// NewFD. This routine performs all semantic checking that does not
5622/// require the actual declarator involved in the declaration, and is
5623/// used both for the declaration of functions as they are parsed
5624/// (called via ActOnDeclarator) and for the declaration of functions
5625/// that have been instantiated via C++ template instantiation (called
5626/// via InstantiateDecl).
5627///
5628/// \param IsExplicitSpecialiation whether this new function declaration is
5629/// an explicit specialization of the previous declaration.
5630///
5631/// This sets NewFD->isInvalidDecl() to true if there was an error.
5632///
5633/// Returns true if the function declaration is a redeclaration.
5634bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5635                                    LookupResult &Previous,
5636                                    bool IsExplicitSpecialization) {
5637  assert(!NewFD->getResultType()->isVariablyModifiedType()
5638         && "Variably modified return types are not handled here");
5639
5640  // Check for a previous declaration of this name.
5641  if (Previous.empty() && NewFD->isExternC()) {
5642    // Since we did not find anything by this name and we're declaring
5643    // an extern "C" function, look for a non-visible extern "C"
5644    // declaration with the same name.
5645    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5646      = findLocallyScopedExternalDecl(NewFD->getDeclName());
5647    if (Pos != LocallyScopedExternalDecls.end())
5648      Previous.addDecl(Pos->second);
5649  }
5650
5651  bool Redeclaration = false;
5652
5653  // Merge or overload the declaration with an existing declaration of
5654  // the same name, if appropriate.
5655  if (!Previous.empty()) {
5656    // Determine whether NewFD is an overload of PrevDecl or
5657    // a declaration that requires merging. If it's an overload,
5658    // there's no more work to do here; we'll just add the new
5659    // function to the scope.
5660
5661    NamedDecl *OldDecl = 0;
5662    if (!AllowOverloadingOfFunction(Previous, Context)) {
5663      Redeclaration = true;
5664      OldDecl = Previous.getFoundDecl();
5665    } else {
5666      switch (CheckOverload(S, NewFD, Previous, OldDecl,
5667                            /*NewIsUsingDecl*/ false)) {
5668      case Ovl_Match:
5669        Redeclaration = true;
5670        break;
5671
5672      case Ovl_NonFunction:
5673        Redeclaration = true;
5674        break;
5675
5676      case Ovl_Overload:
5677        Redeclaration = false;
5678        break;
5679      }
5680
5681      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5682        // If a function name is overloadable in C, then every function
5683        // with that name must be marked "overloadable".
5684        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5685          << Redeclaration << NewFD;
5686        NamedDecl *OverloadedDecl = 0;
5687        if (Redeclaration)
5688          OverloadedDecl = OldDecl;
5689        else if (!Previous.empty())
5690          OverloadedDecl = Previous.getRepresentativeDecl();
5691        if (OverloadedDecl)
5692          Diag(OverloadedDecl->getLocation(),
5693               diag::note_attribute_overloadable_prev_overload);
5694        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5695                                                        Context));
5696      }
5697    }
5698
5699    if (Redeclaration) {
5700      // NewFD and OldDecl represent declarations that need to be
5701      // merged.
5702      if (MergeFunctionDecl(NewFD, OldDecl, S)) {
5703        NewFD->setInvalidDecl();
5704        return Redeclaration;
5705      }
5706
5707      Previous.clear();
5708      Previous.addDecl(OldDecl);
5709
5710      if (FunctionTemplateDecl *OldTemplateDecl
5711                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5712        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5713        FunctionTemplateDecl *NewTemplateDecl
5714          = NewFD->getDescribedFunctionTemplate();
5715        assert(NewTemplateDecl && "Template/non-template mismatch");
5716        if (CXXMethodDecl *Method
5717              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5718          Method->setAccess(OldTemplateDecl->getAccess());
5719          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5720        }
5721
5722        // If this is an explicit specialization of a member that is a function
5723        // template, mark it as a member specialization.
5724        if (IsExplicitSpecialization &&
5725            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5726          NewTemplateDecl->setMemberSpecialization();
5727          assert(OldTemplateDecl->isMemberSpecialization());
5728        }
5729
5730      } else {
5731        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5732          NewFD->setAccess(OldDecl->getAccess());
5733        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5734      }
5735    }
5736  }
5737
5738  // Semantic checking for this function declaration (in isolation).
5739  if (getLangOpts().CPlusPlus) {
5740    // C++-specific checks.
5741    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5742      CheckConstructor(Constructor);
5743    } else if (CXXDestructorDecl *Destructor =
5744                dyn_cast<CXXDestructorDecl>(NewFD)) {
5745      CXXRecordDecl *Record = Destructor->getParent();
5746      QualType ClassType = Context.getTypeDeclType(Record);
5747
5748      // FIXME: Shouldn't we be able to perform this check even when the class
5749      // type is dependent? Both gcc and edg can handle that.
5750      if (!ClassType->isDependentType()) {
5751        DeclarationName Name
5752          = Context.DeclarationNames.getCXXDestructorName(
5753                                        Context.getCanonicalType(ClassType));
5754        if (NewFD->getDeclName() != Name) {
5755          Diag(NewFD->getLocation(), diag::err_destructor_name);
5756          NewFD->setInvalidDecl();
5757          return Redeclaration;
5758        }
5759      }
5760    } else if (CXXConversionDecl *Conversion
5761               = dyn_cast<CXXConversionDecl>(NewFD)) {
5762      ActOnConversionDeclarator(Conversion);
5763    }
5764
5765    // Find any virtual functions that this function overrides.
5766    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5767      if (!Method->isFunctionTemplateSpecialization() &&
5768          !Method->getDescribedFunctionTemplate()) {
5769        if (AddOverriddenMethods(Method->getParent(), Method)) {
5770          // If the function was marked as "static", we have a problem.
5771          if (NewFD->getStorageClass() == SC_Static) {
5772            Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5773              << NewFD->getDeclName();
5774            for (CXXMethodDecl::method_iterator
5775                      Overridden = Method->begin_overridden_methods(),
5776                   OverriddenEnd = Method->end_overridden_methods();
5777                 Overridden != OverriddenEnd;
5778                 ++Overridden) {
5779              Diag((*Overridden)->getLocation(),
5780                   diag::note_overridden_virtual_function);
5781            }
5782          }
5783        }
5784      }
5785    }
5786
5787    // Extra checking for C++ overloaded operators (C++ [over.oper]).
5788    if (NewFD->isOverloadedOperator() &&
5789        CheckOverloadedOperatorDeclaration(NewFD)) {
5790      NewFD->setInvalidDecl();
5791      return Redeclaration;
5792    }
5793
5794    // Extra checking for C++0x literal operators (C++0x [over.literal]).
5795    if (NewFD->getLiteralIdentifier() &&
5796        CheckLiteralOperatorDeclaration(NewFD)) {
5797      NewFD->setInvalidDecl();
5798      return Redeclaration;
5799    }
5800
5801    // In C++, check default arguments now that we have merged decls. Unless
5802    // the lexical context is the class, because in this case this is done
5803    // during delayed parsing anyway.
5804    if (!CurContext->isRecord())
5805      CheckCXXDefaultArguments(NewFD);
5806
5807    // If this function declares a builtin function, check the type of this
5808    // declaration against the expected type for the builtin.
5809    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5810      ASTContext::GetBuiltinTypeError Error;
5811      QualType T = Context.GetBuiltinType(BuiltinID, Error);
5812      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5813        // The type of this function differs from the type of the builtin,
5814        // so forget about the builtin entirely.
5815        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5816      }
5817    }
5818
5819    // If this function is declared as being extern "C", then check to see if
5820    // the function returns a UDT (class, struct, or union type) that is not C
5821    // compatible, and if it does, warn the user.
5822    if (NewFD->isExternC()) {
5823      QualType R = NewFD->getResultType();
5824      if (!R.isPODType(Context) &&
5825          !R->isVoidType())
5826        Diag( NewFD->getLocation(), diag::warn_return_value_udt )
5827          << NewFD << R;
5828    }
5829  }
5830  return Redeclaration;
5831}
5832
5833void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5834  // C++11 [basic.start.main]p3:  A program that declares main to be inline,
5835  //   static or constexpr is ill-formed.
5836  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
5837  //   shall not appear in a declaration of main.
5838  // static main is not an error under C99, but we should warn about it.
5839  if (FD->getStorageClass() == SC_Static)
5840    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
5841         ? diag::err_static_main : diag::warn_static_main)
5842      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5843  if (FD->isInlineSpecified())
5844    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5845      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5846  if (FD->isConstexpr()) {
5847    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5848      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5849    FD->setConstexpr(false);
5850  }
5851
5852  QualType T = FD->getType();
5853  assert(T->isFunctionType() && "function decl is not of function type");
5854  const FunctionType* FT = T->castAs<FunctionType>();
5855
5856  // All the standards say that main() should should return 'int'.
5857  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5858    // In C and C++, main magically returns 0 if you fall off the end;
5859    // set the flag which tells us that.
5860    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5861    FD->setHasImplicitReturnZero(true);
5862
5863  // In C with GNU extensions we allow main() to have non-integer return
5864  // type, but we should warn about the extension, and we disable the
5865  // implicit-return-zero rule.
5866  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
5867    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5868
5869  // Otherwise, this is just a flat-out error.
5870  } else {
5871    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5872    FD->setInvalidDecl(true);
5873  }
5874
5875  // Treat protoless main() as nullary.
5876  if (isa<FunctionNoProtoType>(FT)) return;
5877
5878  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5879  unsigned nparams = FTP->getNumArgs();
5880  assert(FD->getNumParams() == nparams);
5881
5882  bool HasExtraParameters = (nparams > 3);
5883
5884  // Darwin passes an undocumented fourth argument of type char**.  If
5885  // other platforms start sprouting these, the logic below will start
5886  // getting shifty.
5887  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5888    HasExtraParameters = false;
5889
5890  if (HasExtraParameters) {
5891    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5892    FD->setInvalidDecl(true);
5893    nparams = 3;
5894  }
5895
5896  // FIXME: a lot of the following diagnostics would be improved
5897  // if we had some location information about types.
5898
5899  QualType CharPP =
5900    Context.getPointerType(Context.getPointerType(Context.CharTy));
5901  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5902
5903  for (unsigned i = 0; i < nparams; ++i) {
5904    QualType AT = FTP->getArgType(i);
5905
5906    bool mismatch = true;
5907
5908    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5909      mismatch = false;
5910    else if (Expected[i] == CharPP) {
5911      // As an extension, the following forms are okay:
5912      //   char const **
5913      //   char const * const *
5914      //   char * const *
5915
5916      QualifierCollector qs;
5917      const PointerType* PT;
5918      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5919          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5920          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5921        qs.removeConst();
5922        mismatch = !qs.empty();
5923      }
5924    }
5925
5926    if (mismatch) {
5927      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5928      // TODO: suggest replacing given type with expected type
5929      FD->setInvalidDecl(true);
5930    }
5931  }
5932
5933  if (nparams == 1 && !FD->isInvalidDecl()) {
5934    Diag(FD->getLocation(), diag::warn_main_one_arg);
5935  }
5936
5937  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5938    Diag(FD->getLocation(), diag::err_main_template_decl);
5939    FD->setInvalidDecl();
5940  }
5941}
5942
5943bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
5944  // FIXME: Need strict checking.  In C89, we need to check for
5945  // any assignment, increment, decrement, function-calls, or
5946  // commas outside of a sizeof.  In C99, it's the same list,
5947  // except that the aforementioned are allowed in unevaluated
5948  // expressions.  Everything else falls under the
5949  // "may accept other forms of constant expressions" exception.
5950  // (We never end up here for C++, so the constant expression
5951  // rules there don't matter.)
5952  if (Init->isConstantInitializer(Context, false))
5953    return false;
5954  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5955    << Init->getSourceRange();
5956  return true;
5957}
5958
5959namespace {
5960  // Visits an initialization expression to see if OrigDecl is evaluated in
5961  // its own initialization and throws a warning if it does.
5962  class SelfReferenceChecker
5963      : public EvaluatedExprVisitor<SelfReferenceChecker> {
5964    Sema &S;
5965    Decl *OrigDecl;
5966    bool isRecordType;
5967    bool isPODType;
5968
5969  public:
5970    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5971
5972    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5973                                                    S(S), OrigDecl(OrigDecl) {
5974      isPODType = false;
5975      isRecordType = false;
5976      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
5977        isPODType = VD->getType().isPODType(S.Context);
5978        isRecordType = VD->getType()->isRecordType();
5979      }
5980    }
5981
5982    void VisitExpr(Expr *E) {
5983      if (isa<ObjCMessageExpr>(*E)) return;
5984      if (isRecordType) {
5985        Expr *expr = E;
5986        if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5987          ValueDecl *VD = ME->getMemberDecl();
5988          if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
5989          expr = ME->getBase();
5990        }
5991        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
5992          HandleDeclRefExpr(DRE);
5993          return;
5994        }
5995      }
5996      Inherited::VisitExpr(E);
5997    }
5998
5999    void VisitMemberExpr(MemberExpr *E) {
6000      if (E->getType()->canDecayToPointerType()) return;
6001      ValueDecl *VD = E->getMemberDecl();
6002      if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
6003        if (DeclRefExpr *DRE
6004              = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6005          HandleDeclRefExpr(DRE);
6006          return;
6007        }
6008      Inherited::VisitMemberExpr(E);
6009    }
6010
6011    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6012      if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6013          (isRecordType && E->getCastKind() == CK_NoOp)) {
6014        Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6015        if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6016          SubExpr = ME->getBase()->IgnoreParenImpCasts();
6017        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6018          HandleDeclRefExpr(DRE);
6019          return;
6020        }
6021      }
6022      Inherited::VisitImplicitCastExpr(E);
6023    }
6024
6025    void VisitUnaryOperator(UnaryOperator *E) {
6026      // For POD record types, addresses of its own members are well-defined.
6027      if (isRecordType && isPODType) return;
6028      Inherited::VisitUnaryOperator(E);
6029    }
6030
6031    void HandleDeclRefExpr(DeclRefExpr *DRE) {
6032      Decl* ReferenceDecl = DRE->getDecl();
6033      if (OrigDecl != ReferenceDecl) return;
6034      LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6035                          Sema::NotForRedeclaration);
6036      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6037                            S.PDiag(diag::warn_uninit_self_reference_in_init)
6038                              << Result.getLookupName()
6039                              << OrigDecl->getLocation()
6040                              << DRE->getSourceRange());
6041    }
6042  };
6043}
6044
6045/// CheckSelfReference - Warns if OrigDecl is used in expression E.
6046void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6047  SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6048}
6049
6050/// AddInitializerToDecl - Adds the initializer Init to the
6051/// declaration dcl. If DirectInit is true, this is C++ direct
6052/// initialization rather than copy initialization.
6053void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6054                                bool DirectInit, bool TypeMayContainAuto) {
6055  // If there is no declaration, there was an error parsing it.  Just ignore
6056  // the initializer.
6057  if (RealDecl == 0 || RealDecl->isInvalidDecl())
6058    return;
6059
6060  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6061    // With declarators parsed the way they are, the parser cannot
6062    // distinguish between a normal initializer and a pure-specifier.
6063    // Thus this grotesque test.
6064    IntegerLiteral *IL;
6065    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6066        Context.getCanonicalType(IL->getType()) == Context.IntTy)
6067      CheckPureMethod(Method, Init->getSourceRange());
6068    else {
6069      Diag(Method->getLocation(), diag::err_member_function_initialization)
6070        << Method->getDeclName() << Init->getSourceRange();
6071      Method->setInvalidDecl();
6072    }
6073    return;
6074  }
6075
6076  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6077  if (!VDecl) {
6078    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6079    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6080    RealDecl->setInvalidDecl();
6081    return;
6082  }
6083
6084  // Check for self-references within variable initializers.
6085  // Variables declared within a function/method body are handled
6086  // by a dataflow analysis.
6087  if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6088    CheckSelfReference(RealDecl, Init);
6089
6090  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6091
6092  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6093  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
6094    Expr *DeduceInit = Init;
6095    // Initializer could be a C++ direct-initializer. Deduction only works if it
6096    // contains exactly one expression.
6097    if (CXXDirectInit) {
6098      if (CXXDirectInit->getNumExprs() == 0) {
6099        // It isn't possible to write this directly, but it is possible to
6100        // end up in this situation with "auto x(some_pack...);"
6101        Diag(CXXDirectInit->getLocStart(),
6102             diag::err_auto_var_init_no_expression)
6103          << VDecl->getDeclName() << VDecl->getType()
6104          << VDecl->getSourceRange();
6105        RealDecl->setInvalidDecl();
6106        return;
6107      } else if (CXXDirectInit->getNumExprs() > 1) {
6108        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6109             diag::err_auto_var_init_multiple_expressions)
6110          << VDecl->getDeclName() << VDecl->getType()
6111          << VDecl->getSourceRange();
6112        RealDecl->setInvalidDecl();
6113        return;
6114      } else {
6115        DeduceInit = CXXDirectInit->getExpr(0);
6116      }
6117    }
6118    TypeSourceInfo *DeducedType = 0;
6119    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6120            DAR_Failed)
6121      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6122    if (!DeducedType) {
6123      RealDecl->setInvalidDecl();
6124      return;
6125    }
6126    VDecl->setTypeSourceInfo(DeducedType);
6127    VDecl->setType(DeducedType->getType());
6128    VDecl->ClearLinkageCache();
6129
6130    // In ARC, infer lifetime.
6131    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6132      VDecl->setInvalidDecl();
6133
6134    // If this is a redeclaration, check that the type we just deduced matches
6135    // the previously declared type.
6136    if (VarDecl *Old = VDecl->getPreviousDecl())
6137      MergeVarDeclTypes(VDecl, Old);
6138  }
6139
6140  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6141    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6142    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6143    VDecl->setInvalidDecl();
6144    return;
6145  }
6146
6147  if (!VDecl->getType()->isDependentType()) {
6148    // A definition must end up with a complete type, which means it must be
6149    // complete with the restriction that an array type might be completed by
6150    // the initializer; note that later code assumes this restriction.
6151    QualType BaseDeclType = VDecl->getType();
6152    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6153      BaseDeclType = Array->getElementType();
6154    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6155                            diag::err_typecheck_decl_incomplete_type)) {
6156      RealDecl->setInvalidDecl();
6157      return;
6158    }
6159
6160    // The variable can not have an abstract class type.
6161    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6162                               diag::err_abstract_type_in_decl,
6163                               AbstractVariableType))
6164      VDecl->setInvalidDecl();
6165  }
6166
6167  const VarDecl *Def;
6168  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6169    Diag(VDecl->getLocation(), diag::err_redefinition)
6170      << VDecl->getDeclName();
6171    Diag(Def->getLocation(), diag::note_previous_definition);
6172    VDecl->setInvalidDecl();
6173    return;
6174  }
6175
6176  const VarDecl* PrevInit = 0;
6177  if (getLangOpts().CPlusPlus) {
6178    // C++ [class.static.data]p4
6179    //   If a static data member is of const integral or const
6180    //   enumeration type, its declaration in the class definition can
6181    //   specify a constant-initializer which shall be an integral
6182    //   constant expression (5.19). In that case, the member can appear
6183    //   in integral constant expressions. The member shall still be
6184    //   defined in a namespace scope if it is used in the program and the
6185    //   namespace scope definition shall not contain an initializer.
6186    //
6187    // We already performed a redefinition check above, but for static
6188    // data members we also need to check whether there was an in-class
6189    // declaration with an initializer.
6190    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6191      Diag(VDecl->getLocation(), diag::err_redefinition)
6192        << VDecl->getDeclName();
6193      Diag(PrevInit->getLocation(), diag::note_previous_definition);
6194      return;
6195    }
6196
6197    if (VDecl->hasLocalStorage())
6198      getCurFunction()->setHasBranchProtectedScope();
6199
6200    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6201      VDecl->setInvalidDecl();
6202      return;
6203    }
6204  }
6205
6206  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6207  // a kernel function cannot be initialized."
6208  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6209    Diag(VDecl->getLocation(), diag::err_local_cant_init);
6210    VDecl->setInvalidDecl();
6211    return;
6212  }
6213
6214  // Get the decls type and save a reference for later, since
6215  // CheckInitializerTypes may change it.
6216  QualType DclT = VDecl->getType(), SavT = DclT;
6217
6218  // Top-level message sends default to 'id' when we're in a debugger
6219  // and we are assigning it to a variable of 'id' type.
6220  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6221    if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6222      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6223      if (Result.isInvalid()) {
6224        VDecl->setInvalidDecl();
6225        return;
6226      }
6227      Init = Result.take();
6228    }
6229
6230  // Perform the initialization.
6231  if (!VDecl->isInvalidDecl()) {
6232    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6233    InitializationKind Kind
6234      = DirectInit ?
6235          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6236                                                           Init->getLocStart(),
6237                                                           Init->getLocEnd())
6238                        : InitializationKind::CreateDirectList(
6239                                                          VDecl->getLocation())
6240                   : InitializationKind::CreateCopy(VDecl->getLocation(),
6241                                                    Init->getLocStart());
6242
6243    Expr **Args = &Init;
6244    unsigned NumArgs = 1;
6245    if (CXXDirectInit) {
6246      Args = CXXDirectInit->getExprs();
6247      NumArgs = CXXDirectInit->getNumExprs();
6248    }
6249    InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6250    ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6251                                              MultiExprArg(*this, Args,NumArgs),
6252                                              &DclT);
6253    if (Result.isInvalid()) {
6254      VDecl->setInvalidDecl();
6255      return;
6256    }
6257
6258    Init = Result.takeAs<Expr>();
6259  }
6260
6261  // If the type changed, it means we had an incomplete type that was
6262  // completed by the initializer. For example:
6263  //   int ary[] = { 1, 3, 5 };
6264  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6265  if (!VDecl->isInvalidDecl() && (DclT != SavT))
6266    VDecl->setType(DclT);
6267
6268  // Check any implicit conversions within the expression.
6269  CheckImplicitConversions(Init, VDecl->getLocation());
6270
6271  if (!VDecl->isInvalidDecl())
6272    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6273
6274  Init = MaybeCreateExprWithCleanups(Init);
6275  // Attach the initializer to the decl.
6276  VDecl->setInit(Init);
6277
6278  if (VDecl->isLocalVarDecl()) {
6279    // C99 6.7.8p4: All the expressions in an initializer for an object that has
6280    // static storage duration shall be constant expressions or string literals.
6281    // C++ does not have this restriction.
6282    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6283        VDecl->getStorageClass() == SC_Static)
6284      CheckForConstantInitializer(Init, DclT);
6285  } else if (VDecl->isStaticDataMember() &&
6286             VDecl->getLexicalDeclContext()->isRecord()) {
6287    // This is an in-class initialization for a static data member, e.g.,
6288    //
6289    // struct S {
6290    //   static const int value = 17;
6291    // };
6292
6293    // C++ [class.mem]p4:
6294    //   A member-declarator can contain a constant-initializer only
6295    //   if it declares a static member (9.4) of const integral or
6296    //   const enumeration type, see 9.4.2.
6297    //
6298    // C++11 [class.static.data]p3:
6299    //   If a non-volatile const static data member is of integral or
6300    //   enumeration type, its declaration in the class definition can
6301    //   specify a brace-or-equal-initializer in which every initalizer-clause
6302    //   that is an assignment-expression is a constant expression. A static
6303    //   data member of literal type can be declared in the class definition
6304    //   with the constexpr specifier; if so, its declaration shall specify a
6305    //   brace-or-equal-initializer in which every initializer-clause that is
6306    //   an assignment-expression is a constant expression.
6307
6308    // Do nothing on dependent types.
6309    if (DclT->isDependentType()) {
6310
6311    // Allow any 'static constexpr' members, whether or not they are of literal
6312    // type. We separately check that every constexpr variable is of literal
6313    // type.
6314    } else if (VDecl->isConstexpr()) {
6315
6316    // Require constness.
6317    } else if (!DclT.isConstQualified()) {
6318      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6319        << Init->getSourceRange();
6320      VDecl->setInvalidDecl();
6321
6322    // We allow integer constant expressions in all cases.
6323    } else if (DclT->isIntegralOrEnumerationType()) {
6324      // Check whether the expression is a constant expression.
6325      SourceLocation Loc;
6326      if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6327        // In C++11, a non-constexpr const static data member with an
6328        // in-class initializer cannot be volatile.
6329        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6330      else if (Init->isValueDependent())
6331        ; // Nothing to check.
6332      else if (Init->isIntegerConstantExpr(Context, &Loc))
6333        ; // Ok, it's an ICE!
6334      else if (Init->isEvaluatable(Context)) {
6335        // If we can constant fold the initializer through heroics, accept it,
6336        // but report this as a use of an extension for -pedantic.
6337        Diag(Loc, diag::ext_in_class_initializer_non_constant)
6338          << Init->getSourceRange();
6339      } else {
6340        // Otherwise, this is some crazy unknown case.  Report the issue at the
6341        // location provided by the isIntegerConstantExpr failed check.
6342        Diag(Loc, diag::err_in_class_initializer_non_constant)
6343          << Init->getSourceRange();
6344        VDecl->setInvalidDecl();
6345      }
6346
6347    // We allow foldable floating-point constants as an extension.
6348    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6349      Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6350        << DclT << Init->getSourceRange();
6351      if (getLangOpts().CPlusPlus0x)
6352        Diag(VDecl->getLocation(),
6353             diag::note_in_class_initializer_float_type_constexpr)
6354          << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6355
6356      if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6357        Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6358          << Init->getSourceRange();
6359        VDecl->setInvalidDecl();
6360      }
6361
6362    // Suggest adding 'constexpr' in C++11 for literal types.
6363    } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6364      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6365        << DclT << Init->getSourceRange()
6366        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6367      VDecl->setConstexpr(true);
6368
6369    } else {
6370      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6371        << DclT << Init->getSourceRange();
6372      VDecl->setInvalidDecl();
6373    }
6374  } else if (VDecl->isFileVarDecl()) {
6375    if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6376        (!getLangOpts().CPlusPlus ||
6377         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6378      Diag(VDecl->getLocation(), diag::warn_extern_init);
6379
6380    // C99 6.7.8p4. All file scoped initializers need to be constant.
6381    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6382      CheckForConstantInitializer(Init, DclT);
6383  }
6384
6385  // We will represent direct-initialization similarly to copy-initialization:
6386  //    int x(1);  -as-> int x = 1;
6387  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6388  //
6389  // Clients that want to distinguish between the two forms, can check for
6390  // direct initializer using VarDecl::getInitStyle().
6391  // A major benefit is that clients that don't particularly care about which
6392  // exactly form was it (like the CodeGen) can handle both cases without
6393  // special case code.
6394
6395  // C++ 8.5p11:
6396  // The form of initialization (using parentheses or '=') is generally
6397  // insignificant, but does matter when the entity being initialized has a
6398  // class type.
6399  if (CXXDirectInit) {
6400    assert(DirectInit && "Call-style initializer must be direct init.");
6401    VDecl->setInitStyle(VarDecl::CallInit);
6402  } else if (DirectInit) {
6403    // This must be list-initialization. No other way is direct-initialization.
6404    VDecl->setInitStyle(VarDecl::ListInit);
6405  }
6406
6407  CheckCompleteVariableDeclaration(VDecl);
6408}
6409
6410/// ActOnInitializerError - Given that there was an error parsing an
6411/// initializer for the given declaration, try to return to some form
6412/// of sanity.
6413void Sema::ActOnInitializerError(Decl *D) {
6414  // Our main concern here is re-establishing invariants like "a
6415  // variable's type is either dependent or complete".
6416  if (!D || D->isInvalidDecl()) return;
6417
6418  VarDecl *VD = dyn_cast<VarDecl>(D);
6419  if (!VD) return;
6420
6421  // Auto types are meaningless if we can't make sense of the initializer.
6422  if (ParsingInitForAutoVars.count(D)) {
6423    D->setInvalidDecl();
6424    return;
6425  }
6426
6427  QualType Ty = VD->getType();
6428  if (Ty->isDependentType()) return;
6429
6430  // Require a complete type.
6431  if (RequireCompleteType(VD->getLocation(),
6432                          Context.getBaseElementType(Ty),
6433                          diag::err_typecheck_decl_incomplete_type)) {
6434    VD->setInvalidDecl();
6435    return;
6436  }
6437
6438  // Require an abstract type.
6439  if (RequireNonAbstractType(VD->getLocation(), Ty,
6440                             diag::err_abstract_type_in_decl,
6441                             AbstractVariableType)) {
6442    VD->setInvalidDecl();
6443    return;
6444  }
6445
6446  // Don't bother complaining about constructors or destructors,
6447  // though.
6448}
6449
6450void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6451                                  bool TypeMayContainAuto) {
6452  // If there is no declaration, there was an error parsing it. Just ignore it.
6453  if (RealDecl == 0)
6454    return;
6455
6456  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6457    QualType Type = Var->getType();
6458
6459    // C++11 [dcl.spec.auto]p3
6460    if (TypeMayContainAuto && Type->getContainedAutoType()) {
6461      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6462        << Var->getDeclName() << Type;
6463      Var->setInvalidDecl();
6464      return;
6465    }
6466
6467    // C++11 [class.static.data]p3: A static data member can be declared with
6468    // the constexpr specifier; if so, its declaration shall specify
6469    // a brace-or-equal-initializer.
6470    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6471    // the definition of a variable [...] or the declaration of a static data
6472    // member.
6473    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6474      if (Var->isStaticDataMember())
6475        Diag(Var->getLocation(),
6476             diag::err_constexpr_static_mem_var_requires_init)
6477          << Var->getDeclName();
6478      else
6479        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
6480      Var->setInvalidDecl();
6481      return;
6482    }
6483
6484    switch (Var->isThisDeclarationADefinition()) {
6485    case VarDecl::Definition:
6486      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6487        break;
6488
6489      // We have an out-of-line definition of a static data member
6490      // that has an in-class initializer, so we type-check this like
6491      // a declaration.
6492      //
6493      // Fall through
6494
6495    case VarDecl::DeclarationOnly:
6496      // It's only a declaration.
6497
6498      // Block scope. C99 6.7p7: If an identifier for an object is
6499      // declared with no linkage (C99 6.2.2p6), the type for the
6500      // object shall be complete.
6501      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
6502          !Var->getLinkage() && !Var->isInvalidDecl() &&
6503          RequireCompleteType(Var->getLocation(), Type,
6504                              diag::err_typecheck_decl_incomplete_type))
6505        Var->setInvalidDecl();
6506
6507      // Make sure that the type is not abstract.
6508      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6509          RequireNonAbstractType(Var->getLocation(), Type,
6510                                 diag::err_abstract_type_in_decl,
6511                                 AbstractVariableType))
6512        Var->setInvalidDecl();
6513      return;
6514
6515    case VarDecl::TentativeDefinition:
6516      // File scope. C99 6.9.2p2: A declaration of an identifier for an
6517      // object that has file scope without an initializer, and without a
6518      // storage-class specifier or with the storage-class specifier "static",
6519      // constitutes a tentative definition. Note: A tentative definition with
6520      // external linkage is valid (C99 6.2.2p5).
6521      if (!Var->isInvalidDecl()) {
6522        if (const IncompleteArrayType *ArrayT
6523                                    = Context.getAsIncompleteArrayType(Type)) {
6524          if (RequireCompleteType(Var->getLocation(),
6525                                  ArrayT->getElementType(),
6526                                  diag::err_illegal_decl_array_incomplete_type))
6527            Var->setInvalidDecl();
6528        } else if (Var->getStorageClass() == SC_Static) {
6529          // C99 6.9.2p3: If the declaration of an identifier for an object is
6530          // a tentative definition and has internal linkage (C99 6.2.2p3), the
6531          // declared type shall not be an incomplete type.
6532          // NOTE: code such as the following
6533          //     static struct s;
6534          //     struct s { int a; };
6535          // is accepted by gcc. Hence here we issue a warning instead of
6536          // an error and we do not invalidate the static declaration.
6537          // NOTE: to avoid multiple warnings, only check the first declaration.
6538          if (Var->getPreviousDecl() == 0)
6539            RequireCompleteType(Var->getLocation(), Type,
6540                                diag::ext_typecheck_decl_incomplete_type);
6541        }
6542      }
6543
6544      // Record the tentative definition; we're done.
6545      if (!Var->isInvalidDecl())
6546        TentativeDefinitions.push_back(Var);
6547      return;
6548    }
6549
6550    // Provide a specific diagnostic for uninitialized variable
6551    // definitions with incomplete array type.
6552    if (Type->isIncompleteArrayType()) {
6553      Diag(Var->getLocation(),
6554           diag::err_typecheck_incomplete_array_needs_initializer);
6555      Var->setInvalidDecl();
6556      return;
6557    }
6558
6559    // Provide a specific diagnostic for uninitialized variable
6560    // definitions with reference type.
6561    if (Type->isReferenceType()) {
6562      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6563        << Var->getDeclName()
6564        << SourceRange(Var->getLocation(), Var->getLocation());
6565      Var->setInvalidDecl();
6566      return;
6567    }
6568
6569    // Do not attempt to type-check the default initializer for a
6570    // variable with dependent type.
6571    if (Type->isDependentType())
6572      return;
6573
6574    if (Var->isInvalidDecl())
6575      return;
6576
6577    if (RequireCompleteType(Var->getLocation(),
6578                            Context.getBaseElementType(Type),
6579                            diag::err_typecheck_decl_incomplete_type)) {
6580      Var->setInvalidDecl();
6581      return;
6582    }
6583
6584    // The variable can not have an abstract class type.
6585    if (RequireNonAbstractType(Var->getLocation(), Type,
6586                               diag::err_abstract_type_in_decl,
6587                               AbstractVariableType)) {
6588      Var->setInvalidDecl();
6589      return;
6590    }
6591
6592    // Check for jumps past the implicit initializer.  C++0x
6593    // clarifies that this applies to a "variable with automatic
6594    // storage duration", not a "local variable".
6595    // C++11 [stmt.dcl]p3
6596    //   A program that jumps from a point where a variable with automatic
6597    //   storage duration is not in scope to a point where it is in scope is
6598    //   ill-formed unless the variable has scalar type, class type with a
6599    //   trivial default constructor and a trivial destructor, a cv-qualified
6600    //   version of one of these types, or an array of one of the preceding
6601    //   types and is declared without an initializer.
6602    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
6603      if (const RecordType *Record
6604            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6605        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6606        // Mark the function for further checking even if the looser rules of
6607        // C++11 do not require such checks, so that we can diagnose
6608        // incompatibilities with C++98.
6609        if (!CXXRecord->isPOD())
6610          getCurFunction()->setHasBranchProtectedScope();
6611      }
6612    }
6613
6614    // C++03 [dcl.init]p9:
6615    //   If no initializer is specified for an object, and the
6616    //   object is of (possibly cv-qualified) non-POD class type (or
6617    //   array thereof), the object shall be default-initialized; if
6618    //   the object is of const-qualified type, the underlying class
6619    //   type shall have a user-declared default
6620    //   constructor. Otherwise, if no initializer is specified for
6621    //   a non- static object, the object and its subobjects, if
6622    //   any, have an indeterminate initial value); if the object
6623    //   or any of its subobjects are of const-qualified type, the
6624    //   program is ill-formed.
6625    // C++0x [dcl.init]p11:
6626    //   If no initializer is specified for an object, the object is
6627    //   default-initialized; [...].
6628    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6629    InitializationKind Kind
6630      = InitializationKind::CreateDefault(Var->getLocation());
6631
6632    InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6633    ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6634                                      MultiExprArg(*this, 0, 0));
6635    if (Init.isInvalid())
6636      Var->setInvalidDecl();
6637    else if (Init.get()) {
6638      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6639      // This is important for template substitution.
6640      Var->setInitStyle(VarDecl::CallInit);
6641    }
6642
6643    CheckCompleteVariableDeclaration(Var);
6644  }
6645}
6646
6647void Sema::ActOnCXXForRangeDecl(Decl *D) {
6648  VarDecl *VD = dyn_cast<VarDecl>(D);
6649  if (!VD) {
6650    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6651    D->setInvalidDecl();
6652    return;
6653  }
6654
6655  VD->setCXXForRangeDecl(true);
6656
6657  // for-range-declaration cannot be given a storage class specifier.
6658  int Error = -1;
6659  switch (VD->getStorageClassAsWritten()) {
6660  case SC_None:
6661    break;
6662  case SC_Extern:
6663    Error = 0;
6664    break;
6665  case SC_Static:
6666    Error = 1;
6667    break;
6668  case SC_PrivateExtern:
6669    Error = 2;
6670    break;
6671  case SC_Auto:
6672    Error = 3;
6673    break;
6674  case SC_Register:
6675    Error = 4;
6676    break;
6677  case SC_OpenCLWorkGroupLocal:
6678    llvm_unreachable("Unexpected storage class");
6679  }
6680  if (VD->isConstexpr())
6681    Error = 5;
6682  if (Error != -1) {
6683    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6684      << VD->getDeclName() << Error;
6685    D->setInvalidDecl();
6686  }
6687}
6688
6689void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6690  if (var->isInvalidDecl()) return;
6691
6692  // In ARC, don't allow jumps past the implicit initialization of a
6693  // local retaining variable.
6694  if (getLangOpts().ObjCAutoRefCount &&
6695      var->hasLocalStorage()) {
6696    switch (var->getType().getObjCLifetime()) {
6697    case Qualifiers::OCL_None:
6698    case Qualifiers::OCL_ExplicitNone:
6699    case Qualifiers::OCL_Autoreleasing:
6700      break;
6701
6702    case Qualifiers::OCL_Weak:
6703    case Qualifiers::OCL_Strong:
6704      getCurFunction()->setHasBranchProtectedScope();
6705      break;
6706    }
6707  }
6708
6709  // All the following checks are C++ only.
6710  if (!getLangOpts().CPlusPlus) return;
6711
6712  QualType baseType = Context.getBaseElementType(var->getType());
6713  if (baseType->isDependentType()) return;
6714
6715  // __block variables might require us to capture a copy-initializer.
6716  if (var->hasAttr<BlocksAttr>()) {
6717    // It's currently invalid to ever have a __block variable with an
6718    // array type; should we diagnose that here?
6719
6720    // Regardless, we don't want to ignore array nesting when
6721    // constructing this copy.
6722    QualType type = var->getType();
6723
6724    if (type->isStructureOrClassType()) {
6725      SourceLocation poi = var->getLocation();
6726      Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
6727      ExprResult result =
6728        PerformCopyInitialization(
6729                        InitializedEntity::InitializeBlock(poi, type, false),
6730                                  poi, Owned(varRef));
6731      if (!result.isInvalid()) {
6732        result = MaybeCreateExprWithCleanups(result);
6733        Expr *init = result.takeAs<Expr>();
6734        Context.setBlockVarCopyInits(var, init);
6735      }
6736    }
6737  }
6738
6739  Expr *Init = var->getInit();
6740  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6741
6742  if (!var->getDeclContext()->isDependentContext() && Init) {
6743    if (IsGlobal && !var->isConstexpr() &&
6744        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6745                                            var->getLocation())
6746          != DiagnosticsEngine::Ignored &&
6747        !Init->isConstantInitializer(Context, baseType->isReferenceType()))
6748      Diag(var->getLocation(), diag::warn_global_constructor)
6749        << Init->getSourceRange();
6750
6751    if (var->isConstexpr()) {
6752      llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6753      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6754        SourceLocation DiagLoc = var->getLocation();
6755        // If the note doesn't add any useful information other than a source
6756        // location, fold it into the primary diagnostic.
6757        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6758              diag::note_invalid_subexpr_in_const_expr) {
6759          DiagLoc = Notes[0].first;
6760          Notes.clear();
6761        }
6762        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6763          << var << Init->getSourceRange();
6764        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6765          Diag(Notes[I].first, Notes[I].second);
6766      }
6767    } else if (var->isUsableInConstantExpressions(Context)) {
6768      // Check whether the initializer of a const variable of integral or
6769      // enumeration type is an ICE now, since we can't tell whether it was
6770      // initialized by a constant expression if we check later.
6771      var->checkInitIsICE();
6772    }
6773  }
6774
6775  // Require the destructor.
6776  if (const RecordType *recordType = baseType->getAs<RecordType>())
6777    FinalizeVarWithDestructor(var, recordType);
6778}
6779
6780/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6781/// any semantic actions necessary after any initializer has been attached.
6782void
6783Sema::FinalizeDeclaration(Decl *ThisDecl) {
6784  // Note that we are no longer parsing the initializer for this declaration.
6785  ParsingInitForAutoVars.erase(ThisDecl);
6786}
6787
6788Sema::DeclGroupPtrTy
6789Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6790                              Decl **Group, unsigned NumDecls) {
6791  SmallVector<Decl*, 8> Decls;
6792
6793  if (DS.isTypeSpecOwned())
6794    Decls.push_back(DS.getRepAsDecl());
6795
6796  for (unsigned i = 0; i != NumDecls; ++i)
6797    if (Decl *D = Group[i])
6798      Decls.push_back(D);
6799
6800  return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6801                              DS.getTypeSpecType() == DeclSpec::TST_auto);
6802}
6803
6804/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6805/// group, performing any necessary semantic checking.
6806Sema::DeclGroupPtrTy
6807Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6808                           bool TypeMayContainAuto) {
6809  // C++0x [dcl.spec.auto]p7:
6810  //   If the type deduced for the template parameter U is not the same in each
6811  //   deduction, the program is ill-formed.
6812  // FIXME: When initializer-list support is added, a distinction is needed
6813  // between the deduced type U and the deduced type which 'auto' stands for.
6814  //   auto a = 0, b = { 1, 2, 3 };
6815  // is legal because the deduced type U is 'int' in both cases.
6816  if (TypeMayContainAuto && NumDecls > 1) {
6817    QualType Deduced;
6818    CanQualType DeducedCanon;
6819    VarDecl *DeducedDecl = 0;
6820    for (unsigned i = 0; i != NumDecls; ++i) {
6821      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6822        AutoType *AT = D->getType()->getContainedAutoType();
6823        // Don't reissue diagnostics when instantiating a template.
6824        if (AT && D->isInvalidDecl())
6825          break;
6826        if (AT && AT->isDeduced()) {
6827          QualType U = AT->getDeducedType();
6828          CanQualType UCanon = Context.getCanonicalType(U);
6829          if (Deduced.isNull()) {
6830            Deduced = U;
6831            DeducedCanon = UCanon;
6832            DeducedDecl = D;
6833          } else if (DeducedCanon != UCanon) {
6834            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6835                 diag::err_auto_different_deductions)
6836              << Deduced << DeducedDecl->getDeclName()
6837              << U << D->getDeclName()
6838              << DeducedDecl->getInit()->getSourceRange()
6839              << D->getInit()->getSourceRange();
6840            D->setInvalidDecl();
6841            break;
6842          }
6843        }
6844      }
6845    }
6846  }
6847
6848  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6849}
6850
6851
6852/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6853/// to introduce parameters into function prototype scope.
6854Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6855  const DeclSpec &DS = D.getDeclSpec();
6856
6857  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6858  // C++03 [dcl.stc]p2 also permits 'auto'.
6859  VarDecl::StorageClass StorageClass = SC_None;
6860  VarDecl::StorageClass StorageClassAsWritten = SC_None;
6861  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6862    StorageClass = SC_Register;
6863    StorageClassAsWritten = SC_Register;
6864  } else if (getLangOpts().CPlusPlus &&
6865             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6866    StorageClass = SC_Auto;
6867    StorageClassAsWritten = SC_Auto;
6868  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6869    Diag(DS.getStorageClassSpecLoc(),
6870         diag::err_invalid_storage_class_in_func_decl);
6871    D.getMutableDeclSpec().ClearStorageClassSpecs();
6872  }
6873
6874  if (D.getDeclSpec().isThreadSpecified())
6875    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6876  if (D.getDeclSpec().isConstexprSpecified())
6877    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6878      << 0;
6879
6880  DiagnoseFunctionSpecifiers(D);
6881
6882  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6883  QualType parmDeclType = TInfo->getType();
6884
6885  if (getLangOpts().CPlusPlus) {
6886    // Check that there are no default arguments inside the type of this
6887    // parameter.
6888    CheckExtraCXXDefaultArguments(D);
6889
6890    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6891    if (D.getCXXScopeSpec().isSet()) {
6892      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6893        << D.getCXXScopeSpec().getRange();
6894      D.getCXXScopeSpec().clear();
6895    }
6896  }
6897
6898  // Ensure we have a valid name
6899  IdentifierInfo *II = 0;
6900  if (D.hasName()) {
6901    II = D.getIdentifier();
6902    if (!II) {
6903      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6904        << GetNameForDeclarator(D).getName().getAsString();
6905      D.setInvalidType(true);
6906    }
6907  }
6908
6909  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6910  if (II) {
6911    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6912                   ForRedeclaration);
6913    LookupName(R, S);
6914    if (R.isSingleResult()) {
6915      NamedDecl *PrevDecl = R.getFoundDecl();
6916      if (PrevDecl->isTemplateParameter()) {
6917        // Maybe we will complain about the shadowed template parameter.
6918        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6919        // Just pretend that we didn't see the previous declaration.
6920        PrevDecl = 0;
6921      } else if (S->isDeclScope(PrevDecl)) {
6922        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6923        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6924
6925        // Recover by removing the name
6926        II = 0;
6927        D.SetIdentifier(0, D.getIdentifierLoc());
6928        D.setInvalidType(true);
6929      }
6930    }
6931  }
6932
6933  // Temporarily put parameter variables in the translation unit, not
6934  // the enclosing context.  This prevents them from accidentally
6935  // looking like class members in C++.
6936  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6937                                    D.getLocStart(),
6938                                    D.getIdentifierLoc(), II,
6939                                    parmDeclType, TInfo,
6940                                    StorageClass, StorageClassAsWritten);
6941
6942  if (D.isInvalidType())
6943    New->setInvalidDecl();
6944
6945  assert(S->isFunctionPrototypeScope());
6946  assert(S->getFunctionPrototypeDepth() >= 1);
6947  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6948                    S->getNextFunctionPrototypeIndex());
6949
6950  // Add the parameter declaration into this scope.
6951  S->AddDecl(New);
6952  if (II)
6953    IdResolver.AddDecl(New);
6954
6955  ProcessDeclAttributes(S, New, D);
6956
6957  if (D.getDeclSpec().isModulePrivateSpecified())
6958    Diag(New->getLocation(), diag::err_module_private_local)
6959      << 1 << New->getDeclName()
6960      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6961      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6962
6963  if (New->hasAttr<BlocksAttr>()) {
6964    Diag(New->getLocation(), diag::err_block_on_nonlocal);
6965  }
6966  return New;
6967}
6968
6969/// \brief Synthesizes a variable for a parameter arising from a
6970/// typedef.
6971ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6972                                              SourceLocation Loc,
6973                                              QualType T) {
6974  /* FIXME: setting StartLoc == Loc.
6975     Would it be worth to modify callers so as to provide proper source
6976     location for the unnamed parameters, embedding the parameter's type? */
6977  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
6978                                T, Context.getTrivialTypeSourceInfo(T, Loc),
6979                                           SC_None, SC_None, 0);
6980  Param->setImplicit();
6981  return Param;
6982}
6983
6984void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6985                                    ParmVarDecl * const *ParamEnd) {
6986  // Don't diagnose unused-parameter errors in template instantiations; we
6987  // will already have done so in the template itself.
6988  if (!ActiveTemplateInstantiations.empty())
6989    return;
6990
6991  for (; Param != ParamEnd; ++Param) {
6992    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
6993        !(*Param)->hasAttr<UnusedAttr>()) {
6994      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6995        << (*Param)->getDeclName();
6996    }
6997  }
6998}
6999
7000void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7001                                                  ParmVarDecl * const *ParamEnd,
7002                                                  QualType ReturnTy,
7003                                                  NamedDecl *D) {
7004  if (LangOpts.NumLargeByValueCopy == 0) // No check.
7005    return;
7006
7007  // Warn if the return value is pass-by-value and larger than the specified
7008  // threshold.
7009  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7010    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7011    if (Size > LangOpts.NumLargeByValueCopy)
7012      Diag(D->getLocation(), diag::warn_return_value_size)
7013          << D->getDeclName() << Size;
7014  }
7015
7016  // Warn if any parameter is pass-by-value and larger than the specified
7017  // threshold.
7018  for (; Param != ParamEnd; ++Param) {
7019    QualType T = (*Param)->getType();
7020    if (T->isDependentType() || !T.isPODType(Context))
7021      continue;
7022    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7023    if (Size > LangOpts.NumLargeByValueCopy)
7024      Diag((*Param)->getLocation(), diag::warn_parameter_size)
7025          << (*Param)->getDeclName() << Size;
7026  }
7027}
7028
7029ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7030                                  SourceLocation NameLoc, IdentifierInfo *Name,
7031                                  QualType T, TypeSourceInfo *TSInfo,
7032                                  VarDecl::StorageClass StorageClass,
7033                                  VarDecl::StorageClass StorageClassAsWritten) {
7034  // In ARC, infer a lifetime qualifier for appropriate parameter types.
7035  if (getLangOpts().ObjCAutoRefCount &&
7036      T.getObjCLifetime() == Qualifiers::OCL_None &&
7037      T->isObjCLifetimeType()) {
7038
7039    Qualifiers::ObjCLifetime lifetime;
7040
7041    // Special cases for arrays:
7042    //   - if it's const, use __unsafe_unretained
7043    //   - otherwise, it's an error
7044    if (T->isArrayType()) {
7045      if (!T.isConstQualified()) {
7046        DelayedDiagnostics.add(
7047            sema::DelayedDiagnostic::makeForbiddenType(
7048            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7049      }
7050      lifetime = Qualifiers::OCL_ExplicitNone;
7051    } else {
7052      lifetime = T->getObjCARCImplicitLifetime();
7053    }
7054    T = Context.getLifetimeQualifiedType(T, lifetime);
7055  }
7056
7057  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7058                                         Context.getAdjustedParameterType(T),
7059                                         TSInfo,
7060                                         StorageClass, StorageClassAsWritten,
7061                                         0);
7062
7063  // Parameters can not be abstract class types.
7064  // For record types, this is done by the AbstractClassUsageDiagnoser once
7065  // the class has been completely parsed.
7066  if (!CurContext->isRecord() &&
7067      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7068                             AbstractParamType))
7069    New->setInvalidDecl();
7070
7071  // Parameter declarators cannot be interface types. All ObjC objects are
7072  // passed by reference.
7073  if (T->isObjCObjectType()) {
7074    Diag(NameLoc,
7075         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7076      << FixItHint::CreateInsertion(NameLoc, "*");
7077    T = Context.getObjCObjectPointerType(T);
7078    New->setType(T);
7079  }
7080
7081  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7082  // duration shall not be qualified by an address-space qualifier."
7083  // Since all parameters have automatic store duration, they can not have
7084  // an address space.
7085  if (T.getAddressSpace() != 0) {
7086    Diag(NameLoc, diag::err_arg_with_address_space);
7087    New->setInvalidDecl();
7088  }
7089
7090  return New;
7091}
7092
7093void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7094                                           SourceLocation LocAfterDecls) {
7095  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7096
7097  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7098  // for a K&R function.
7099  if (!FTI.hasPrototype) {
7100    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7101      --i;
7102      if (FTI.ArgInfo[i].Param == 0) {
7103        SmallString<256> Code;
7104        llvm::raw_svector_ostream(Code) << "  int "
7105                                        << FTI.ArgInfo[i].Ident->getName()
7106                                        << ";\n";
7107        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7108          << FTI.ArgInfo[i].Ident
7109          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7110
7111        // Implicitly declare the argument as type 'int' for lack of a better
7112        // type.
7113        AttributeFactory attrs;
7114        DeclSpec DS(attrs);
7115        const char* PrevSpec; // unused
7116        unsigned DiagID; // unused
7117        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7118                           PrevSpec, DiagID);
7119        Declarator ParamD(DS, Declarator::KNRTypeListContext);
7120        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7121        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7122      }
7123    }
7124  }
7125}
7126
7127Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
7128                                         Declarator &D) {
7129  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7130  assert(D.isFunctionDeclarator() && "Not a function declarator!");
7131  Scope *ParentScope = FnBodyScope->getParent();
7132
7133  D.setFunctionDefinitionKind(FDK_Definition);
7134  Decl *DP = HandleDeclarator(ParentScope, D,
7135                              MultiTemplateParamsArg(*this));
7136  return ActOnStartOfFunctionDef(FnBodyScope, DP);
7137}
7138
7139static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7140  // Don't warn about invalid declarations.
7141  if (FD->isInvalidDecl())
7142    return false;
7143
7144  // Or declarations that aren't global.
7145  if (!FD->isGlobal())
7146    return false;
7147
7148  // Don't warn about C++ member functions.
7149  if (isa<CXXMethodDecl>(FD))
7150    return false;
7151
7152  // Don't warn about 'main'.
7153  if (FD->isMain())
7154    return false;
7155
7156  // Don't warn about inline functions.
7157  if (FD->isInlined())
7158    return false;
7159
7160  // Don't warn about function templates.
7161  if (FD->getDescribedFunctionTemplate())
7162    return false;
7163
7164  // Don't warn about function template specializations.
7165  if (FD->isFunctionTemplateSpecialization())
7166    return false;
7167
7168  bool MissingPrototype = true;
7169  for (const FunctionDecl *Prev = FD->getPreviousDecl();
7170       Prev; Prev = Prev->getPreviousDecl()) {
7171    // Ignore any declarations that occur in function or method
7172    // scope, because they aren't visible from the header.
7173    if (Prev->getDeclContext()->isFunctionOrMethod())
7174      continue;
7175
7176    MissingPrototype = !Prev->getType()->isFunctionProtoType();
7177    break;
7178  }
7179
7180  return MissingPrototype;
7181}
7182
7183void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7184  // Don't complain if we're in GNU89 mode and the previous definition
7185  // was an extern inline function.
7186  const FunctionDecl *Definition;
7187  if (FD->isDefined(Definition) &&
7188      !canRedefineFunction(Definition, getLangOpts())) {
7189    if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7190        Definition->getStorageClass() == SC_Extern)
7191      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7192        << FD->getDeclName() << getLangOpts().CPlusPlus;
7193    else
7194      Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7195    Diag(Definition->getLocation(), diag::note_previous_definition);
7196  }
7197}
7198
7199Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7200  // Clear the last template instantiation error context.
7201  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7202
7203  if (!D)
7204    return D;
7205  FunctionDecl *FD = 0;
7206
7207  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7208    FD = FunTmpl->getTemplatedDecl();
7209  else
7210    FD = cast<FunctionDecl>(D);
7211
7212  // Enter a new function scope
7213  PushFunctionScope();
7214
7215  // See if this is a redefinition.
7216  if (!FD->isLateTemplateParsed())
7217    CheckForFunctionRedefinition(FD);
7218
7219  // Builtin functions cannot be defined.
7220  if (unsigned BuiltinID = FD->getBuiltinID()) {
7221    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7222      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7223      FD->setInvalidDecl();
7224    }
7225  }
7226
7227  // The return type of a function definition must be complete
7228  // (C99 6.9.1p3, C++ [dcl.fct]p6).
7229  QualType ResultType = FD->getResultType();
7230  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7231      !FD->isInvalidDecl() &&
7232      RequireCompleteType(FD->getLocation(), ResultType,
7233                          diag::err_func_def_incomplete_result))
7234    FD->setInvalidDecl();
7235
7236  // GNU warning -Wmissing-prototypes:
7237  //   Warn if a global function is defined without a previous
7238  //   prototype declaration. This warning is issued even if the
7239  //   definition itself provides a prototype. The aim is to detect
7240  //   global functions that fail to be declared in header files.
7241  if (ShouldWarnAboutMissingPrototype(FD))
7242    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7243
7244  if (FnBodyScope)
7245    PushDeclContext(FnBodyScope, FD);
7246
7247  // Check the validity of our function parameters
7248  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7249                           /*CheckParameterNames=*/true);
7250
7251  // Introduce our parameters into the function scope
7252  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7253    ParmVarDecl *Param = FD->getParamDecl(p);
7254    Param->setOwningFunction(FD);
7255
7256    // If this has an identifier, add it to the scope stack.
7257    if (Param->getIdentifier() && FnBodyScope) {
7258      CheckShadow(FnBodyScope, Param);
7259
7260      PushOnScopeChains(Param, FnBodyScope);
7261    }
7262  }
7263
7264  // If we had any tags defined in the function prototype,
7265  // introduce them into the function scope.
7266  if (FnBodyScope) {
7267    for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7268           E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7269      NamedDecl *D = *I;
7270
7271      // Some of these decls (like enums) may have been pinned to the translation unit
7272      // for lack of a real context earlier. If so, remove from the translation unit
7273      // and reattach to the current context.
7274      if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7275        // Is the decl actually in the context?
7276        for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7277               DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7278          if (*DI == D) {
7279            Context.getTranslationUnitDecl()->removeDecl(D);
7280            break;
7281          }
7282        }
7283        // Either way, reassign the lexical decl context to our FunctionDecl.
7284        D->setLexicalDeclContext(CurContext);
7285      }
7286
7287      // If the decl has a non-null name, make accessible in the current scope.
7288      if (!D->getName().empty())
7289        PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7290
7291      // Similarly, dive into enums and fish their constants out, making them
7292      // accessible in this scope.
7293      if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7294        for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7295               EE = ED->enumerator_end(); EI != EE; ++EI)
7296          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7297      }
7298    }
7299  }
7300
7301  // Checking attributes of current function definition
7302  // dllimport attribute.
7303  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7304  if (DA && (!FD->getAttr<DLLExportAttr>())) {
7305    // dllimport attribute cannot be directly applied to definition.
7306    // Microsoft accepts dllimport for functions defined within class scope.
7307    if (!DA->isInherited() &&
7308        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7309      Diag(FD->getLocation(),
7310           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7311        << "dllimport";
7312      FD->setInvalidDecl();
7313      return FD;
7314    }
7315
7316    // Visual C++ appears to not think this is an issue, so only issue
7317    // a warning when Microsoft extensions are disabled.
7318    if (!LangOpts.MicrosoftExt) {
7319      // If a symbol previously declared dllimport is later defined, the
7320      // attribute is ignored in subsequent references, and a warning is
7321      // emitted.
7322      Diag(FD->getLocation(),
7323           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7324        << FD->getName() << "dllimport";
7325    }
7326  }
7327  return FD;
7328}
7329
7330/// \brief Given the set of return statements within a function body,
7331/// compute the variables that are subject to the named return value
7332/// optimization.
7333///
7334/// Each of the variables that is subject to the named return value
7335/// optimization will be marked as NRVO variables in the AST, and any
7336/// return statement that has a marked NRVO variable as its NRVO candidate can
7337/// use the named return value optimization.
7338///
7339/// This function applies a very simplistic algorithm for NRVO: if every return
7340/// statement in the function has the same NRVO candidate, that candidate is
7341/// the NRVO variable.
7342///
7343/// FIXME: Employ a smarter algorithm that accounts for multiple return
7344/// statements and the lifetimes of the NRVO candidates. We should be able to
7345/// find a maximal set of NRVO variables.
7346void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7347  ReturnStmt **Returns = Scope->Returns.data();
7348
7349  const VarDecl *NRVOCandidate = 0;
7350  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7351    if (!Returns[I]->getNRVOCandidate())
7352      return;
7353
7354    if (!NRVOCandidate)
7355      NRVOCandidate = Returns[I]->getNRVOCandidate();
7356    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7357      return;
7358  }
7359
7360  if (NRVOCandidate)
7361    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7362}
7363
7364Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7365  return ActOnFinishFunctionBody(D, move(BodyArg), false);
7366}
7367
7368Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7369                                    bool IsInstantiation) {
7370  FunctionDecl *FD = 0;
7371  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7372  if (FunTmpl)
7373    FD = FunTmpl->getTemplatedDecl();
7374  else
7375    FD = dyn_cast_or_null<FunctionDecl>(dcl);
7376
7377  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7378  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7379
7380  if (FD) {
7381    FD->setBody(Body);
7382
7383    // If the function implicitly returns zero (like 'main') or is naked,
7384    // don't complain about missing return statements.
7385    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
7386      WP.disableCheckFallThrough();
7387
7388    // MSVC permits the use of pure specifier (=0) on function definition,
7389    // defined at class scope, warn about this non standard construct.
7390    if (getLangOpts().MicrosoftExt && FD->isPure())
7391      Diag(FD->getLocation(), diag::warn_pure_function_definition);
7392
7393    if (!FD->isInvalidDecl()) {
7394      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7395      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7396                                             FD->getResultType(), FD);
7397
7398      // If this is a constructor, we need a vtable.
7399      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7400        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7401
7402      computeNRVO(Body, getCurFunction());
7403    }
7404
7405    assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7406           "Function parsing confused");
7407  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7408    assert(MD == getCurMethodDecl() && "Method parsing confused");
7409    MD->setBody(Body);
7410    if (Body)
7411      MD->setEndLoc(Body->getLocEnd());
7412    if (!MD->isInvalidDecl()) {
7413      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7414      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7415                                             MD->getResultType(), MD);
7416
7417      if (Body)
7418        computeNRVO(Body, getCurFunction());
7419    }
7420    if (ObjCShouldCallSuperDealloc) {
7421      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7422      ObjCShouldCallSuperDealloc = false;
7423    }
7424    if (ObjCShouldCallSuperFinalize) {
7425      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7426      ObjCShouldCallSuperFinalize = false;
7427    }
7428  } else {
7429    return 0;
7430  }
7431
7432  assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7433         "ObjC methods, which should have been handled in the block above.");
7434  assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7435         "ObjC methods, which should have been handled in the block above.");
7436
7437  // Verify and clean out per-function state.
7438  if (Body) {
7439    // C++ constructors that have function-try-blocks can't have return
7440    // statements in the handlers of that block. (C++ [except.handle]p14)
7441    // Verify this.
7442    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7443      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7444
7445    // Verify that gotos and switch cases don't jump into scopes illegally.
7446    if (getCurFunction()->NeedsScopeChecking() &&
7447        !dcl->isInvalidDecl() &&
7448        !hasAnyUnrecoverableErrorsInThisFunction())
7449      DiagnoseInvalidJumps(Body);
7450
7451    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7452      if (!Destructor->getParent()->isDependentType())
7453        CheckDestructor(Destructor);
7454
7455      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7456                                             Destructor->getParent());
7457    }
7458
7459    // If any errors have occurred, clear out any temporaries that may have
7460    // been leftover. This ensures that these temporaries won't be picked up for
7461    // deletion in some later function.
7462    if (PP.getDiagnostics().hasErrorOccurred() ||
7463        PP.getDiagnostics().getSuppressAllDiagnostics()) {
7464      DiscardCleanupsInEvaluationContext();
7465    } else if (!isa<FunctionTemplateDecl>(dcl)) {
7466      // Since the body is valid, issue any analysis-based warnings that are
7467      // enabled.
7468      ActivePolicy = &WP;
7469    }
7470
7471    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7472        (!CheckConstexprFunctionDecl(FD) ||
7473         !CheckConstexprFunctionBody(FD, Body)))
7474      FD->setInvalidDecl();
7475
7476    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
7477    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7478    assert(MaybeODRUseExprs.empty() &&
7479           "Leftover expressions for odr-use checking");
7480  }
7481
7482  if (!IsInstantiation)
7483    PopDeclContext();
7484
7485  PopFunctionScopeInfo(ActivePolicy, dcl);
7486
7487  // If any errors have occurred, clear out any temporaries that may have
7488  // been leftover. This ensures that these temporaries won't be picked up for
7489  // deletion in some later function.
7490  if (getDiagnostics().hasErrorOccurred()) {
7491    DiscardCleanupsInEvaluationContext();
7492  }
7493
7494  return dcl;
7495}
7496
7497
7498/// When we finish delayed parsing of an attribute, we must attach it to the
7499/// relevant Decl.
7500void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7501                                       ParsedAttributes &Attrs) {
7502  // Always attach attributes to the underlying decl.
7503  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7504    D = TD->getTemplatedDecl();
7505  ProcessDeclAttributeList(S, D, Attrs.getList());
7506}
7507
7508
7509/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7510/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7511NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7512                                          IdentifierInfo &II, Scope *S) {
7513  // Before we produce a declaration for an implicitly defined
7514  // function, see whether there was a locally-scoped declaration of
7515  // this name as a function or variable. If so, use that
7516  // (non-visible) declaration, and complain about it.
7517  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7518    = findLocallyScopedExternalDecl(&II);
7519  if (Pos != LocallyScopedExternalDecls.end()) {
7520    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7521    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7522    return Pos->second;
7523  }
7524
7525  // Extension in C99.  Legal in C90, but warn about it.
7526  unsigned diag_id;
7527  if (II.getName().startswith("__builtin_"))
7528    diag_id = diag::warn_builtin_unknown;
7529  else if (getLangOpts().C99)
7530    diag_id = diag::ext_implicit_function_decl;
7531  else
7532    diag_id = diag::warn_implicit_function_decl;
7533  Diag(Loc, diag_id) << &II;
7534
7535  // Because typo correction is expensive, only do it if the implicit
7536  // function declaration is going to be treated as an error.
7537  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7538    TypoCorrection Corrected;
7539    DeclFilterCCC<FunctionDecl> Validator;
7540    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
7541                                      LookupOrdinaryName, S, 0, Validator))) {
7542      std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7543      std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
7544      FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
7545
7546      Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7547          << FixItHint::CreateReplacement(Loc, CorrectedStr);
7548
7549      if (Func->getLocation().isValid()
7550          && !II.getName().startswith("__builtin_"))
7551        Diag(Func->getLocation(), diag::note_previous_decl)
7552            << CorrectedQuotedStr;
7553    }
7554  }
7555
7556  // Set a Declarator for the implicit definition: int foo();
7557  const char *Dummy;
7558  AttributeFactory attrFactory;
7559  DeclSpec DS(attrFactory);
7560  unsigned DiagID;
7561  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7562  (void)Error; // Silence warning.
7563  assert(!Error && "Error setting up implicit decl!");
7564  Declarator D(DS, Declarator::BlockContext);
7565  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7566                                             0, 0, true, SourceLocation(),
7567                                             SourceLocation(), SourceLocation(),
7568                                             SourceLocation(),
7569                                             EST_None, SourceLocation(),
7570                                             0, 0, 0, 0, Loc, Loc, D),
7571                DS.getAttributes(),
7572                SourceLocation());
7573  D.SetIdentifier(&II, Loc);
7574
7575  // Insert this function into translation-unit scope.
7576
7577  DeclContext *PrevDC = CurContext;
7578  CurContext = Context.getTranslationUnitDecl();
7579
7580  FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7581  FD->setImplicit();
7582
7583  CurContext = PrevDC;
7584
7585  AddKnownFunctionAttributes(FD);
7586
7587  return FD;
7588}
7589
7590/// \brief Adds any function attributes that we know a priori based on
7591/// the declaration of this function.
7592///
7593/// These attributes can apply both to implicitly-declared builtins
7594/// (like __builtin___printf_chk) or to library-declared functions
7595/// like NSLog or printf.
7596///
7597/// We need to check for duplicate attributes both here and where user-written
7598/// attributes are applied to declarations.
7599void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7600  if (FD->isInvalidDecl())
7601    return;
7602
7603  // If this is a built-in function, map its builtin attributes to
7604  // actual attributes.
7605  if (unsigned BuiltinID = FD->getBuiltinID()) {
7606    // Handle printf-formatting attributes.
7607    unsigned FormatIdx;
7608    bool HasVAListArg;
7609    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7610      if (!FD->getAttr<FormatAttr>()) {
7611        const char *fmt = "printf";
7612        unsigned int NumParams = FD->getNumParams();
7613        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7614            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7615          fmt = "NSString";
7616        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7617                                               fmt, FormatIdx+1,
7618                                               HasVAListArg ? 0 : FormatIdx+2));
7619      }
7620    }
7621    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7622                                             HasVAListArg)) {
7623     if (!FD->getAttr<FormatAttr>())
7624       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7625                                              "scanf", FormatIdx+1,
7626                                              HasVAListArg ? 0 : FormatIdx+2));
7627    }
7628
7629    // Mark const if we don't care about errno and that is the only
7630    // thing preventing the function from being const. This allows
7631    // IRgen to use LLVM intrinsics for such functions.
7632    if (!getLangOpts().MathErrno &&
7633        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7634      if (!FD->getAttr<ConstAttr>())
7635        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7636    }
7637
7638    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7639        !FD->getAttr<ReturnsTwiceAttr>())
7640      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7641    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7642      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7643    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7644      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7645  }
7646
7647  IdentifierInfo *Name = FD->getIdentifier();
7648  if (!Name)
7649    return;
7650  if ((!getLangOpts().CPlusPlus &&
7651       FD->getDeclContext()->isTranslationUnit()) ||
7652      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7653       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7654       LinkageSpecDecl::lang_c)) {
7655    // Okay: this could be a libc/libm/Objective-C function we know
7656    // about.
7657  } else
7658    return;
7659
7660  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7661    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7662    // target-specific builtins, perhaps?
7663    if (!FD->getAttr<FormatAttr>())
7664      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7665                                             "printf", 2,
7666                                             Name->isStr("vasprintf") ? 0 : 3));
7667  }
7668}
7669
7670TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7671                                    TypeSourceInfo *TInfo) {
7672  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7673  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7674
7675  if (!TInfo) {
7676    assert(D.isInvalidType() && "no declarator info for valid type");
7677    TInfo = Context.getTrivialTypeSourceInfo(T);
7678  }
7679
7680  // Scope manipulation handled by caller.
7681  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7682                                           D.getLocStart(),
7683                                           D.getIdentifierLoc(),
7684                                           D.getIdentifier(),
7685                                           TInfo);
7686
7687  // Bail out immediately if we have an invalid declaration.
7688  if (D.isInvalidType()) {
7689    NewTD->setInvalidDecl();
7690    return NewTD;
7691  }
7692
7693  if (D.getDeclSpec().isModulePrivateSpecified()) {
7694    if (CurContext->isFunctionOrMethod())
7695      Diag(NewTD->getLocation(), diag::err_module_private_local)
7696        << 2 << NewTD->getDeclName()
7697        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7698        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7699    else
7700      NewTD->setModulePrivate();
7701  }
7702
7703  // C++ [dcl.typedef]p8:
7704  //   If the typedef declaration defines an unnamed class (or
7705  //   enum), the first typedef-name declared by the declaration
7706  //   to be that class type (or enum type) is used to denote the
7707  //   class type (or enum type) for linkage purposes only.
7708  // We need to check whether the type was declared in the declaration.
7709  switch (D.getDeclSpec().getTypeSpecType()) {
7710  case TST_enum:
7711  case TST_struct:
7712  case TST_union:
7713  case TST_class: {
7714    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7715
7716    // Do nothing if the tag is not anonymous or already has an
7717    // associated typedef (from an earlier typedef in this decl group).
7718    if (tagFromDeclSpec->getIdentifier()) break;
7719    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7720
7721    // A well-formed anonymous tag must always be a TUK_Definition.
7722    assert(tagFromDeclSpec->isThisDeclarationADefinition());
7723
7724    // The type must match the tag exactly;  no qualifiers allowed.
7725    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7726      break;
7727
7728    // Otherwise, set this is the anon-decl typedef for the tag.
7729    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7730    break;
7731  }
7732
7733  default:
7734    break;
7735  }
7736
7737  return NewTD;
7738}
7739
7740
7741/// \brief Determine whether a tag with a given kind is acceptable
7742/// as a redeclaration of the given tag declaration.
7743///
7744/// \returns true if the new tag kind is acceptable, false otherwise.
7745bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7746                                        TagTypeKind NewTag, bool isDefinition,
7747                                        SourceLocation NewTagLoc,
7748                                        const IdentifierInfo &Name) {
7749  // C++ [dcl.type.elab]p3:
7750  //   The class-key or enum keyword present in the
7751  //   elaborated-type-specifier shall agree in kind with the
7752  //   declaration to which the name in the elaborated-type-specifier
7753  //   refers. This rule also applies to the form of
7754  //   elaborated-type-specifier that declares a class-name or
7755  //   friend class since it can be construed as referring to the
7756  //   definition of the class. Thus, in any
7757  //   elaborated-type-specifier, the enum keyword shall be used to
7758  //   refer to an enumeration (7.2), the union class-key shall be
7759  //   used to refer to a union (clause 9), and either the class or
7760  //   struct class-key shall be used to refer to a class (clause 9)
7761  //   declared using the class or struct class-key.
7762  TagTypeKind OldTag = Previous->getTagKind();
7763  if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7764    if (OldTag == NewTag)
7765      return true;
7766
7767  if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7768      (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7769    // Warn about the struct/class tag mismatch.
7770    bool isTemplate = false;
7771    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7772      isTemplate = Record->getDescribedClassTemplate();
7773
7774    if (!ActiveTemplateInstantiations.empty()) {
7775      // In a template instantiation, do not offer fix-its for tag mismatches
7776      // since they usually mess up the template instead of fixing the problem.
7777      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7778        << (NewTag == TTK_Class) << isTemplate << &Name;
7779      return true;
7780    }
7781
7782    if (isDefinition) {
7783      // On definitions, check previous tags and issue a fix-it for each
7784      // one that doesn't match the current tag.
7785      if (Previous->getDefinition()) {
7786        // Don't suggest fix-its for redefinitions.
7787        return true;
7788      }
7789
7790      bool previousMismatch = false;
7791      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7792           E(Previous->redecls_end()); I != E; ++I) {
7793        if (I->getTagKind() != NewTag) {
7794          if (!previousMismatch) {
7795            previousMismatch = true;
7796            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7797              << (NewTag == TTK_Class) << isTemplate << &Name;
7798          }
7799          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7800            << (NewTag == TTK_Class)
7801            << FixItHint::CreateReplacement(I->getInnerLocStart(),
7802                                            NewTag == TTK_Class?
7803                                            "class" : "struct");
7804        }
7805      }
7806      return true;
7807    }
7808
7809    // Check for a previous definition.  If current tag and definition
7810    // are same type, do nothing.  If no definition, but disagree with
7811    // with previous tag type, give a warning, but no fix-it.
7812    const TagDecl *Redecl = Previous->getDefinition() ?
7813                            Previous->getDefinition() : Previous;
7814    if (Redecl->getTagKind() == NewTag) {
7815      return true;
7816    }
7817
7818    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7819      << (NewTag == TTK_Class)
7820      << isTemplate << &Name;
7821    Diag(Redecl->getLocation(), diag::note_previous_use);
7822
7823    // If there is a previous defintion, suggest a fix-it.
7824    if (Previous->getDefinition()) {
7825        Diag(NewTagLoc, diag::note_struct_class_suggestion)
7826          << (Redecl->getTagKind() == TTK_Class)
7827          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7828                        Redecl->getTagKind() == TTK_Class? "class" : "struct");
7829    }
7830
7831    return true;
7832  }
7833  return false;
7834}
7835
7836/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
7837/// former case, Name will be non-null.  In the later case, Name will be null.
7838/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7839/// reference/declaration/definition of a tag.
7840Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7841                     SourceLocation KWLoc, CXXScopeSpec &SS,
7842                     IdentifierInfo *Name, SourceLocation NameLoc,
7843                     AttributeList *Attr, AccessSpecifier AS,
7844                     SourceLocation ModulePrivateLoc,
7845                     MultiTemplateParamsArg TemplateParameterLists,
7846                     bool &OwnedDecl, bool &IsDependent,
7847                     SourceLocation ScopedEnumKWLoc,
7848                     bool ScopedEnumUsesClassTag,
7849                     TypeResult UnderlyingType) {
7850  // If this is not a definition, it must have a name.
7851  assert((Name != 0 || TUK == TUK_Definition) &&
7852         "Nameless record must be a definition!");
7853  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7854
7855  OwnedDecl = false;
7856  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7857  bool ScopedEnum = ScopedEnumKWLoc.isValid();
7858
7859  // FIXME: Check explicit specializations more carefully.
7860  bool isExplicitSpecialization = false;
7861  bool Invalid = false;
7862
7863  // We only need to do this matching if we have template parameters
7864  // or a scope specifier, which also conveniently avoids this work
7865  // for non-C++ cases.
7866  if (TemplateParameterLists.size() > 0 ||
7867      (SS.isNotEmpty() && TUK != TUK_Reference)) {
7868    if (TemplateParameterList *TemplateParams
7869          = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7870                                                TemplateParameterLists.get(),
7871                                                TemplateParameterLists.size(),
7872                                                    TUK == TUK_Friend,
7873                                                    isExplicitSpecialization,
7874                                                    Invalid)) {
7875      if (TemplateParams->size() > 0) {
7876        // This is a declaration or definition of a class template (which may
7877        // be a member of another template).
7878
7879        if (Invalid)
7880          return 0;
7881
7882        OwnedDecl = false;
7883        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7884                                               SS, Name, NameLoc, Attr,
7885                                               TemplateParams, AS,
7886                                               ModulePrivateLoc,
7887                                           TemplateParameterLists.size() - 1,
7888                 (TemplateParameterList**) TemplateParameterLists.release());
7889        return Result.get();
7890      } else {
7891        // The "template<>" header is extraneous.
7892        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7893          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7894        isExplicitSpecialization = true;
7895      }
7896    }
7897  }
7898
7899  // Figure out the underlying type if this a enum declaration. We need to do
7900  // this early, because it's needed to detect if this is an incompatible
7901  // redeclaration.
7902  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
7903
7904  if (Kind == TTK_Enum) {
7905    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
7906      // No underlying type explicitly specified, or we failed to parse the
7907      // type, default to int.
7908      EnumUnderlying = Context.IntTy.getTypePtr();
7909    else if (UnderlyingType.get()) {
7910      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
7911      // integral type; any cv-qualification is ignored.
7912      TypeSourceInfo *TI = 0;
7913      QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
7914      EnumUnderlying = TI;
7915
7916      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7917
7918      if (!T->isDependentType() && !T->isIntegralType(Context)) {
7919        Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
7920          << T;
7921        // Recover by falling back to int.
7922        EnumUnderlying = Context.IntTy.getTypePtr();
7923      }
7924
7925      if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
7926                                          UPPC_FixedUnderlyingType))
7927        EnumUnderlying = Context.IntTy.getTypePtr();
7928
7929    } else if (getLangOpts().MicrosoftMode)
7930      // Microsoft enums are always of int type.
7931      EnumUnderlying = Context.IntTy.getTypePtr();
7932  }
7933
7934  DeclContext *SearchDC = CurContext;
7935  DeclContext *DC = CurContext;
7936  bool isStdBadAlloc = false;
7937
7938  RedeclarationKind Redecl = ForRedeclaration;
7939  if (TUK == TUK_Friend || TUK == TUK_Reference)
7940    Redecl = NotForRedeclaration;
7941
7942  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
7943
7944  if (Name && SS.isNotEmpty()) {
7945    // We have a nested-name tag ('struct foo::bar').
7946
7947    // Check for invalid 'foo::'.
7948    if (SS.isInvalid()) {
7949      Name = 0;
7950      goto CreateNewDecl;
7951    }
7952
7953    // If this is a friend or a reference to a class in a dependent
7954    // context, don't try to make a decl for it.
7955    if (TUK == TUK_Friend || TUK == TUK_Reference) {
7956      DC = computeDeclContext(SS, false);
7957      if (!DC) {
7958        IsDependent = true;
7959        return 0;
7960      }
7961    } else {
7962      DC = computeDeclContext(SS, true);
7963      if (!DC) {
7964        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
7965          << SS.getRange();
7966        return 0;
7967      }
7968    }
7969
7970    if (RequireCompleteDeclContext(SS, DC))
7971      return 0;
7972
7973    SearchDC = DC;
7974    // Look-up name inside 'foo::'.
7975    LookupQualifiedName(Previous, DC);
7976
7977    if (Previous.isAmbiguous())
7978      return 0;
7979
7980    if (Previous.empty()) {
7981      // Name lookup did not find anything. However, if the
7982      // nested-name-specifier refers to the current instantiation,
7983      // and that current instantiation has any dependent base
7984      // classes, we might find something at instantiation time: treat
7985      // this as a dependent elaborated-type-specifier.
7986      // But this only makes any sense for reference-like lookups.
7987      if (Previous.wasNotFoundInCurrentInstantiation() &&
7988          (TUK == TUK_Reference || TUK == TUK_Friend)) {
7989        IsDependent = true;
7990        return 0;
7991      }
7992
7993      // A tag 'foo::bar' must already exist.
7994      Diag(NameLoc, diag::err_not_tag_in_scope)
7995        << Kind << Name << DC << SS.getRange();
7996      Name = 0;
7997      Invalid = true;
7998      goto CreateNewDecl;
7999    }
8000  } else if (Name) {
8001    // If this is a named struct, check to see if there was a previous forward
8002    // declaration or definition.
8003    // FIXME: We're looking into outer scopes here, even when we
8004    // shouldn't be. Doing so can result in ambiguities that we
8005    // shouldn't be diagnosing.
8006    LookupName(Previous, S);
8007
8008    if (Previous.isAmbiguous() &&
8009        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8010      LookupResult::Filter F = Previous.makeFilter();
8011      while (F.hasNext()) {
8012        NamedDecl *ND = F.next();
8013        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8014          F.erase();
8015      }
8016      F.done();
8017    }
8018
8019    // Note:  there used to be some attempt at recovery here.
8020    if (Previous.isAmbiguous())
8021      return 0;
8022
8023    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8024      // FIXME: This makes sure that we ignore the contexts associated
8025      // with C structs, unions, and enums when looking for a matching
8026      // tag declaration or definition. See the similar lookup tweak
8027      // in Sema::LookupName; is there a better way to deal with this?
8028      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8029        SearchDC = SearchDC->getParent();
8030    }
8031  } else if (S->isFunctionPrototypeScope()) {
8032    // If this is an enum declaration in function prototype scope, set its
8033    // initial context to the translation unit.
8034    // FIXME: [citation needed]
8035    SearchDC = Context.getTranslationUnitDecl();
8036  }
8037
8038  if (Previous.isSingleResult() &&
8039      Previous.getFoundDecl()->isTemplateParameter()) {
8040    // Maybe we will complain about the shadowed template parameter.
8041    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8042    // Just pretend that we didn't see the previous declaration.
8043    Previous.clear();
8044  }
8045
8046  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8047      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8048    // This is a declaration of or a reference to "std::bad_alloc".
8049    isStdBadAlloc = true;
8050
8051    if (Previous.empty() && StdBadAlloc) {
8052      // std::bad_alloc has been implicitly declared (but made invisible to
8053      // name lookup). Fill in this implicit declaration as the previous
8054      // declaration, so that the declarations get chained appropriately.
8055      Previous.addDecl(getStdBadAlloc());
8056    }
8057  }
8058
8059  // If we didn't find a previous declaration, and this is a reference
8060  // (or friend reference), move to the correct scope.  In C++, we
8061  // also need to do a redeclaration lookup there, just in case
8062  // there's a shadow friend decl.
8063  if (Name && Previous.empty() &&
8064      (TUK == TUK_Reference || TUK == TUK_Friend)) {
8065    if (Invalid) goto CreateNewDecl;
8066    assert(SS.isEmpty());
8067
8068    if (TUK == TUK_Reference) {
8069      // C++ [basic.scope.pdecl]p5:
8070      //   -- for an elaborated-type-specifier of the form
8071      //
8072      //          class-key identifier
8073      //
8074      //      if the elaborated-type-specifier is used in the
8075      //      decl-specifier-seq or parameter-declaration-clause of a
8076      //      function defined in namespace scope, the identifier is
8077      //      declared as a class-name in the namespace that contains
8078      //      the declaration; otherwise, except as a friend
8079      //      declaration, the identifier is declared in the smallest
8080      //      non-class, non-function-prototype scope that contains the
8081      //      declaration.
8082      //
8083      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8084      // C structs and unions.
8085      //
8086      // It is an error in C++ to declare (rather than define) an enum
8087      // type, including via an elaborated type specifier.  We'll
8088      // diagnose that later; for now, declare the enum in the same
8089      // scope as we would have picked for any other tag type.
8090      //
8091      // GNU C also supports this behavior as part of its incomplete
8092      // enum types extension, while GNU C++ does not.
8093      //
8094      // Find the context where we'll be declaring the tag.
8095      // FIXME: We would like to maintain the current DeclContext as the
8096      // lexical context,
8097      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8098        SearchDC = SearchDC->getParent();
8099
8100      // Find the scope where we'll be declaring the tag.
8101      while (S->isClassScope() ||
8102             (getLangOpts().CPlusPlus &&
8103              S->isFunctionPrototypeScope()) ||
8104             ((S->getFlags() & Scope::DeclScope) == 0) ||
8105             (S->getEntity() &&
8106              ((DeclContext *)S->getEntity())->isTransparentContext()))
8107        S = S->getParent();
8108    } else {
8109      assert(TUK == TUK_Friend);
8110      // C++ [namespace.memdef]p3:
8111      //   If a friend declaration in a non-local class first declares a
8112      //   class or function, the friend class or function is a member of
8113      //   the innermost enclosing namespace.
8114      SearchDC = SearchDC->getEnclosingNamespaceContext();
8115    }
8116
8117    // In C++, we need to do a redeclaration lookup to properly
8118    // diagnose some problems.
8119    if (getLangOpts().CPlusPlus) {
8120      Previous.setRedeclarationKind(ForRedeclaration);
8121      LookupQualifiedName(Previous, SearchDC);
8122    }
8123  }
8124
8125  if (!Previous.empty()) {
8126    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8127
8128    // It's okay to have a tag decl in the same scope as a typedef
8129    // which hides a tag decl in the same scope.  Finding this
8130    // insanity with a redeclaration lookup can only actually happen
8131    // in C++.
8132    //
8133    // This is also okay for elaborated-type-specifiers, which is
8134    // technically forbidden by the current standard but which is
8135    // okay according to the likely resolution of an open issue;
8136    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8137    if (getLangOpts().CPlusPlus) {
8138      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8139        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8140          TagDecl *Tag = TT->getDecl();
8141          if (Tag->getDeclName() == Name &&
8142              Tag->getDeclContext()->getRedeclContext()
8143                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
8144            PrevDecl = Tag;
8145            Previous.clear();
8146            Previous.addDecl(Tag);
8147            Previous.resolveKind();
8148          }
8149        }
8150      }
8151    }
8152
8153    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8154      // If this is a use of a previous tag, or if the tag is already declared
8155      // in the same scope (so that the definition/declaration completes or
8156      // rementions the tag), reuse the decl.
8157      if (TUK == TUK_Reference || TUK == TUK_Friend ||
8158          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8159        // Make sure that this wasn't declared as an enum and now used as a
8160        // struct or something similar.
8161        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8162                                          TUK == TUK_Definition, KWLoc,
8163                                          *Name)) {
8164          bool SafeToContinue
8165            = (PrevTagDecl->getTagKind() != TTK_Enum &&
8166               Kind != TTK_Enum);
8167          if (SafeToContinue)
8168            Diag(KWLoc, diag::err_use_with_wrong_tag)
8169              << Name
8170              << FixItHint::CreateReplacement(SourceRange(KWLoc),
8171                                              PrevTagDecl->getKindName());
8172          else
8173            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8174          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8175
8176          if (SafeToContinue)
8177            Kind = PrevTagDecl->getTagKind();
8178          else {
8179            // Recover by making this an anonymous redefinition.
8180            Name = 0;
8181            Previous.clear();
8182            Invalid = true;
8183          }
8184        }
8185
8186        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8187          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8188
8189          // If this is an elaborated-type-specifier for a scoped enumeration,
8190          // the 'class' keyword is not necessary and not permitted.
8191          if (TUK == TUK_Reference || TUK == TUK_Friend) {
8192            if (ScopedEnum)
8193              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8194                << PrevEnum->isScoped()
8195                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8196            return PrevTagDecl;
8197          }
8198
8199          // All conflicts with previous declarations are recovered by
8200          // returning the previous declaration.
8201          if (ScopedEnum != PrevEnum->isScoped()) {
8202            Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
8203              << PrevEnum->isScoped();
8204            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8205            return PrevTagDecl;
8206          }
8207          else if (EnumUnderlying && PrevEnum->isFixed()) {
8208            QualType T;
8209            if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8210                T = TI->getType();
8211            else
8212                T = QualType(EnumUnderlying.get<const Type*>(), 0);
8213
8214            if (!Context.hasSameUnqualifiedType(T,
8215                                                PrevEnum->getIntegerType())) {
8216              Diag(NameLoc.isValid() ? NameLoc : KWLoc,
8217                   diag::err_enum_redeclare_type_mismatch)
8218                << T
8219                << PrevEnum->getIntegerType();
8220              Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8221              return PrevTagDecl;
8222            }
8223          }
8224          else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
8225            Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
8226              << PrevEnum->isFixed();
8227            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8228            return PrevTagDecl;
8229          }
8230        }
8231
8232        if (!Invalid) {
8233          // If this is a use, just return the declaration we found.
8234
8235          // FIXME: In the future, return a variant or some other clue
8236          // for the consumer of this Decl to know it doesn't own it.
8237          // For our current ASTs this shouldn't be a problem, but will
8238          // need to be changed with DeclGroups.
8239          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8240               getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8241            return PrevTagDecl;
8242
8243          // Diagnose attempts to redefine a tag.
8244          if (TUK == TUK_Definition) {
8245            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8246              // If we're defining a specialization and the previous definition
8247              // is from an implicit instantiation, don't emit an error
8248              // here; we'll catch this in the general case below.
8249              if (!isExplicitSpecialization ||
8250                  !isa<CXXRecordDecl>(Def) ||
8251                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
8252                                               == TSK_ExplicitSpecialization) {
8253                // A redeclaration in function prototype scope in C isn't
8254                // visible elsewhere, so merely issue a warning.
8255                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
8256                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8257                else
8258                  Diag(NameLoc, diag::err_redefinition) << Name;
8259                Diag(Def->getLocation(), diag::note_previous_definition);
8260                // If this is a redefinition, recover by making this
8261                // struct be anonymous, which will make any later
8262                // references get the previous definition.
8263                Name = 0;
8264                Previous.clear();
8265                Invalid = true;
8266              }
8267            } else {
8268              // If the type is currently being defined, complain
8269              // about a nested redefinition.
8270              const TagType *Tag
8271                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
8272              if (Tag->isBeingDefined()) {
8273                Diag(NameLoc, diag::err_nested_redefinition) << Name;
8274                Diag(PrevTagDecl->getLocation(),
8275                     diag::note_previous_definition);
8276                Name = 0;
8277                Previous.clear();
8278                Invalid = true;
8279              }
8280            }
8281
8282            // Okay, this is definition of a previously declared or referenced
8283            // tag PrevDecl. We're going to create a new Decl for it.
8284          }
8285        }
8286        // If we get here we have (another) forward declaration or we
8287        // have a definition.  Just create a new decl.
8288
8289      } else {
8290        // If we get here, this is a definition of a new tag type in a nested
8291        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8292        // new decl/type.  We set PrevDecl to NULL so that the entities
8293        // have distinct types.
8294        Previous.clear();
8295      }
8296      // If we get here, we're going to create a new Decl. If PrevDecl
8297      // is non-NULL, it's a definition of the tag declared by
8298      // PrevDecl. If it's NULL, we have a new definition.
8299
8300
8301    // Otherwise, PrevDecl is not a tag, but was found with tag
8302    // lookup.  This is only actually possible in C++, where a few
8303    // things like templates still live in the tag namespace.
8304    } else {
8305      // Use a better diagnostic if an elaborated-type-specifier
8306      // found the wrong kind of type on the first
8307      // (non-redeclaration) lookup.
8308      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8309          !Previous.isForRedeclaration()) {
8310        unsigned Kind = 0;
8311        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8312        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8313        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8314        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8315        Diag(PrevDecl->getLocation(), diag::note_declared_at);
8316        Invalid = true;
8317
8318      // Otherwise, only diagnose if the declaration is in scope.
8319      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8320                                isExplicitSpecialization)) {
8321        // do nothing
8322
8323      // Diagnose implicit declarations introduced by elaborated types.
8324      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8325        unsigned Kind = 0;
8326        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8327        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8328        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8329        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8330        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8331        Invalid = true;
8332
8333      // Otherwise it's a declaration.  Call out a particularly common
8334      // case here.
8335      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8336        unsigned Kind = 0;
8337        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8338        Diag(NameLoc, diag::err_tag_definition_of_typedef)
8339          << Name << Kind << TND->getUnderlyingType();
8340        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8341        Invalid = true;
8342
8343      // Otherwise, diagnose.
8344      } else {
8345        // The tag name clashes with something else in the target scope,
8346        // issue an error and recover by making this tag be anonymous.
8347        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8348        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8349        Name = 0;
8350        Invalid = true;
8351      }
8352
8353      // The existing declaration isn't relevant to us; we're in a
8354      // new scope, so clear out the previous declaration.
8355      Previous.clear();
8356    }
8357  }
8358
8359CreateNewDecl:
8360
8361  TagDecl *PrevDecl = 0;
8362  if (Previous.isSingleResult())
8363    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8364
8365  // If there is an identifier, use the location of the identifier as the
8366  // location of the decl, otherwise use the location of the struct/union
8367  // keyword.
8368  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8369
8370  // Otherwise, create a new declaration. If there is a previous
8371  // declaration of the same entity, the two will be linked via
8372  // PrevDecl.
8373  TagDecl *New;
8374
8375  bool IsForwardReference = false;
8376  if (Kind == TTK_Enum) {
8377    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8378    // enum X { A, B, C } D;    D should chain to X.
8379    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8380                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8381                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8382    // If this is an undefined enum, warn.
8383    if (TUK != TUK_Definition && !Invalid) {
8384      TagDecl *Def;
8385      if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8386        // C++0x: 7.2p2: opaque-enum-declaration.
8387        // Conflicts are diagnosed above. Do nothing.
8388      }
8389      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8390        Diag(Loc, diag::ext_forward_ref_enum_def)
8391          << New;
8392        Diag(Def->getLocation(), diag::note_previous_definition);
8393      } else {
8394        unsigned DiagID = diag::ext_forward_ref_enum;
8395        if (getLangOpts().MicrosoftMode)
8396          DiagID = diag::ext_ms_forward_ref_enum;
8397        else if (getLangOpts().CPlusPlus)
8398          DiagID = diag::err_forward_ref_enum;
8399        Diag(Loc, DiagID);
8400
8401        // If this is a forward-declared reference to an enumeration, make a
8402        // note of it; we won't actually be introducing the declaration into
8403        // the declaration context.
8404        if (TUK == TUK_Reference)
8405          IsForwardReference = true;
8406      }
8407    }
8408
8409    if (EnumUnderlying) {
8410      EnumDecl *ED = cast<EnumDecl>(New);
8411      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8412        ED->setIntegerTypeSourceInfo(TI);
8413      else
8414        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8415      ED->setPromotionType(ED->getIntegerType());
8416    }
8417
8418  } else {
8419    // struct/union/class
8420
8421    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8422    // struct X { int A; } D;    D should chain to X.
8423    if (getLangOpts().CPlusPlus) {
8424      // FIXME: Look for a way to use RecordDecl for simple structs.
8425      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8426                                  cast_or_null<CXXRecordDecl>(PrevDecl));
8427
8428      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8429        StdBadAlloc = cast<CXXRecordDecl>(New);
8430    } else
8431      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8432                               cast_or_null<RecordDecl>(PrevDecl));
8433  }
8434
8435  // Maybe add qualifier info.
8436  if (SS.isNotEmpty()) {
8437    if (SS.isSet()) {
8438      New->setQualifierInfo(SS.getWithLocInContext(Context));
8439      if (TemplateParameterLists.size() > 0) {
8440        New->setTemplateParameterListsInfo(Context,
8441                                           TemplateParameterLists.size(),
8442                    (TemplateParameterList**) TemplateParameterLists.release());
8443      }
8444    }
8445    else
8446      Invalid = true;
8447  }
8448
8449  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8450    // Add alignment attributes if necessary; these attributes are checked when
8451    // the ASTContext lays out the structure.
8452    //
8453    // It is important for implementing the correct semantics that this
8454    // happen here (in act on tag decl). The #pragma pack stack is
8455    // maintained as a result of parser callbacks which can occur at
8456    // many points during the parsing of a struct declaration (because
8457    // the #pragma tokens are effectively skipped over during the
8458    // parsing of the struct).
8459    AddAlignmentAttributesForRecord(RD);
8460
8461    AddMsStructLayoutForRecord(RD);
8462  }
8463
8464  if (ModulePrivateLoc.isValid()) {
8465    if (isExplicitSpecialization)
8466      Diag(New->getLocation(), diag::err_module_private_specialization)
8467        << 2
8468        << FixItHint::CreateRemoval(ModulePrivateLoc);
8469    // __module_private__ does not apply to local classes. However, we only
8470    // diagnose this as an error when the declaration specifiers are
8471    // freestanding. Here, we just ignore the __module_private__.
8472    else if (!SearchDC->isFunctionOrMethod())
8473      New->setModulePrivate();
8474  }
8475
8476  // If this is a specialization of a member class (of a class template),
8477  // check the specialization.
8478  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8479    Invalid = true;
8480
8481  if (Invalid)
8482    New->setInvalidDecl();
8483
8484  if (Attr)
8485    ProcessDeclAttributeList(S, New, Attr);
8486
8487  // If we're declaring or defining a tag in function prototype scope
8488  // in C, note that this type can only be used within the function.
8489  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
8490    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8491
8492  // Set the lexical context. If the tag has a C++ scope specifier, the
8493  // lexical context will be different from the semantic context.
8494  New->setLexicalDeclContext(CurContext);
8495
8496  // Mark this as a friend decl if applicable.
8497  // In Microsoft mode, a friend declaration also acts as a forward
8498  // declaration so we always pass true to setObjectOfFriendDecl to make
8499  // the tag name visible.
8500  if (TUK == TUK_Friend)
8501    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8502                               getLangOpts().MicrosoftExt);
8503
8504  // Set the access specifier.
8505  if (!Invalid && SearchDC->isRecord())
8506    SetMemberAccessSpecifier(New, PrevDecl, AS);
8507
8508  if (TUK == TUK_Definition)
8509    New->startDefinition();
8510
8511  // If this has an identifier, add it to the scope stack.
8512  if (TUK == TUK_Friend) {
8513    // We might be replacing an existing declaration in the lookup tables;
8514    // if so, borrow its access specifier.
8515    if (PrevDecl)
8516      New->setAccess(PrevDecl->getAccess());
8517
8518    DeclContext *DC = New->getDeclContext()->getRedeclContext();
8519    DC->makeDeclVisibleInContext(New);
8520    if (Name) // can be null along some error paths
8521      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8522        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8523  } else if (Name) {
8524    S = getNonFieldDeclScope(S);
8525    PushOnScopeChains(New, S, !IsForwardReference);
8526    if (IsForwardReference)
8527      SearchDC->makeDeclVisibleInContext(New);
8528
8529  } else {
8530    CurContext->addDecl(New);
8531  }
8532
8533  // If this is the C FILE type, notify the AST context.
8534  if (IdentifierInfo *II = New->getIdentifier())
8535    if (!New->isInvalidDecl() &&
8536        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8537        II->isStr("FILE"))
8538      Context.setFILEDecl(New);
8539
8540  // If we were in function prototype scope (and not in C++ mode), add this
8541  // tag to the list of decls to inject into the function definition scope.
8542  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
8543      InFunctionDeclarator && Name)
8544    DeclsInPrototypeScope.push_back(New);
8545
8546  OwnedDecl = true;
8547  return New;
8548}
8549
8550void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8551  AdjustDeclIfTemplate(TagD);
8552  TagDecl *Tag = cast<TagDecl>(TagD);
8553
8554  // Enter the tag context.
8555  PushDeclContext(S, Tag);
8556}
8557
8558Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8559  assert(isa<ObjCContainerDecl>(IDecl) &&
8560         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8561  DeclContext *OCD = cast<DeclContext>(IDecl);
8562  assert(getContainingDC(OCD) == CurContext &&
8563      "The next DeclContext should be lexically contained in the current one.");
8564  CurContext = OCD;
8565  return IDecl;
8566}
8567
8568void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8569                                           SourceLocation FinalLoc,
8570                                           SourceLocation LBraceLoc) {
8571  AdjustDeclIfTemplate(TagD);
8572  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8573
8574  FieldCollector->StartClass();
8575
8576  if (!Record->getIdentifier())
8577    return;
8578
8579  if (FinalLoc.isValid())
8580    Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8581
8582  // C++ [class]p2:
8583  //   [...] The class-name is also inserted into the scope of the
8584  //   class itself; this is known as the injected-class-name. For
8585  //   purposes of access checking, the injected-class-name is treated
8586  //   as if it were a public member name.
8587  CXXRecordDecl *InjectedClassName
8588    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8589                            Record->getLocStart(), Record->getLocation(),
8590                            Record->getIdentifier(),
8591                            /*PrevDecl=*/0,
8592                            /*DelayTypeCreation=*/true);
8593  Context.getTypeDeclType(InjectedClassName, Record);
8594  InjectedClassName->setImplicit();
8595  InjectedClassName->setAccess(AS_public);
8596  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8597      InjectedClassName->setDescribedClassTemplate(Template);
8598  PushOnScopeChains(InjectedClassName, S);
8599  assert(InjectedClassName->isInjectedClassName() &&
8600         "Broken injected-class-name");
8601}
8602
8603void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8604                                    SourceLocation RBraceLoc) {
8605  AdjustDeclIfTemplate(TagD);
8606  TagDecl *Tag = cast<TagDecl>(TagD);
8607  Tag->setRBraceLoc(RBraceLoc);
8608
8609  // Make sure we "complete" the definition even it is invalid.
8610  if (Tag->isBeingDefined()) {
8611    assert(Tag->isInvalidDecl() && "We should already have completed it");
8612    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8613      RD->completeDefinition();
8614  }
8615
8616  if (isa<CXXRecordDecl>(Tag))
8617    FieldCollector->FinishClass();
8618
8619  // Exit this scope of this tag's definition.
8620  PopDeclContext();
8621
8622  // Notify the consumer that we've defined a tag.
8623  Consumer.HandleTagDeclDefinition(Tag);
8624}
8625
8626void Sema::ActOnObjCContainerFinishDefinition() {
8627  // Exit this scope of this interface definition.
8628  PopDeclContext();
8629}
8630
8631void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8632  assert(DC == CurContext && "Mismatch of container contexts");
8633  OriginalLexicalContext = DC;
8634  ActOnObjCContainerFinishDefinition();
8635}
8636
8637void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8638  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8639  OriginalLexicalContext = 0;
8640}
8641
8642void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8643  AdjustDeclIfTemplate(TagD);
8644  TagDecl *Tag = cast<TagDecl>(TagD);
8645  Tag->setInvalidDecl();
8646
8647  // Make sure we "complete" the definition even it is invalid.
8648  if (Tag->isBeingDefined()) {
8649    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8650      RD->completeDefinition();
8651  }
8652
8653  // We're undoing ActOnTagStartDefinition here, not
8654  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8655  // the FieldCollector.
8656
8657  PopDeclContext();
8658}
8659
8660// Note that FieldName may be null for anonymous bitfields.
8661ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8662                                IdentifierInfo *FieldName,
8663                                QualType FieldTy, Expr *BitWidth,
8664                                bool *ZeroWidth) {
8665  // Default to true; that shouldn't confuse checks for emptiness
8666  if (ZeroWidth)
8667    *ZeroWidth = true;
8668
8669  // C99 6.7.2.1p4 - verify the field type.
8670  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8671  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8672    // Handle incomplete types with specific error.
8673    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8674      return ExprError();
8675    if (FieldName)
8676      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8677        << FieldName << FieldTy << BitWidth->getSourceRange();
8678    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8679      << FieldTy << BitWidth->getSourceRange();
8680  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8681                                             UPPC_BitFieldWidth))
8682    return ExprError();
8683
8684  // If the bit-width is type- or value-dependent, don't try to check
8685  // it now.
8686  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8687    return Owned(BitWidth);
8688
8689  llvm::APSInt Value;
8690  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8691  if (ICE.isInvalid())
8692    return ICE;
8693  BitWidth = ICE.take();
8694
8695  if (Value != 0 && ZeroWidth)
8696    *ZeroWidth = false;
8697
8698  // Zero-width bitfield is ok for anonymous field.
8699  if (Value == 0 && FieldName)
8700    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8701
8702  if (Value.isSigned() && Value.isNegative()) {
8703    if (FieldName)
8704      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8705               << FieldName << Value.toString(10);
8706    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8707      << Value.toString(10);
8708  }
8709
8710  if (!FieldTy->isDependentType()) {
8711    uint64_t TypeSize = Context.getTypeSize(FieldTy);
8712    if (Value.getZExtValue() > TypeSize) {
8713      if (!getLangOpts().CPlusPlus) {
8714        if (FieldName)
8715          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8716            << FieldName << (unsigned)Value.getZExtValue()
8717            << (unsigned)TypeSize;
8718
8719        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8720          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8721      }
8722
8723      if (FieldName)
8724        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8725          << FieldName << (unsigned)Value.getZExtValue()
8726          << (unsigned)TypeSize;
8727      else
8728        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8729          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8730    }
8731  }
8732
8733  return Owned(BitWidth);
8734}
8735
8736/// ActOnField - Each field of a C struct/union is passed into this in order
8737/// to create a FieldDecl object for it.
8738Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8739                       Declarator &D, Expr *BitfieldWidth) {
8740  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8741                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8742                               /*HasInit=*/false, AS_public);
8743  return Res;
8744}
8745
8746/// HandleField - Analyze a field of a C struct or a C++ data member.
8747///
8748FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8749                             SourceLocation DeclStart,
8750                             Declarator &D, Expr *BitWidth, bool HasInit,
8751                             AccessSpecifier AS) {
8752  IdentifierInfo *II = D.getIdentifier();
8753  SourceLocation Loc = DeclStart;
8754  if (II) Loc = D.getIdentifierLoc();
8755
8756  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8757  QualType T = TInfo->getType();
8758  if (getLangOpts().CPlusPlus) {
8759    CheckExtraCXXDefaultArguments(D);
8760
8761    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8762                                        UPPC_DataMemberType)) {
8763      D.setInvalidType();
8764      T = Context.IntTy;
8765      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8766    }
8767  }
8768
8769  DiagnoseFunctionSpecifiers(D);
8770
8771  if (D.getDeclSpec().isThreadSpecified())
8772    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8773  if (D.getDeclSpec().isConstexprSpecified())
8774    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8775      << 2;
8776
8777  // Check to see if this name was declared as a member previously
8778  NamedDecl *PrevDecl = 0;
8779  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8780  LookupName(Previous, S);
8781  switch (Previous.getResultKind()) {
8782    case LookupResult::Found:
8783    case LookupResult::FoundUnresolvedValue:
8784      PrevDecl = Previous.getAsSingle<NamedDecl>();
8785      break;
8786
8787    case LookupResult::FoundOverloaded:
8788      PrevDecl = Previous.getRepresentativeDecl();
8789      break;
8790
8791    case LookupResult::NotFound:
8792    case LookupResult::NotFoundInCurrentInstantiation:
8793    case LookupResult::Ambiguous:
8794      break;
8795  }
8796  Previous.suppressDiagnostics();
8797
8798  if (PrevDecl && PrevDecl->isTemplateParameter()) {
8799    // Maybe we will complain about the shadowed template parameter.
8800    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8801    // Just pretend that we didn't see the previous declaration.
8802    PrevDecl = 0;
8803  }
8804
8805  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8806    PrevDecl = 0;
8807
8808  bool Mutable
8809    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8810  SourceLocation TSSL = D.getLocStart();
8811  FieldDecl *NewFD
8812    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8813                     TSSL, AS, PrevDecl, &D);
8814
8815  if (NewFD->isInvalidDecl())
8816    Record->setInvalidDecl();
8817
8818  if (D.getDeclSpec().isModulePrivateSpecified())
8819    NewFD->setModulePrivate();
8820
8821  if (NewFD->isInvalidDecl() && PrevDecl) {
8822    // Don't introduce NewFD into scope; there's already something
8823    // with the same name in the same scope.
8824  } else if (II) {
8825    PushOnScopeChains(NewFD, S);
8826  } else
8827    Record->addDecl(NewFD);
8828
8829  return NewFD;
8830}
8831
8832/// \brief Build a new FieldDecl and check its well-formedness.
8833///
8834/// This routine builds a new FieldDecl given the fields name, type,
8835/// record, etc. \p PrevDecl should refer to any previous declaration
8836/// with the same name and in the same scope as the field to be
8837/// created.
8838///
8839/// \returns a new FieldDecl.
8840///
8841/// \todo The Declarator argument is a hack. It will be removed once
8842FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8843                                TypeSourceInfo *TInfo,
8844                                RecordDecl *Record, SourceLocation Loc,
8845                                bool Mutable, Expr *BitWidth, bool HasInit,
8846                                SourceLocation TSSL,
8847                                AccessSpecifier AS, NamedDecl *PrevDecl,
8848                                Declarator *D) {
8849  IdentifierInfo *II = Name.getAsIdentifierInfo();
8850  bool InvalidDecl = false;
8851  if (D) InvalidDecl = D->isInvalidType();
8852
8853  // If we receive a broken type, recover by assuming 'int' and
8854  // marking this declaration as invalid.
8855  if (T.isNull()) {
8856    InvalidDecl = true;
8857    T = Context.IntTy;
8858  }
8859
8860  QualType EltTy = Context.getBaseElementType(T);
8861  if (!EltTy->isDependentType()) {
8862    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8863      // Fields of incomplete type force their record to be invalid.
8864      Record->setInvalidDecl();
8865      InvalidDecl = true;
8866    } else {
8867      NamedDecl *Def;
8868      EltTy->isIncompleteType(&Def);
8869      if (Def && Def->isInvalidDecl()) {
8870        Record->setInvalidDecl();
8871        InvalidDecl = true;
8872      }
8873    }
8874  }
8875
8876  // C99 6.7.2.1p8: A member of a structure or union may have any type other
8877  // than a variably modified type.
8878  if (!InvalidDecl && T->isVariablyModifiedType()) {
8879    bool SizeIsNegative;
8880    llvm::APSInt Oversized;
8881    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8882                                                           SizeIsNegative,
8883                                                           Oversized);
8884    if (!FixedTy.isNull()) {
8885      Diag(Loc, diag::warn_illegal_constant_array_size);
8886      T = FixedTy;
8887    } else {
8888      if (SizeIsNegative)
8889        Diag(Loc, diag::err_typecheck_negative_array_size);
8890      else if (Oversized.getBoolValue())
8891        Diag(Loc, diag::err_array_too_large)
8892          << Oversized.toString(10);
8893      else
8894        Diag(Loc, diag::err_typecheck_field_variable_size);
8895      InvalidDecl = true;
8896    }
8897  }
8898
8899  // Fields can not have abstract class types
8900  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8901                                             diag::err_abstract_type_in_decl,
8902                                             AbstractFieldType))
8903    InvalidDecl = true;
8904
8905  bool ZeroWidth = false;
8906  // If this is declared as a bit-field, check the bit-field.
8907  if (!InvalidDecl && BitWidth) {
8908    BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
8909    if (!BitWidth) {
8910      InvalidDecl = true;
8911      BitWidth = 0;
8912      ZeroWidth = false;
8913    }
8914  }
8915
8916  // Check that 'mutable' is consistent with the type of the declaration.
8917  if (!InvalidDecl && Mutable) {
8918    unsigned DiagID = 0;
8919    if (T->isReferenceType())
8920      DiagID = diag::err_mutable_reference;
8921    else if (T.isConstQualified())
8922      DiagID = diag::err_mutable_const;
8923
8924    if (DiagID) {
8925      SourceLocation ErrLoc = Loc;
8926      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
8927        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
8928      Diag(ErrLoc, DiagID);
8929      Mutable = false;
8930      InvalidDecl = true;
8931    }
8932  }
8933
8934  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
8935                                       BitWidth, Mutable, HasInit);
8936  if (InvalidDecl)
8937    NewFD->setInvalidDecl();
8938
8939  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
8940    Diag(Loc, diag::err_duplicate_member) << II;
8941    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8942    NewFD->setInvalidDecl();
8943  }
8944
8945  if (!InvalidDecl && getLangOpts().CPlusPlus) {
8946    if (Record->isUnion()) {
8947      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8948        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8949        if (RDecl->getDefinition()) {
8950          // C++ [class.union]p1: An object of a class with a non-trivial
8951          // constructor, a non-trivial copy constructor, a non-trivial
8952          // destructor, or a non-trivial copy assignment operator
8953          // cannot be a member of a union, nor can an array of such
8954          // objects.
8955          if (CheckNontrivialField(NewFD))
8956            NewFD->setInvalidDecl();
8957        }
8958      }
8959
8960      // C++ [class.union]p1: If a union contains a member of reference type,
8961      // the program is ill-formed.
8962      if (EltTy->isReferenceType()) {
8963        Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
8964          << NewFD->getDeclName() << EltTy;
8965        NewFD->setInvalidDecl();
8966      }
8967    }
8968  }
8969
8970  // FIXME: We need to pass in the attributes given an AST
8971  // representation, not a parser representation.
8972  if (D)
8973    // FIXME: What to pass instead of TUScope?
8974    ProcessDeclAttributes(TUScope, NewFD, *D);
8975
8976  // In auto-retain/release, infer strong retension for fields of
8977  // retainable type.
8978  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
8979    NewFD->setInvalidDecl();
8980
8981  if (T.isObjCGCWeak())
8982    Diag(Loc, diag::warn_attribute_weak_on_field);
8983
8984  NewFD->setAccess(AS);
8985  return NewFD;
8986}
8987
8988bool Sema::CheckNontrivialField(FieldDecl *FD) {
8989  assert(FD);
8990  assert(getLangOpts().CPlusPlus && "valid check only for C++");
8991
8992  if (FD->isInvalidDecl())
8993    return true;
8994
8995  QualType EltTy = Context.getBaseElementType(FD->getType());
8996  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8997    CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8998    if (RDecl->getDefinition()) {
8999      // We check for copy constructors before constructors
9000      // because otherwise we'll never get complaints about
9001      // copy constructors.
9002
9003      CXXSpecialMember member = CXXInvalid;
9004      if (!RDecl->hasTrivialCopyConstructor())
9005        member = CXXCopyConstructor;
9006      else if (!RDecl->hasTrivialDefaultConstructor())
9007        member = CXXDefaultConstructor;
9008      else if (!RDecl->hasTrivialCopyAssignment())
9009        member = CXXCopyAssignment;
9010      else if (!RDecl->hasTrivialDestructor())
9011        member = CXXDestructor;
9012
9013      if (member != CXXInvalid) {
9014        if (!getLangOpts().CPlusPlus0x &&
9015            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9016          // Objective-C++ ARC: it is an error to have a non-trivial field of
9017          // a union. However, system headers in Objective-C programs
9018          // occasionally have Objective-C lifetime objects within unions,
9019          // and rather than cause the program to fail, we make those
9020          // members unavailable.
9021          SourceLocation Loc = FD->getLocation();
9022          if (getSourceManager().isInSystemHeader(Loc)) {
9023            if (!FD->hasAttr<UnavailableAttr>())
9024              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9025                                  "this system field has retaining ownership"));
9026            return false;
9027          }
9028        }
9029
9030        Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9031               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9032               diag::err_illegal_union_or_anon_struct_member)
9033          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9034        DiagnoseNontrivial(RT, member);
9035        return !getLangOpts().CPlusPlus0x;
9036      }
9037    }
9038  }
9039
9040  return false;
9041}
9042
9043/// If the given constructor is user-provided, produce a diagnostic explaining
9044/// that it makes the class non-trivial.
9045static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9046                                               CXXConstructorDecl *CD,
9047                                               Sema::CXXSpecialMember CSM) {
9048  if (!CD->isUserProvided())
9049    return false;
9050
9051  SourceLocation CtorLoc = CD->getLocation();
9052  S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9053  return true;
9054}
9055
9056/// DiagnoseNontrivial - Given that a class has a non-trivial
9057/// special member, figure out why.
9058void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9059  QualType QT(T, 0U);
9060  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9061
9062  // Check whether the member was user-declared.
9063  switch (member) {
9064  case CXXInvalid:
9065    break;
9066
9067  case CXXDefaultConstructor:
9068    if (RD->hasUserDeclaredConstructor()) {
9069      typedef CXXRecordDecl::ctor_iterator ctor_iter;
9070      for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9071        if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
9072          return;
9073
9074      // No user-provided constructors; look for constructor templates.
9075      typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9076          tmpl_iter;
9077      for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9078           TI != TE; ++TI) {
9079        CXXConstructorDecl *CD =
9080            dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9081        if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9082          return;
9083      }
9084    }
9085    break;
9086
9087  case CXXCopyConstructor:
9088    if (RD->hasUserDeclaredCopyConstructor()) {
9089      SourceLocation CtorLoc =
9090        RD->getCopyConstructor(0)->getLocation();
9091      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9092      return;
9093    }
9094    break;
9095
9096  case CXXMoveConstructor:
9097    if (RD->hasUserDeclaredMoveConstructor()) {
9098      SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9099      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9100      return;
9101    }
9102    break;
9103
9104  case CXXCopyAssignment:
9105    if (RD->hasUserDeclaredCopyAssignment()) {
9106      // FIXME: this should use the location of the copy
9107      // assignment, not the type.
9108      SourceLocation TyLoc = RD->getLocStart();
9109      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9110      return;
9111    }
9112    break;
9113
9114  case CXXMoveAssignment:
9115    if (RD->hasUserDeclaredMoveAssignment()) {
9116      SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9117      Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9118      return;
9119    }
9120    break;
9121
9122  case CXXDestructor:
9123    if (RD->hasUserDeclaredDestructor()) {
9124      SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9125      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9126      return;
9127    }
9128    break;
9129  }
9130
9131  typedef CXXRecordDecl::base_class_iterator base_iter;
9132
9133  // Virtual bases and members inhibit trivial copying/construction,
9134  // but not trivial destruction.
9135  if (member != CXXDestructor) {
9136    // Check for virtual bases.  vbases includes indirect virtual bases,
9137    // so we just iterate through the direct bases.
9138    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9139      if (bi->isVirtual()) {
9140        SourceLocation BaseLoc = bi->getLocStart();
9141        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9142        return;
9143      }
9144
9145    // Check for virtual methods.
9146    typedef CXXRecordDecl::method_iterator meth_iter;
9147    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9148         ++mi) {
9149      if (mi->isVirtual()) {
9150        SourceLocation MLoc = mi->getLocStart();
9151        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9152        return;
9153      }
9154    }
9155  }
9156
9157  bool (CXXRecordDecl::*hasTrivial)() const;
9158  switch (member) {
9159  case CXXDefaultConstructor:
9160    hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
9161  case CXXCopyConstructor:
9162    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9163  case CXXCopyAssignment:
9164    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9165  case CXXDestructor:
9166    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9167  default:
9168    llvm_unreachable("unexpected special member");
9169  }
9170
9171  // Check for nontrivial bases (and recurse).
9172  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9173    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9174    assert(BaseRT && "Don't know how to handle dependent bases");
9175    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9176    if (!(BaseRecTy->*hasTrivial)()) {
9177      SourceLocation BaseLoc = bi->getLocStart();
9178      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9179      DiagnoseNontrivial(BaseRT, member);
9180      return;
9181    }
9182  }
9183
9184  // Check for nontrivial members (and recurse).
9185  typedef RecordDecl::field_iterator field_iter;
9186  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9187       ++fi) {
9188    QualType EltTy = Context.getBaseElementType((*fi)->getType());
9189    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9190      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9191
9192      if (!(EltRD->*hasTrivial)()) {
9193        SourceLocation FLoc = (*fi)->getLocation();
9194        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9195        DiagnoseNontrivial(EltRT, member);
9196        return;
9197      }
9198    }
9199
9200    if (EltTy->isObjCLifetimeType()) {
9201      switch (EltTy.getObjCLifetime()) {
9202      case Qualifiers::OCL_None:
9203      case Qualifiers::OCL_ExplicitNone:
9204        break;
9205
9206      case Qualifiers::OCL_Autoreleasing:
9207      case Qualifiers::OCL_Weak:
9208      case Qualifiers::OCL_Strong:
9209        Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
9210          << QT << EltTy.getObjCLifetime();
9211        return;
9212      }
9213    }
9214  }
9215
9216  llvm_unreachable("found no explanation for non-trivial member");
9217}
9218
9219/// TranslateIvarVisibility - Translate visibility from a token ID to an
9220///  AST enum value.
9221static ObjCIvarDecl::AccessControl
9222TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9223  switch (ivarVisibility) {
9224  default: llvm_unreachable("Unknown visitibility kind");
9225  case tok::objc_private: return ObjCIvarDecl::Private;
9226  case tok::objc_public: return ObjCIvarDecl::Public;
9227  case tok::objc_protected: return ObjCIvarDecl::Protected;
9228  case tok::objc_package: return ObjCIvarDecl::Package;
9229  }
9230}
9231
9232/// ActOnIvar - Each ivar field of an objective-c class is passed into this
9233/// in order to create an IvarDecl object for it.
9234Decl *Sema::ActOnIvar(Scope *S,
9235                                SourceLocation DeclStart,
9236                                Declarator &D, Expr *BitfieldWidth,
9237                                tok::ObjCKeywordKind Visibility) {
9238
9239  IdentifierInfo *II = D.getIdentifier();
9240  Expr *BitWidth = (Expr*)BitfieldWidth;
9241  SourceLocation Loc = DeclStart;
9242  if (II) Loc = D.getIdentifierLoc();
9243
9244  // FIXME: Unnamed fields can be handled in various different ways, for
9245  // example, unnamed unions inject all members into the struct namespace!
9246
9247  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9248  QualType T = TInfo->getType();
9249
9250  if (BitWidth) {
9251    // 6.7.2.1p3, 6.7.2.1p4
9252    BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9253    if (!BitWidth)
9254      D.setInvalidType();
9255  } else {
9256    // Not a bitfield.
9257
9258    // validate II.
9259
9260  }
9261  if (T->isReferenceType()) {
9262    Diag(Loc, diag::err_ivar_reference_type);
9263    D.setInvalidType();
9264  }
9265  // C99 6.7.2.1p8: A member of a structure or union may have any type other
9266  // than a variably modified type.
9267  else if (T->isVariablyModifiedType()) {
9268    Diag(Loc, diag::err_typecheck_ivar_variable_size);
9269    D.setInvalidType();
9270  }
9271
9272  // Get the visibility (access control) for this ivar.
9273  ObjCIvarDecl::AccessControl ac =
9274    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9275                                        : ObjCIvarDecl::None;
9276  // Must set ivar's DeclContext to its enclosing interface.
9277  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9278  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9279    return 0;
9280  ObjCContainerDecl *EnclosingContext;
9281  if (ObjCImplementationDecl *IMPDecl =
9282      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9283    if (!LangOpts.ObjCNonFragileABI2) {
9284    // Case of ivar declared in an implementation. Context is that of its class.
9285      EnclosingContext = IMPDecl->getClassInterface();
9286      assert(EnclosingContext && "Implementation has no class interface!");
9287    }
9288    else
9289      EnclosingContext = EnclosingDecl;
9290  } else {
9291    if (ObjCCategoryDecl *CDecl =
9292        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9293      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9294        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
9295        return 0;
9296      }
9297    }
9298    EnclosingContext = EnclosingDecl;
9299  }
9300
9301  // Construct the decl.
9302  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9303                                             DeclStart, Loc, II, T,
9304                                             TInfo, ac, (Expr *)BitfieldWidth);
9305
9306  if (II) {
9307    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
9308                                           ForRedeclaration);
9309    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
9310        && !isa<TagDecl>(PrevDecl)) {
9311      Diag(Loc, diag::err_duplicate_member) << II;
9312      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9313      NewID->setInvalidDecl();
9314    }
9315  }
9316
9317  // Process attributes attached to the ivar.
9318  ProcessDeclAttributes(S, NewID, D);
9319
9320  if (D.isInvalidType())
9321    NewID->setInvalidDecl();
9322
9323  // In ARC, infer 'retaining' for ivars of retainable type.
9324  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9325    NewID->setInvalidDecl();
9326
9327  if (D.getDeclSpec().isModulePrivateSpecified())
9328    NewID->setModulePrivate();
9329
9330  if (II) {
9331    // FIXME: When interfaces are DeclContexts, we'll need to add
9332    // these to the interface.
9333    S->AddDecl(NewID);
9334    IdResolver.AddDecl(NewID);
9335  }
9336
9337  return NewID;
9338}
9339
9340/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9341/// class and class extensions. For every class @interface and class
9342/// extension @interface, if the last ivar is a bitfield of any type,
9343/// then add an implicit `char :0` ivar to the end of that interface.
9344void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9345                             SmallVectorImpl<Decl *> &AllIvarDecls) {
9346  if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9347    return;
9348
9349  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9350  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9351
9352  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9353    return;
9354  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9355  if (!ID) {
9356    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9357      if (!CD->IsClassExtension())
9358        return;
9359    }
9360    // No need to add this to end of @implementation.
9361    else
9362      return;
9363  }
9364  // All conditions are met. Add a new bitfield to the tail end of ivars.
9365  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9366  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9367
9368  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9369                              DeclLoc, DeclLoc, 0,
9370                              Context.CharTy,
9371                              Context.getTrivialTypeSourceInfo(Context.CharTy,
9372                                                               DeclLoc),
9373                              ObjCIvarDecl::Private, BW,
9374                              true);
9375  AllIvarDecls.push_back(Ivar);
9376}
9377
9378void Sema::ActOnFields(Scope* S,
9379                       SourceLocation RecLoc, Decl *EnclosingDecl,
9380                       llvm::ArrayRef<Decl *> Fields,
9381                       SourceLocation LBrac, SourceLocation RBrac,
9382                       AttributeList *Attr) {
9383  assert(EnclosingDecl && "missing record or interface decl");
9384
9385  // If the decl this is being inserted into is invalid, then it may be a
9386  // redeclaration or some other bogus case.  Don't try to add fields to it.
9387  if (EnclosingDecl->isInvalidDecl())
9388    return;
9389
9390  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9391
9392  // Start counting up the number of named members; make sure to include
9393  // members of anonymous structs and unions in the total.
9394  unsigned NumNamedMembers = 0;
9395  if (Record) {
9396    for (RecordDecl::decl_iterator i = Record->decls_begin(),
9397                                   e = Record->decls_end(); i != e; i++) {
9398      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9399        if (IFD->getDeclName())
9400          ++NumNamedMembers;
9401    }
9402  }
9403
9404  // Verify that all the fields are okay.
9405  SmallVector<FieldDecl*, 32> RecFields;
9406
9407  bool ARCErrReported = false;
9408  for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9409       i != end; ++i) {
9410    FieldDecl *FD = cast<FieldDecl>(*i);
9411
9412    // Get the type for the field.
9413    const Type *FDTy = FD->getType().getTypePtr();
9414
9415    if (!FD->isAnonymousStructOrUnion()) {
9416      // Remember all fields written by the user.
9417      RecFields.push_back(FD);
9418    }
9419
9420    // If the field is already invalid for some reason, don't emit more
9421    // diagnostics about it.
9422    if (FD->isInvalidDecl()) {
9423      EnclosingDecl->setInvalidDecl();
9424      continue;
9425    }
9426
9427    // C99 6.7.2.1p2:
9428    //   A structure or union shall not contain a member with
9429    //   incomplete or function type (hence, a structure shall not
9430    //   contain an instance of itself, but may contain a pointer to
9431    //   an instance of itself), except that the last member of a
9432    //   structure with more than one named member may have incomplete
9433    //   array type; such a structure (and any union containing,
9434    //   possibly recursively, a member that is such a structure)
9435    //   shall not be a member of a structure or an element of an
9436    //   array.
9437    if (FDTy->isFunctionType()) {
9438      // Field declared as a function.
9439      Diag(FD->getLocation(), diag::err_field_declared_as_function)
9440        << FD->getDeclName();
9441      FD->setInvalidDecl();
9442      EnclosingDecl->setInvalidDecl();
9443      continue;
9444    } else if (FDTy->isIncompleteArrayType() && Record &&
9445               ((i + 1 == Fields.end() && !Record->isUnion()) ||
9446                ((getLangOpts().MicrosoftExt ||
9447                  getLangOpts().CPlusPlus) &&
9448                 (i + 1 == Fields.end() || Record->isUnion())))) {
9449      // Flexible array member.
9450      // Microsoft and g++ is more permissive regarding flexible array.
9451      // It will accept flexible array in union and also
9452      // as the sole element of a struct/class.
9453      if (getLangOpts().MicrosoftExt) {
9454        if (Record->isUnion())
9455          Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9456            << FD->getDeclName();
9457        else if (Fields.size() == 1)
9458          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9459            << FD->getDeclName() << Record->getTagKind();
9460      } else if (getLangOpts().CPlusPlus) {
9461        if (Record->isUnion())
9462          Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9463            << FD->getDeclName();
9464        else if (Fields.size() == 1)
9465          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9466            << FD->getDeclName() << Record->getTagKind();
9467      } else if (NumNamedMembers < 1) {
9468        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9469          << FD->getDeclName();
9470        FD->setInvalidDecl();
9471        EnclosingDecl->setInvalidDecl();
9472        continue;
9473      }
9474      if (!FD->getType()->isDependentType() &&
9475          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9476        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9477          << FD->getDeclName() << FD->getType();
9478        FD->setInvalidDecl();
9479        EnclosingDecl->setInvalidDecl();
9480        continue;
9481      }
9482      // Okay, we have a legal flexible array member at the end of the struct.
9483      if (Record)
9484        Record->setHasFlexibleArrayMember(true);
9485    } else if (!FDTy->isDependentType() &&
9486               RequireCompleteType(FD->getLocation(), FD->getType(),
9487                                   diag::err_field_incomplete)) {
9488      // Incomplete type
9489      FD->setInvalidDecl();
9490      EnclosingDecl->setInvalidDecl();
9491      continue;
9492    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9493      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9494        // If this is a member of a union, then entire union becomes "flexible".
9495        if (Record && Record->isUnion()) {
9496          Record->setHasFlexibleArrayMember(true);
9497        } else {
9498          // If this is a struct/class and this is not the last element, reject
9499          // it.  Note that GCC supports variable sized arrays in the middle of
9500          // structures.
9501          if (i + 1 != Fields.end())
9502            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9503              << FD->getDeclName() << FD->getType();
9504          else {
9505            // We support flexible arrays at the end of structs in
9506            // other structs as an extension.
9507            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9508              << FD->getDeclName();
9509            if (Record)
9510              Record->setHasFlexibleArrayMember(true);
9511          }
9512        }
9513      }
9514      if (Record && FDTTy->getDecl()->hasObjectMember())
9515        Record->setHasObjectMember(true);
9516    } else if (FDTy->isObjCObjectType()) {
9517      /// A field cannot be an Objective-c object
9518      Diag(FD->getLocation(), diag::err_statically_allocated_object)
9519        << FixItHint::CreateInsertion(FD->getLocation(), "*");
9520      QualType T = Context.getObjCObjectPointerType(FD->getType());
9521      FD->setType(T);
9522    }
9523    else if (!getLangOpts().CPlusPlus) {
9524      if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
9525        // It's an error in ARC if a field has lifetime.
9526        // We don't want to report this in a system header, though,
9527        // so we just make the field unavailable.
9528        // FIXME: that's really not sufficient; we need to make the type
9529        // itself invalid to, say, initialize or copy.
9530        QualType T = FD->getType();
9531        Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9532        if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9533          SourceLocation loc = FD->getLocation();
9534          if (getSourceManager().isInSystemHeader(loc)) {
9535            if (!FD->hasAttr<UnavailableAttr>()) {
9536              FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9537                                "this system field has retaining ownership"));
9538            }
9539          } else {
9540            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9541              << T->isBlockPointerType();
9542          }
9543          ARCErrReported = true;
9544        }
9545      }
9546      else if (getLangOpts().ObjC1 &&
9547               getLangOpts().getGC() != LangOptions::NonGC &&
9548               Record && !Record->hasObjectMember()) {
9549        if (FD->getType()->isObjCObjectPointerType() ||
9550            FD->getType().isObjCGCStrong())
9551          Record->setHasObjectMember(true);
9552        else if (Context.getAsArrayType(FD->getType())) {
9553          QualType BaseType = Context.getBaseElementType(FD->getType());
9554          if (BaseType->isRecordType() &&
9555              BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9556            Record->setHasObjectMember(true);
9557          else if (BaseType->isObjCObjectPointerType() ||
9558                   BaseType.isObjCGCStrong())
9559                 Record->setHasObjectMember(true);
9560        }
9561      }
9562    }
9563    // Keep track of the number of named members.
9564    if (FD->getIdentifier())
9565      ++NumNamedMembers;
9566  }
9567
9568  // Okay, we successfully defined 'Record'.
9569  if (Record) {
9570    bool Completed = false;
9571    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9572      if (!CXXRecord->isInvalidDecl()) {
9573        // Set access bits correctly on the directly-declared conversions.
9574        UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9575        for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9576             I != E; ++I)
9577          Convs->setAccess(I, (*I)->getAccess());
9578
9579        if (!CXXRecord->isDependentType()) {
9580          // Objective-C Automatic Reference Counting:
9581          //   If a class has a non-static data member of Objective-C pointer
9582          //   type (or array thereof), it is a non-POD type and its
9583          //   default constructor (if any), copy constructor, copy assignment
9584          //   operator, and destructor are non-trivial.
9585          //
9586          // This rule is also handled by CXXRecordDecl::completeDefinition().
9587          // However, here we check whether this particular class is only
9588          // non-POD because of the presence of an Objective-C pointer member.
9589          // If so, objects of this type cannot be shared between code compiled
9590          // with instant objects and code compiled with manual retain/release.
9591          if (getLangOpts().ObjCAutoRefCount &&
9592              CXXRecord->hasObjectMember() &&
9593              CXXRecord->getLinkage() == ExternalLinkage) {
9594            if (CXXRecord->isPOD()) {
9595              Diag(CXXRecord->getLocation(),
9596                   diag::warn_arc_non_pod_class_with_object_member)
9597               << CXXRecord;
9598            } else {
9599              // FIXME: Fix-Its would be nice here, but finding a good location
9600              // for them is going to be tricky.
9601              if (CXXRecord->hasTrivialCopyConstructor())
9602                Diag(CXXRecord->getLocation(),
9603                     diag::warn_arc_trivial_member_function_with_object_member)
9604                  << CXXRecord << 0;
9605              if (CXXRecord->hasTrivialCopyAssignment())
9606                Diag(CXXRecord->getLocation(),
9607                     diag::warn_arc_trivial_member_function_with_object_member)
9608                << CXXRecord << 1;
9609              if (CXXRecord->hasTrivialDestructor())
9610                Diag(CXXRecord->getLocation(),
9611                     diag::warn_arc_trivial_member_function_with_object_member)
9612                << CXXRecord << 2;
9613            }
9614          }
9615
9616          // Adjust user-defined destructor exception spec.
9617          if (getLangOpts().CPlusPlus0x &&
9618              CXXRecord->hasUserDeclaredDestructor())
9619            AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9620
9621          // Add any implicitly-declared members to this class.
9622          AddImplicitlyDeclaredMembersToClass(CXXRecord);
9623
9624          // If we have virtual base classes, we may end up finding multiple
9625          // final overriders for a given virtual function. Check for this
9626          // problem now.
9627          if (CXXRecord->getNumVBases()) {
9628            CXXFinalOverriderMap FinalOverriders;
9629            CXXRecord->getFinalOverriders(FinalOverriders);
9630
9631            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9632                                             MEnd = FinalOverriders.end();
9633                 M != MEnd; ++M) {
9634              for (OverridingMethods::iterator SO = M->second.begin(),
9635                                            SOEnd = M->second.end();
9636                   SO != SOEnd; ++SO) {
9637                assert(SO->second.size() > 0 &&
9638                       "Virtual function without overridding functions?");
9639                if (SO->second.size() == 1)
9640                  continue;
9641
9642                // C++ [class.virtual]p2:
9643                //   In a derived class, if a virtual member function of a base
9644                //   class subobject has more than one final overrider the
9645                //   program is ill-formed.
9646                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9647                  << (NamedDecl *)M->first << Record;
9648                Diag(M->first->getLocation(),
9649                     diag::note_overridden_virtual_function);
9650                for (OverridingMethods::overriding_iterator
9651                          OM = SO->second.begin(),
9652                       OMEnd = SO->second.end();
9653                     OM != OMEnd; ++OM)
9654                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
9655                    << (NamedDecl *)M->first << OM->Method->getParent();
9656
9657                Record->setInvalidDecl();
9658              }
9659            }
9660            CXXRecord->completeDefinition(&FinalOverriders);
9661            Completed = true;
9662          }
9663        }
9664      }
9665    }
9666
9667    if (!Completed)
9668      Record->completeDefinition();
9669
9670    // Now that the record is complete, do any delayed exception spec checks
9671    // we were missing.
9672    while (!DelayedDestructorExceptionSpecChecks.empty()) {
9673      const CXXDestructorDecl *Dtor =
9674              DelayedDestructorExceptionSpecChecks.back().first;
9675      if (Dtor->getParent() != Record)
9676        break;
9677
9678      assert(!Dtor->getParent()->isDependentType() &&
9679          "Should not ever add destructors of templates into the list.");
9680      CheckOverridingFunctionExceptionSpec(Dtor,
9681          DelayedDestructorExceptionSpecChecks.back().second);
9682      DelayedDestructorExceptionSpecChecks.pop_back();
9683    }
9684
9685  } else {
9686    ObjCIvarDecl **ClsFields =
9687      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9688    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9689      ID->setEndOfDefinitionLoc(RBrac);
9690      // Add ivar's to class's DeclContext.
9691      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9692        ClsFields[i]->setLexicalDeclContext(ID);
9693        ID->addDecl(ClsFields[i]);
9694      }
9695      // Must enforce the rule that ivars in the base classes may not be
9696      // duplicates.
9697      if (ID->getSuperClass())
9698        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9699    } else if (ObjCImplementationDecl *IMPDecl =
9700                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9701      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9702      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9703        // Ivar declared in @implementation never belongs to the implementation.
9704        // Only it is in implementation's lexical context.
9705        ClsFields[I]->setLexicalDeclContext(IMPDecl);
9706      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9707      IMPDecl->setIvarLBraceLoc(LBrac);
9708      IMPDecl->setIvarRBraceLoc(RBrac);
9709    } else if (ObjCCategoryDecl *CDecl =
9710                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9711      // case of ivars in class extension; all other cases have been
9712      // reported as errors elsewhere.
9713      // FIXME. Class extension does not have a LocEnd field.
9714      // CDecl->setLocEnd(RBrac);
9715      // Add ivar's to class extension's DeclContext.
9716      // Diagnose redeclaration of private ivars.
9717      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9718      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9719        if (IDecl) {
9720          if (const ObjCIvarDecl *ClsIvar =
9721              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9722            Diag(ClsFields[i]->getLocation(),
9723                 diag::err_duplicate_ivar_declaration);
9724            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9725            continue;
9726          }
9727          for (const ObjCCategoryDecl *ClsExtDecl =
9728                IDecl->getFirstClassExtension();
9729               ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9730            if (const ObjCIvarDecl *ClsExtIvar =
9731                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9732              Diag(ClsFields[i]->getLocation(),
9733                   diag::err_duplicate_ivar_declaration);
9734              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9735              continue;
9736            }
9737          }
9738        }
9739        ClsFields[i]->setLexicalDeclContext(CDecl);
9740        CDecl->addDecl(ClsFields[i]);
9741      }
9742      CDecl->setIvarLBraceLoc(LBrac);
9743      CDecl->setIvarRBraceLoc(RBrac);
9744    }
9745  }
9746
9747  if (Attr)
9748    ProcessDeclAttributeList(S, Record, Attr);
9749
9750  // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9751  // set the visibility of this record.
9752  if (Record && !Record->getDeclContext()->isRecord())
9753    AddPushedVisibilityAttribute(Record);
9754}
9755
9756/// \brief Determine whether the given integral value is representable within
9757/// the given type T.
9758static bool isRepresentableIntegerValue(ASTContext &Context,
9759                                        llvm::APSInt &Value,
9760                                        QualType T) {
9761  assert(T->isIntegralType(Context) && "Integral type required!");
9762  unsigned BitWidth = Context.getIntWidth(T);
9763
9764  if (Value.isUnsigned() || Value.isNonNegative()) {
9765    if (T->isSignedIntegerOrEnumerationType())
9766      --BitWidth;
9767    return Value.getActiveBits() <= BitWidth;
9768  }
9769  return Value.getMinSignedBits() <= BitWidth;
9770}
9771
9772// \brief Given an integral type, return the next larger integral type
9773// (or a NULL type of no such type exists).
9774static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9775  // FIXME: Int128/UInt128 support, which also needs to be introduced into
9776  // enum checking below.
9777  assert(T->isIntegralType(Context) && "Integral type required!");
9778  const unsigned NumTypes = 4;
9779  QualType SignedIntegralTypes[NumTypes] = {
9780    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9781  };
9782  QualType UnsignedIntegralTypes[NumTypes] = {
9783    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9784    Context.UnsignedLongLongTy
9785  };
9786
9787  unsigned BitWidth = Context.getTypeSize(T);
9788  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9789                                                        : UnsignedIntegralTypes;
9790  for (unsigned I = 0; I != NumTypes; ++I)
9791    if (Context.getTypeSize(Types[I]) > BitWidth)
9792      return Types[I];
9793
9794  return QualType();
9795}
9796
9797EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9798                                          EnumConstantDecl *LastEnumConst,
9799                                          SourceLocation IdLoc,
9800                                          IdentifierInfo *Id,
9801                                          Expr *Val) {
9802  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9803  llvm::APSInt EnumVal(IntWidth);
9804  QualType EltTy;
9805
9806  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9807    Val = 0;
9808
9809  if (Val)
9810    Val = DefaultLvalueConversion(Val).take();
9811
9812  if (Val) {
9813    if (Enum->isDependentType() || Val->isTypeDependent())
9814      EltTy = Context.DependentTy;
9815    else {
9816      SourceLocation ExpLoc;
9817      if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9818          !getLangOpts().MicrosoftMode) {
9819        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9820        // constant-expression in the enumerator-definition shall be a converted
9821        // constant expression of the underlying type.
9822        EltTy = Enum->getIntegerType();
9823        ExprResult Converted =
9824          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9825                                           CCEK_Enumerator);
9826        if (Converted.isInvalid())
9827          Val = 0;
9828        else
9829          Val = Converted.take();
9830      } else if (!Val->isValueDependent() &&
9831                 !(Val = VerifyIntegerConstantExpression(Val,
9832                                                         &EnumVal).take())) {
9833        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9834      } else {
9835        if (Enum->isFixed()) {
9836          EltTy = Enum->getIntegerType();
9837
9838          // In Obj-C and Microsoft mode, require the enumeration value to be
9839          // representable in the underlying type of the enumeration. In C++11,
9840          // we perform a non-narrowing conversion as part of converted constant
9841          // expression checking.
9842          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9843            if (getLangOpts().MicrosoftMode) {
9844              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9845              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9846            } else
9847              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
9848          } else
9849            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9850        } else if (getLangOpts().CPlusPlus) {
9851          // C++11 [dcl.enum]p5:
9852          //   If the underlying type is not fixed, the type of each enumerator
9853          //   is the type of its initializing value:
9854          //     - If an initializer is specified for an enumerator, the
9855          //       initializing value has the same type as the expression.
9856          EltTy = Val->getType();
9857        } else {
9858          // C99 6.7.2.2p2:
9859          //   The expression that defines the value of an enumeration constant
9860          //   shall be an integer constant expression that has a value
9861          //   representable as an int.
9862
9863          // Complain if the value is not representable in an int.
9864          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9865            Diag(IdLoc, diag::ext_enum_value_not_int)
9866              << EnumVal.toString(10) << Val->getSourceRange()
9867              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9868          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9869            // Force the type of the expression to 'int'.
9870            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9871          }
9872          EltTy = Val->getType();
9873        }
9874      }
9875    }
9876  }
9877
9878  if (!Val) {
9879    if (Enum->isDependentType())
9880      EltTy = Context.DependentTy;
9881    else if (!LastEnumConst) {
9882      // C++0x [dcl.enum]p5:
9883      //   If the underlying type is not fixed, the type of each enumerator
9884      //   is the type of its initializing value:
9885      //     - If no initializer is specified for the first enumerator, the
9886      //       initializing value has an unspecified integral type.
9887      //
9888      // GCC uses 'int' for its unspecified integral type, as does
9889      // C99 6.7.2.2p3.
9890      if (Enum->isFixed()) {
9891        EltTy = Enum->getIntegerType();
9892      }
9893      else {
9894        EltTy = Context.IntTy;
9895      }
9896    } else {
9897      // Assign the last value + 1.
9898      EnumVal = LastEnumConst->getInitVal();
9899      ++EnumVal;
9900      EltTy = LastEnumConst->getType();
9901
9902      // Check for overflow on increment.
9903      if (EnumVal < LastEnumConst->getInitVal()) {
9904        // C++0x [dcl.enum]p5:
9905        //   If the underlying type is not fixed, the type of each enumerator
9906        //   is the type of its initializing value:
9907        //
9908        //     - Otherwise the type of the initializing value is the same as
9909        //       the type of the initializing value of the preceding enumerator
9910        //       unless the incremented value is not representable in that type,
9911        //       in which case the type is an unspecified integral type
9912        //       sufficient to contain the incremented value. If no such type
9913        //       exists, the program is ill-formed.
9914        QualType T = getNextLargerIntegralType(Context, EltTy);
9915        if (T.isNull() || Enum->isFixed()) {
9916          // There is no integral type larger enough to represent this
9917          // value. Complain, then allow the value to wrap around.
9918          EnumVal = LastEnumConst->getInitVal();
9919          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
9920          ++EnumVal;
9921          if (Enum->isFixed())
9922            // When the underlying type is fixed, this is ill-formed.
9923            Diag(IdLoc, diag::err_enumerator_wrapped)
9924              << EnumVal.toString(10)
9925              << EltTy;
9926          else
9927            Diag(IdLoc, diag::warn_enumerator_too_large)
9928              << EnumVal.toString(10);
9929        } else {
9930          EltTy = T;
9931        }
9932
9933        // Retrieve the last enumerator's value, extent that type to the
9934        // type that is supposed to be large enough to represent the incremented
9935        // value, then increment.
9936        EnumVal = LastEnumConst->getInitVal();
9937        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9938        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
9939        ++EnumVal;
9940
9941        // If we're not in C++, diagnose the overflow of enumerator values,
9942        // which in C99 means that the enumerator value is not representable in
9943        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
9944        // permits enumerator values that are representable in some larger
9945        // integral type.
9946        if (!getLangOpts().CPlusPlus && !T.isNull())
9947          Diag(IdLoc, diag::warn_enum_value_overflow);
9948      } else if (!getLangOpts().CPlusPlus &&
9949                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9950        // Enforce C99 6.7.2.2p2 even when we compute the next value.
9951        Diag(IdLoc, diag::ext_enum_value_not_int)
9952          << EnumVal.toString(10) << 1;
9953      }
9954    }
9955  }
9956
9957  if (!EltTy->isDependentType()) {
9958    // Make the enumerator value match the signedness and size of the
9959    // enumerator's type.
9960    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
9961    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9962  }
9963
9964  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
9965                                  Val, EnumVal);
9966}
9967
9968
9969Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
9970                              SourceLocation IdLoc, IdentifierInfo *Id,
9971                              AttributeList *Attr,
9972                              SourceLocation EqualLoc, Expr *Val) {
9973  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
9974  EnumConstantDecl *LastEnumConst =
9975    cast_or_null<EnumConstantDecl>(lastEnumConst);
9976
9977  // The scope passed in may not be a decl scope.  Zip up the scope tree until
9978  // we find one that is.
9979  S = getNonFieldDeclScope(S);
9980
9981  // Verify that there isn't already something declared with this name in this
9982  // scope.
9983  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
9984                                         ForRedeclaration);
9985  if (PrevDecl && PrevDecl->isTemplateParameter()) {
9986    // Maybe we will complain about the shadowed template parameter.
9987    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
9988    // Just pretend that we didn't see the previous declaration.
9989    PrevDecl = 0;
9990  }
9991
9992  if (PrevDecl) {
9993    // When in C++, we may get a TagDecl with the same name; in this case the
9994    // enum constant will 'hide' the tag.
9995    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
9996           "Received TagDecl when not in C++!");
9997    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
9998      if (isa<EnumConstantDecl>(PrevDecl))
9999        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10000      else
10001        Diag(IdLoc, diag::err_redefinition) << Id;
10002      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10003      return 0;
10004    }
10005  }
10006
10007  // C++ [class.mem]p13:
10008  //   If T is the name of a class, then each of the following shall have a
10009  //   name different from T:
10010  //     - every enumerator of every member of class T that is an enumerated
10011  //       type
10012  if (CXXRecordDecl *Record
10013                      = dyn_cast<CXXRecordDecl>(
10014                             TheEnumDecl->getDeclContext()->getRedeclContext()))
10015    if (Record->getIdentifier() && Record->getIdentifier() == Id)
10016      Diag(IdLoc, diag::err_member_name_of_class) << Id;
10017
10018  EnumConstantDecl *New =
10019    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10020
10021  if (New) {
10022    // Process attributes.
10023    if (Attr) ProcessDeclAttributeList(S, New, Attr);
10024
10025    // Register this decl in the current scope stack.
10026    New->setAccess(TheEnumDecl->getAccess());
10027    PushOnScopeChains(New, S);
10028  }
10029
10030  return New;
10031}
10032
10033void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10034                         SourceLocation RBraceLoc, Decl *EnumDeclX,
10035                         Decl **Elements, unsigned NumElements,
10036                         Scope *S, AttributeList *Attr) {
10037  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10038  QualType EnumType = Context.getTypeDeclType(Enum);
10039
10040  if (Attr)
10041    ProcessDeclAttributeList(S, Enum, Attr);
10042
10043  if (Enum->isDependentType()) {
10044    for (unsigned i = 0; i != NumElements; ++i) {
10045      EnumConstantDecl *ECD =
10046        cast_or_null<EnumConstantDecl>(Elements[i]);
10047      if (!ECD) continue;
10048
10049      ECD->setType(EnumType);
10050    }
10051
10052    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10053    return;
10054  }
10055
10056  // TODO: If the result value doesn't fit in an int, it must be a long or long
10057  // long value.  ISO C does not support this, but GCC does as an extension,
10058  // emit a warning.
10059  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10060  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10061  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10062
10063  // Verify that all the values are okay, compute the size of the values, and
10064  // reverse the list.
10065  unsigned NumNegativeBits = 0;
10066  unsigned NumPositiveBits = 0;
10067
10068  // Keep track of whether all elements have type int.
10069  bool AllElementsInt = true;
10070
10071  for (unsigned i = 0; i != NumElements; ++i) {
10072    EnumConstantDecl *ECD =
10073      cast_or_null<EnumConstantDecl>(Elements[i]);
10074    if (!ECD) continue;  // Already issued a diagnostic.
10075
10076    const llvm::APSInt &InitVal = ECD->getInitVal();
10077
10078    // Keep track of the size of positive and negative values.
10079    if (InitVal.isUnsigned() || InitVal.isNonNegative())
10080      NumPositiveBits = std::max(NumPositiveBits,
10081                                 (unsigned)InitVal.getActiveBits());
10082    else
10083      NumNegativeBits = std::max(NumNegativeBits,
10084                                 (unsigned)InitVal.getMinSignedBits());
10085
10086    // Keep track of whether every enum element has type int (very commmon).
10087    if (AllElementsInt)
10088      AllElementsInt = ECD->getType() == Context.IntTy;
10089  }
10090
10091  // Figure out the type that should be used for this enum.
10092  QualType BestType;
10093  unsigned BestWidth;
10094
10095  // C++0x N3000 [conv.prom]p3:
10096  //   An rvalue of an unscoped enumeration type whose underlying
10097  //   type is not fixed can be converted to an rvalue of the first
10098  //   of the following types that can represent all the values of
10099  //   the enumeration: int, unsigned int, long int, unsigned long
10100  //   int, long long int, or unsigned long long int.
10101  // C99 6.4.4.3p2:
10102  //   An identifier declared as an enumeration constant has type int.
10103  // The C99 rule is modified by a gcc extension
10104  QualType BestPromotionType;
10105
10106  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10107  // -fshort-enums is the equivalent to specifying the packed attribute on all
10108  // enum definitions.
10109  if (LangOpts.ShortEnums)
10110    Packed = true;
10111
10112  if (Enum->isFixed()) {
10113    BestType = Enum->getIntegerType();
10114    if (BestType->isPromotableIntegerType())
10115      BestPromotionType = Context.getPromotedIntegerType(BestType);
10116    else
10117      BestPromotionType = BestType;
10118    // We don't need to set BestWidth, because BestType is going to be the type
10119    // of the enumerators, but we do anyway because otherwise some compilers
10120    // warn that it might be used uninitialized.
10121    BestWidth = CharWidth;
10122  }
10123  else if (NumNegativeBits) {
10124    // If there is a negative value, figure out the smallest integer type (of
10125    // int/long/longlong) that fits.
10126    // If it's packed, check also if it fits a char or a short.
10127    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10128      BestType = Context.SignedCharTy;
10129      BestWidth = CharWidth;
10130    } else if (Packed && NumNegativeBits <= ShortWidth &&
10131               NumPositiveBits < ShortWidth) {
10132      BestType = Context.ShortTy;
10133      BestWidth = ShortWidth;
10134    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10135      BestType = Context.IntTy;
10136      BestWidth = IntWidth;
10137    } else {
10138      BestWidth = Context.getTargetInfo().getLongWidth();
10139
10140      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10141        BestType = Context.LongTy;
10142      } else {
10143        BestWidth = Context.getTargetInfo().getLongLongWidth();
10144
10145        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10146          Diag(Enum->getLocation(), diag::warn_enum_too_large);
10147        BestType = Context.LongLongTy;
10148      }
10149    }
10150    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10151  } else {
10152    // If there is no negative value, figure out the smallest type that fits
10153    // all of the enumerator values.
10154    // If it's packed, check also if it fits a char or a short.
10155    if (Packed && NumPositiveBits <= CharWidth) {
10156      BestType = Context.UnsignedCharTy;
10157      BestPromotionType = Context.IntTy;
10158      BestWidth = CharWidth;
10159    } else if (Packed && NumPositiveBits <= ShortWidth) {
10160      BestType = Context.UnsignedShortTy;
10161      BestPromotionType = Context.IntTy;
10162      BestWidth = ShortWidth;
10163    } else if (NumPositiveBits <= IntWidth) {
10164      BestType = Context.UnsignedIntTy;
10165      BestWidth = IntWidth;
10166      BestPromotionType
10167        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10168                           ? Context.UnsignedIntTy : Context.IntTy;
10169    } else if (NumPositiveBits <=
10170               (BestWidth = Context.getTargetInfo().getLongWidth())) {
10171      BestType = Context.UnsignedLongTy;
10172      BestPromotionType
10173        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10174                           ? Context.UnsignedLongTy : Context.LongTy;
10175    } else {
10176      BestWidth = Context.getTargetInfo().getLongLongWidth();
10177      assert(NumPositiveBits <= BestWidth &&
10178             "How could an initializer get larger than ULL?");
10179      BestType = Context.UnsignedLongLongTy;
10180      BestPromotionType
10181        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10182                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
10183    }
10184  }
10185
10186  // Loop over all of the enumerator constants, changing their types to match
10187  // the type of the enum if needed.
10188  for (unsigned i = 0; i != NumElements; ++i) {
10189    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10190    if (!ECD) continue;  // Already issued a diagnostic.
10191
10192    // Standard C says the enumerators have int type, but we allow, as an
10193    // extension, the enumerators to be larger than int size.  If each
10194    // enumerator value fits in an int, type it as an int, otherwise type it the
10195    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
10196    // that X has type 'int', not 'unsigned'.
10197
10198    // Determine whether the value fits into an int.
10199    llvm::APSInt InitVal = ECD->getInitVal();
10200
10201    // If it fits into an integer type, force it.  Otherwise force it to match
10202    // the enum decl type.
10203    QualType NewTy;
10204    unsigned NewWidth;
10205    bool NewSign;
10206    if (!getLangOpts().CPlusPlus &&
10207        !Enum->isFixed() &&
10208        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10209      NewTy = Context.IntTy;
10210      NewWidth = IntWidth;
10211      NewSign = true;
10212    } else if (ECD->getType() == BestType) {
10213      // Already the right type!
10214      if (getLangOpts().CPlusPlus)
10215        // C++ [dcl.enum]p4: Following the closing brace of an
10216        // enum-specifier, each enumerator has the type of its
10217        // enumeration.
10218        ECD->setType(EnumType);
10219      continue;
10220    } else {
10221      NewTy = BestType;
10222      NewWidth = BestWidth;
10223      NewSign = BestType->isSignedIntegerOrEnumerationType();
10224    }
10225
10226    // Adjust the APSInt value.
10227    InitVal = InitVal.extOrTrunc(NewWidth);
10228    InitVal.setIsSigned(NewSign);
10229    ECD->setInitVal(InitVal);
10230
10231    // Adjust the Expr initializer and type.
10232    if (ECD->getInitExpr() &&
10233        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10234      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10235                                                CK_IntegralCast,
10236                                                ECD->getInitExpr(),
10237                                                /*base paths*/ 0,
10238                                                VK_RValue));
10239    if (getLangOpts().CPlusPlus)
10240      // C++ [dcl.enum]p4: Following the closing brace of an
10241      // enum-specifier, each enumerator has the type of its
10242      // enumeration.
10243      ECD->setType(EnumType);
10244    else
10245      ECD->setType(NewTy);
10246  }
10247
10248  Enum->completeDefinition(BestType, BestPromotionType,
10249                           NumPositiveBits, NumNegativeBits);
10250
10251  // If we're declaring a function, ensure this decl isn't forgotten about -
10252  // it needs to go into the function scope.
10253  if (InFunctionDeclarator)
10254    DeclsInPrototypeScope.push_back(Enum);
10255
10256}
10257
10258Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10259                                  SourceLocation StartLoc,
10260                                  SourceLocation EndLoc) {
10261  StringLiteral *AsmString = cast<StringLiteral>(expr);
10262
10263  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10264                                                   AsmString, StartLoc,
10265                                                   EndLoc);
10266  CurContext->addDecl(New);
10267  return New;
10268}
10269
10270DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10271                                   SourceLocation ImportLoc,
10272                                   ModuleIdPath Path) {
10273  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
10274                                                Module::AllVisible,
10275                                                /*IsIncludeDirective=*/false);
10276  if (!Mod)
10277    return true;
10278
10279  llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10280  Module *ModCheck = Mod;
10281  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10282    // If we've run out of module parents, just drop the remaining identifiers.
10283    // We need the length to be consistent.
10284    if (!ModCheck)
10285      break;
10286    ModCheck = ModCheck->Parent;
10287
10288    IdentifierLocs.push_back(Path[I].second);
10289  }
10290
10291  ImportDecl *Import = ImportDecl::Create(Context,
10292                                          Context.getTranslationUnitDecl(),
10293                                          AtLoc.isValid()? AtLoc : ImportLoc,
10294                                          Mod, IdentifierLocs);
10295  Context.getTranslationUnitDecl()->addDecl(Import);
10296  return Import;
10297}
10298
10299void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10300                                      IdentifierInfo* AliasName,
10301                                      SourceLocation PragmaLoc,
10302                                      SourceLocation NameLoc,
10303                                      SourceLocation AliasNameLoc) {
10304  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10305                                    LookupOrdinaryName);
10306  AsmLabelAttr *Attr =
10307     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
10308
10309  if (PrevDecl)
10310    PrevDecl->addAttr(Attr);
10311  else
10312    (void)ExtnameUndeclaredIdentifiers.insert(
10313      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10314}
10315
10316void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10317                             SourceLocation PragmaLoc,
10318                             SourceLocation NameLoc) {
10319  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
10320
10321  if (PrevDecl) {
10322    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
10323  } else {
10324    (void)WeakUndeclaredIdentifiers.insert(
10325      std::pair<IdentifierInfo*,WeakInfo>
10326        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
10327  }
10328}
10329
10330void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10331                                IdentifierInfo* AliasName,
10332                                SourceLocation PragmaLoc,
10333                                SourceLocation NameLoc,
10334                                SourceLocation AliasNameLoc) {
10335  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10336                                    LookupOrdinaryName);
10337  WeakInfo W = WeakInfo(Name, NameLoc);
10338
10339  if (PrevDecl) {
10340    if (!PrevDecl->hasAttr<AliasAttr>())
10341      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
10342        DeclApplyPragmaWeak(TUScope, ND, W);
10343  } else {
10344    (void)WeakUndeclaredIdentifiers.insert(
10345      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
10346  }
10347}
10348
10349Decl *Sema::getObjCDeclContext() const {
10350  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10351}
10352
10353AvailabilityResult Sema::getCurContextAvailability() const {
10354  const Decl *D = cast<Decl>(getCurLexicalContext());
10355  // A category implicitly has the availability of the interface.
10356  if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10357    D = CatD->getClassInterface();
10358
10359  return D->getAvailability();
10360}
10361