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