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