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