SemaDecl.cpp revision 3b25216a47681e7957c0e9ec37a3cf445ab24743
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.setFunctionDefinition(false);
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 (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
4999        D.isFunctionDefinition()) {
5000      // A method is implicitly inline if it's defined in its class
5001      // definition.
5002      NewFD->setImplicitlyInline();
5003    }
5004
5005    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5006        !CurContext->isRecord()) {
5007      // C++ [class.static]p1:
5008      //   A data or function member of a class may be declared static
5009      //   in a class definition, in which case it is a static member of
5010      //   the class.
5011
5012      // Complain about the 'static' specifier if it's on an out-of-line
5013      // member function definition.
5014      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5015           diag::err_static_out_of_line)
5016        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5017    }
5018  }
5019
5020  // Filter out previous declarations that don't match the scope.
5021  FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5022                       isExplicitSpecialization ||
5023                       isFunctionTemplateSpecialization);
5024
5025  // Handle GNU asm-label extension (encoded as an attribute).
5026  if (Expr *E = (Expr*) D.getAsmLabel()) {
5027    // The parser guarantees this is a string.
5028    StringLiteral *SE = cast<StringLiteral>(E);
5029    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5030                                                SE->getString()));
5031  }
5032
5033  // Copy the parameter declarations from the declarator D to the function
5034  // declaration NewFD, if they are available.  First scavenge them into Params.
5035  SmallVector<ParmVarDecl*, 16> Params;
5036  if (D.isFunctionDeclarator()) {
5037    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5038
5039    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5040    // function that takes no arguments, not a function that takes a
5041    // single void argument.
5042    // We let through "const void" here because Sema::GetTypeForDeclarator
5043    // already checks for that case.
5044    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5045        FTI.ArgInfo[0].Param &&
5046        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5047      // Empty arg list, don't push any params.
5048      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5049
5050      // In C++, the empty parameter-type-list must be spelled "void"; a
5051      // typedef of void is not permitted.
5052      if (getLangOptions().CPlusPlus &&
5053          Param->getType().getUnqualifiedType() != Context.VoidTy) {
5054        bool IsTypeAlias = false;
5055        if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5056          IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5057        else if (const TemplateSpecializationType *TST =
5058                   Param->getType()->getAs<TemplateSpecializationType>())
5059          IsTypeAlias = TST->isTypeAlias();
5060        Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5061          << IsTypeAlias;
5062      }
5063    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5064      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5065        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5066        assert(Param->getDeclContext() != NewFD && "Was set before ?");
5067        Param->setDeclContext(NewFD);
5068        Params.push_back(Param);
5069
5070        if (Param->isInvalidDecl())
5071          NewFD->setInvalidDecl();
5072      }
5073    }
5074
5075  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5076    // When we're declaring a function with a typedef, typeof, etc as in the
5077    // following example, we'll need to synthesize (unnamed)
5078    // parameters for use in the declaration.
5079    //
5080    // @code
5081    // typedef void fn(int);
5082    // fn f;
5083    // @endcode
5084
5085    // Synthesize a parameter for each argument type.
5086    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5087         AE = FT->arg_type_end(); AI != AE; ++AI) {
5088      ParmVarDecl *Param =
5089        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5090      Param->setScopeInfo(0, Params.size());
5091      Params.push_back(Param);
5092    }
5093  } else {
5094    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5095           "Should not need args for typedef of non-prototype fn");
5096  }
5097
5098  // Finally, we know we have the right number of parameters, install them.
5099  NewFD->setParams(Params);
5100
5101  // Process the non-inheritable attributes on this declaration.
5102  ProcessDeclAttributes(S, NewFD, D,
5103                        /*NonInheritable=*/true, /*Inheritable=*/false);
5104
5105  if (!getLangOptions().CPlusPlus) {
5106    // Perform semantic checking on the function declaration.
5107    bool isExplicitSpecialization=false;
5108    if (!NewFD->isInvalidDecl()) {
5109      if (NewFD->getResultType()->isVariablyModifiedType()) {
5110        // Functions returning a variably modified type violate C99 6.7.5.2p2
5111        // because all functions have linkage.
5112        Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5113        NewFD->setInvalidDecl();
5114      } else {
5115        if (NewFD->isMain())
5116          CheckMain(NewFD, D.getDeclSpec());
5117        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5118                                                    isExplicitSpecialization));
5119      }
5120    }
5121    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5122            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5123           "previous declaration set still overloaded");
5124  } else {
5125    // If the declarator is a template-id, translate the parser's template
5126    // argument list into our AST format.
5127    bool HasExplicitTemplateArgs = false;
5128    TemplateArgumentListInfo TemplateArgs;
5129    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5130      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5131      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5132      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5133      ASTTemplateArgsPtr TemplateArgsPtr(*this,
5134                                         TemplateId->getTemplateArgs(),
5135                                         TemplateId->NumArgs);
5136      translateTemplateArguments(TemplateArgsPtr,
5137                                 TemplateArgs);
5138      TemplateArgsPtr.release();
5139
5140      HasExplicitTemplateArgs = true;
5141
5142      if (NewFD->isInvalidDecl()) {
5143        HasExplicitTemplateArgs = false;
5144      } else if (FunctionTemplate) {
5145        // Function template with explicit template arguments.
5146        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5147          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5148
5149        HasExplicitTemplateArgs = false;
5150      } else if (!isFunctionTemplateSpecialization &&
5151                 !D.getDeclSpec().isFriendSpecified()) {
5152        // We have encountered something that the user meant to be a
5153        // specialization (because it has explicitly-specified template
5154        // arguments) but that was not introduced with a "template<>" (or had
5155        // too few of them).
5156        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5157          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5158          << FixItHint::CreateInsertion(
5159                                    D.getDeclSpec().getSourceRange().getBegin(),
5160                                        "template<> ");
5161        isFunctionTemplateSpecialization = true;
5162      } else {
5163        // "friend void foo<>(int);" is an implicit specialization decl.
5164        isFunctionTemplateSpecialization = true;
5165      }
5166    } else if (isFriend && isFunctionTemplateSpecialization) {
5167      // This combination is only possible in a recovery case;  the user
5168      // wrote something like:
5169      //   template <> friend void foo(int);
5170      // which we're recovering from as if the user had written:
5171      //   friend void foo<>(int);
5172      // Go ahead and fake up a template id.
5173      HasExplicitTemplateArgs = true;
5174        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5175      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5176    }
5177
5178    // If it's a friend (and only if it's a friend), it's possible
5179    // that either the specialized function type or the specialized
5180    // template is dependent, and therefore matching will fail.  In
5181    // this case, don't check the specialization yet.
5182    bool InstantiationDependent = false;
5183    if (isFunctionTemplateSpecialization && isFriend &&
5184        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5185         TemplateSpecializationType::anyDependentTemplateArguments(
5186            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5187            InstantiationDependent))) {
5188      assert(HasExplicitTemplateArgs &&
5189             "friend function specialization without template args");
5190      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5191                                                       Previous))
5192        NewFD->setInvalidDecl();
5193    } else if (isFunctionTemplateSpecialization) {
5194      if (CurContext->isDependentContext() && CurContext->isRecord()
5195          && !isFriend) {
5196        isDependentClassScopeExplicitSpecialization = true;
5197        Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ?
5198          diag::ext_function_specialization_in_class :
5199          diag::err_function_specialization_in_class)
5200          << NewFD->getDeclName();
5201      } else if (CheckFunctionTemplateSpecialization(NewFD,
5202                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5203                                                     Previous))
5204        NewFD->setInvalidDecl();
5205
5206      // C++ [dcl.stc]p1:
5207      //   A storage-class-specifier shall not be specified in an explicit
5208      //   specialization (14.7.3)
5209      if (SC != SC_None) {
5210        if (SC != NewFD->getStorageClass())
5211          Diag(NewFD->getLocation(),
5212               diag::err_explicit_specialization_inconsistent_storage_class)
5213            << SC
5214            << FixItHint::CreateRemoval(
5215                                      D.getDeclSpec().getStorageClassSpecLoc());
5216
5217        else
5218          Diag(NewFD->getLocation(),
5219               diag::ext_explicit_specialization_storage_class)
5220            << FixItHint::CreateRemoval(
5221                                      D.getDeclSpec().getStorageClassSpecLoc());
5222      }
5223
5224    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5225      if (CheckMemberSpecialization(NewFD, Previous))
5226          NewFD->setInvalidDecl();
5227    }
5228
5229    // Perform semantic checking on the function declaration.
5230    if (!isDependentClassScopeExplicitSpecialization) {
5231      if (NewFD->isInvalidDecl()) {
5232        // If this is a class member, mark the class invalid immediately.
5233        // This avoids some consistency errors later.
5234        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5235          methodDecl->getParent()->setInvalidDecl();
5236      } else {
5237        if (NewFD->isMain())
5238          CheckMain(NewFD, D.getDeclSpec());
5239        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5240                                                    isExplicitSpecialization));
5241      }
5242    }
5243
5244    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5245            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5246           "previous declaration set still overloaded");
5247
5248    if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() &&
5249        !CheckConstexprFunctionDecl(NewFD, CCK_Declaration))
5250      NewFD->setInvalidDecl();
5251
5252    NamedDecl *PrincipalDecl = (FunctionTemplate
5253                                ? cast<NamedDecl>(FunctionTemplate)
5254                                : NewFD);
5255
5256    if (isFriend && D.isRedeclaration()) {
5257      AccessSpecifier Access = AS_public;
5258      if (!NewFD->isInvalidDecl())
5259        Access = NewFD->getPreviousDeclaration()->getAccess();
5260
5261      NewFD->setAccess(Access);
5262      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5263
5264      PrincipalDecl->setObjectOfFriendDecl(true);
5265    }
5266
5267    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5268        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5269      PrincipalDecl->setNonMemberOperator();
5270
5271    // If we have a function template, check the template parameter
5272    // list. This will check and merge default template arguments.
5273    if (FunctionTemplate) {
5274      FunctionTemplateDecl *PrevTemplate =
5275                                     FunctionTemplate->getPreviousDeclaration();
5276      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5277                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5278                            D.getDeclSpec().isFriendSpecified()
5279                              ? (D.isFunctionDefinition()
5280                                   ? TPC_FriendFunctionTemplateDefinition
5281                                   : TPC_FriendFunctionTemplate)
5282                              : (D.getCXXScopeSpec().isSet() &&
5283                                 DC && DC->isRecord() &&
5284                                 DC->isDependentContext())
5285                                  ? TPC_ClassTemplateMember
5286                                  : TPC_FunctionTemplate);
5287    }
5288
5289    if (NewFD->isInvalidDecl()) {
5290      // Ignore all the rest of this.
5291    } else if (!D.isRedeclaration()) {
5292      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5293                                       AddToScope };
5294      // Fake up an access specifier if it's supposed to be a class member.
5295      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5296        NewFD->setAccess(AS_public);
5297
5298      // Qualified decls generally require a previous declaration.
5299      if (D.getCXXScopeSpec().isSet()) {
5300        // ...with the major exception of templated-scope or
5301        // dependent-scope friend declarations.
5302
5303        // TODO: we currently also suppress this check in dependent
5304        // contexts because (1) the parameter depth will be off when
5305        // matching friend templates and (2) we might actually be
5306        // selecting a friend based on a dependent factor.  But there
5307        // are situations where these conditions don't apply and we
5308        // can actually do this check immediately.
5309        if (isFriend &&
5310            (TemplateParamLists.size() ||
5311             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5312             CurContext->isDependentContext())) {
5313          // ignore these
5314        } else {
5315          // The user tried to provide an out-of-line definition for a
5316          // function that is a member of a class or namespace, but there
5317          // was no such member function declared (C++ [class.mfct]p2,
5318          // C++ [namespace.memdef]p2). For example:
5319          //
5320          // class X {
5321          //   void f() const;
5322          // };
5323          //
5324          // void X::f() { } // ill-formed
5325          //
5326          // Complain about this problem, and attempt to suggest close
5327          // matches (e.g., those that differ only in cv-qualifiers and
5328          // whether the parameter types are references).
5329
5330          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5331                                                               NewFD,
5332                                                               ExtraArgs)) {
5333            AddToScope = ExtraArgs.AddToScope;
5334            return Result;
5335          }
5336        }
5337
5338        // Unqualified local friend declarations are required to resolve
5339        // to something.
5340      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5341        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5342                                                             NewFD,
5343                                                             ExtraArgs)) {
5344          AddToScope = ExtraArgs.AddToScope;
5345          return Result;
5346        }
5347      }
5348
5349    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5350               !isFriend && !isFunctionTemplateSpecialization &&
5351               !isExplicitSpecialization) {
5352      // An out-of-line member function declaration must also be a
5353      // definition (C++ [dcl.meaning]p1).
5354      // Note that this is not the case for explicit specializations of
5355      // function templates or member functions of class templates, per
5356      // C++ [temp.expl.spec]p2. We also allow these declarations as an
5357      // extension for compatibility with old SWIG code which likes to
5358      // generate them.
5359      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5360        << D.getCXXScopeSpec().getRange();
5361    }
5362  }
5363
5364
5365  // Handle attributes. We need to have merged decls when handling attributes
5366  // (for example to check for conflicts, etc).
5367  // FIXME: This needs to happen before we merge declarations. Then,
5368  // let attribute merging cope with attribute conflicts.
5369  ProcessDeclAttributes(S, NewFD, D,
5370                        /*NonInheritable=*/false, /*Inheritable=*/true);
5371
5372  // attributes declared post-definition are currently ignored
5373  // FIXME: This should happen during attribute merging
5374  if (D.isRedeclaration() && Previous.isSingleResult()) {
5375    const FunctionDecl *Def;
5376    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5377    if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5378      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5379      Diag(Def->getLocation(), diag::note_previous_definition);
5380    }
5381  }
5382
5383  AddKnownFunctionAttributes(NewFD);
5384
5385  if (NewFD->hasAttr<OverloadableAttr>() &&
5386      !NewFD->getType()->getAs<FunctionProtoType>()) {
5387    Diag(NewFD->getLocation(),
5388         diag::err_attribute_overloadable_no_prototype)
5389      << NewFD;
5390
5391    // Turn this into a variadic function with no parameters.
5392    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5393    FunctionProtoType::ExtProtoInfo EPI;
5394    EPI.Variadic = true;
5395    EPI.ExtInfo = FT->getExtInfo();
5396
5397    QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5398    NewFD->setType(R);
5399  }
5400
5401  // If there's a #pragma GCC visibility in scope, and this isn't a class
5402  // member, set the visibility of this function.
5403  if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5404    AddPushedVisibilityAttribute(NewFD);
5405
5406  // If there's a #pragma clang arc_cf_code_audited in scope, consider
5407  // marking the function.
5408  AddCFAuditedAttribute(NewFD);
5409
5410  // If this is a locally-scoped extern C function, update the
5411  // map of such names.
5412  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5413      && !NewFD->isInvalidDecl())
5414    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5415
5416  // Set this FunctionDecl's range up to the right paren.
5417  NewFD->setRangeEnd(D.getSourceRange().getEnd());
5418
5419  if (getLangOptions().CPlusPlus) {
5420    if (FunctionTemplate) {
5421      if (NewFD->isInvalidDecl())
5422        FunctionTemplate->setInvalidDecl();
5423      return FunctionTemplate;
5424    }
5425  }
5426
5427  MarkUnusedFileScopedDecl(NewFD);
5428
5429  if (getLangOptions().CUDA)
5430    if (IdentifierInfo *II = NewFD->getIdentifier())
5431      if (!NewFD->isInvalidDecl() &&
5432          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5433        if (II->isStr("cudaConfigureCall")) {
5434          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5435            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5436
5437          Context.setcudaConfigureCallDecl(NewFD);
5438        }
5439      }
5440
5441  // Here we have an function template explicit specialization at class scope.
5442  // The actually specialization will be postponed to template instatiation
5443  // time via the ClassScopeFunctionSpecializationDecl node.
5444  if (isDependentClassScopeExplicitSpecialization) {
5445    ClassScopeFunctionSpecializationDecl *NewSpec =
5446                         ClassScopeFunctionSpecializationDecl::Create(
5447                                Context, CurContext,  SourceLocation(),
5448                                cast<CXXMethodDecl>(NewFD));
5449    CurContext->addDecl(NewSpec);
5450    AddToScope = false;
5451  }
5452
5453  return NewFD;
5454}
5455
5456/// \brief Perform semantic checking of a new function declaration.
5457///
5458/// Performs semantic analysis of the new function declaration
5459/// NewFD. This routine performs all semantic checking that does not
5460/// require the actual declarator involved in the declaration, and is
5461/// used both for the declaration of functions as they are parsed
5462/// (called via ActOnDeclarator) and for the declaration of functions
5463/// that have been instantiated via C++ template instantiation (called
5464/// via InstantiateDecl).
5465///
5466/// \param IsExplicitSpecialiation whether this new function declaration is
5467/// an explicit specialization of the previous declaration.
5468///
5469/// This sets NewFD->isInvalidDecl() to true if there was an error.
5470///
5471/// Returns true if the function declaration is a redeclaration.
5472bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5473                                    LookupResult &Previous,
5474                                    bool IsExplicitSpecialization) {
5475  assert(!NewFD->getResultType()->isVariablyModifiedType()
5476         && "Variably modified return types are not handled here");
5477
5478  // Check for a previous declaration of this name.
5479  if (Previous.empty() && NewFD->isExternC()) {
5480    // Since we did not find anything by this name and we're declaring
5481    // an extern "C" function, look for a non-visible extern "C"
5482    // declaration with the same name.
5483    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5484      = findLocallyScopedExternalDecl(NewFD->getDeclName());
5485    if (Pos != LocallyScopedExternalDecls.end())
5486      Previous.addDecl(Pos->second);
5487  }
5488
5489  bool Redeclaration = false;
5490
5491  // Merge or overload the declaration with an existing declaration of
5492  // the same name, if appropriate.
5493  if (!Previous.empty()) {
5494    // Determine whether NewFD is an overload of PrevDecl or
5495    // a declaration that requires merging. If it's an overload,
5496    // there's no more work to do here; we'll just add the new
5497    // function to the scope.
5498
5499    NamedDecl *OldDecl = 0;
5500    if (!AllowOverloadingOfFunction(Previous, Context)) {
5501      Redeclaration = true;
5502      OldDecl = Previous.getFoundDecl();
5503    } else {
5504      switch (CheckOverload(S, NewFD, Previous, OldDecl,
5505                            /*NewIsUsingDecl*/ false)) {
5506      case Ovl_Match:
5507        Redeclaration = true;
5508        break;
5509
5510      case Ovl_NonFunction:
5511        Redeclaration = true;
5512        break;
5513
5514      case Ovl_Overload:
5515        Redeclaration = false;
5516        break;
5517      }
5518
5519      if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5520        // If a function name is overloadable in C, then every function
5521        // with that name must be marked "overloadable".
5522        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5523          << Redeclaration << NewFD;
5524        NamedDecl *OverloadedDecl = 0;
5525        if (Redeclaration)
5526          OverloadedDecl = OldDecl;
5527        else if (!Previous.empty())
5528          OverloadedDecl = Previous.getRepresentativeDecl();
5529        if (OverloadedDecl)
5530          Diag(OverloadedDecl->getLocation(),
5531               diag::note_attribute_overloadable_prev_overload);
5532        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5533                                                        Context));
5534      }
5535    }
5536
5537    if (Redeclaration) {
5538      // NewFD and OldDecl represent declarations that need to be
5539      // merged.
5540      if (MergeFunctionDecl(NewFD, OldDecl)) {
5541        NewFD->setInvalidDecl();
5542        return Redeclaration;
5543      }
5544
5545      Previous.clear();
5546      Previous.addDecl(OldDecl);
5547
5548      if (FunctionTemplateDecl *OldTemplateDecl
5549                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5550        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5551        FunctionTemplateDecl *NewTemplateDecl
5552          = NewFD->getDescribedFunctionTemplate();
5553        assert(NewTemplateDecl && "Template/non-template mismatch");
5554        if (CXXMethodDecl *Method
5555              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5556          Method->setAccess(OldTemplateDecl->getAccess());
5557          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5558        }
5559
5560        // If this is an explicit specialization of a member that is a function
5561        // template, mark it as a member specialization.
5562        if (IsExplicitSpecialization &&
5563            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5564          NewTemplateDecl->setMemberSpecialization();
5565          assert(OldTemplateDecl->isMemberSpecialization());
5566        }
5567
5568        if (OldTemplateDecl->isModulePrivate())
5569          NewTemplateDecl->setModulePrivate();
5570
5571      } else {
5572        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5573          NewFD->setAccess(OldDecl->getAccess());
5574        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5575      }
5576    }
5577  }
5578
5579  // Semantic checking for this function declaration (in isolation).
5580  if (getLangOptions().CPlusPlus) {
5581    // C++-specific checks.
5582    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5583      CheckConstructor(Constructor);
5584    } else if (CXXDestructorDecl *Destructor =
5585                dyn_cast<CXXDestructorDecl>(NewFD)) {
5586      CXXRecordDecl *Record = Destructor->getParent();
5587      QualType ClassType = Context.getTypeDeclType(Record);
5588
5589      // FIXME: Shouldn't we be able to perform this check even when the class
5590      // type is dependent? Both gcc and edg can handle that.
5591      if (!ClassType->isDependentType()) {
5592        DeclarationName Name
5593          = Context.DeclarationNames.getCXXDestructorName(
5594                                        Context.getCanonicalType(ClassType));
5595        if (NewFD->getDeclName() != Name) {
5596          Diag(NewFD->getLocation(), diag::err_destructor_name);
5597          NewFD->setInvalidDecl();
5598          return Redeclaration;
5599        }
5600      }
5601    } else if (CXXConversionDecl *Conversion
5602               = dyn_cast<CXXConversionDecl>(NewFD)) {
5603      ActOnConversionDeclarator(Conversion);
5604    }
5605
5606    // Find any virtual functions that this function overrides.
5607    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5608      if (!Method->isFunctionTemplateSpecialization() &&
5609          !Method->getDescribedFunctionTemplate()) {
5610        if (AddOverriddenMethods(Method->getParent(), Method)) {
5611          // If the function was marked as "static", we have a problem.
5612          if (NewFD->getStorageClass() == SC_Static) {
5613            Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5614              << NewFD->getDeclName();
5615            for (CXXMethodDecl::method_iterator
5616                      Overridden = Method->begin_overridden_methods(),
5617                   OverriddenEnd = Method->end_overridden_methods();
5618                 Overridden != OverriddenEnd;
5619                 ++Overridden) {
5620              Diag((*Overridden)->getLocation(),
5621                   diag::note_overridden_virtual_function);
5622            }
5623          }
5624        }
5625      }
5626    }
5627
5628    // Extra checking for C++ overloaded operators (C++ [over.oper]).
5629    if (NewFD->isOverloadedOperator() &&
5630        CheckOverloadedOperatorDeclaration(NewFD)) {
5631      NewFD->setInvalidDecl();
5632      return Redeclaration;
5633    }
5634
5635    // Extra checking for C++0x literal operators (C++0x [over.literal]).
5636    if (NewFD->getLiteralIdentifier() &&
5637        CheckLiteralOperatorDeclaration(NewFD)) {
5638      NewFD->setInvalidDecl();
5639      return Redeclaration;
5640    }
5641
5642    // In C++, check default arguments now that we have merged decls. Unless
5643    // the lexical context is the class, because in this case this is done
5644    // during delayed parsing anyway.
5645    if (!CurContext->isRecord())
5646      CheckCXXDefaultArguments(NewFD);
5647
5648    // If this function declares a builtin function, check the type of this
5649    // declaration against the expected type for the builtin.
5650    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5651      ASTContext::GetBuiltinTypeError Error;
5652      QualType T = Context.GetBuiltinType(BuiltinID, Error);
5653      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5654        // The type of this function differs from the type of the builtin,
5655        // so forget about the builtin entirely.
5656        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5657      }
5658    }
5659  }
5660  return Redeclaration;
5661}
5662
5663void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5664  // C++ [basic.start.main]p3:  A program that declares main to be inline
5665  //   or static is ill-formed.
5666  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
5667  //   shall not appear in a declaration of main.
5668  // static main is not an error under C99, but we should warn about it.
5669  if (FD->getStorageClass() == SC_Static)
5670    Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus
5671         ? diag::err_static_main : diag::warn_static_main)
5672      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5673  if (FD->isInlineSpecified())
5674    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5675      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5676
5677  QualType T = FD->getType();
5678  assert(T->isFunctionType() && "function decl is not of function type");
5679  const FunctionType* FT = T->getAs<FunctionType>();
5680
5681  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5682    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5683    FD->setInvalidDecl(true);
5684  }
5685
5686  // Treat protoless main() as nullary.
5687  if (isa<FunctionNoProtoType>(FT)) return;
5688
5689  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5690  unsigned nparams = FTP->getNumArgs();
5691  assert(FD->getNumParams() == nparams);
5692
5693  bool HasExtraParameters = (nparams > 3);
5694
5695  // Darwin passes an undocumented fourth argument of type char**.  If
5696  // other platforms start sprouting these, the logic below will start
5697  // getting shifty.
5698  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5699    HasExtraParameters = false;
5700
5701  if (HasExtraParameters) {
5702    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5703    FD->setInvalidDecl(true);
5704    nparams = 3;
5705  }
5706
5707  // FIXME: a lot of the following diagnostics would be improved
5708  // if we had some location information about types.
5709
5710  QualType CharPP =
5711    Context.getPointerType(Context.getPointerType(Context.CharTy));
5712  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5713
5714  for (unsigned i = 0; i < nparams; ++i) {
5715    QualType AT = FTP->getArgType(i);
5716
5717    bool mismatch = true;
5718
5719    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5720      mismatch = false;
5721    else if (Expected[i] == CharPP) {
5722      // As an extension, the following forms are okay:
5723      //   char const **
5724      //   char const * const *
5725      //   char * const *
5726
5727      QualifierCollector qs;
5728      const PointerType* PT;
5729      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5730          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5731          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5732        qs.removeConst();
5733        mismatch = !qs.empty();
5734      }
5735    }
5736
5737    if (mismatch) {
5738      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5739      // TODO: suggest replacing given type with expected type
5740      FD->setInvalidDecl(true);
5741    }
5742  }
5743
5744  if (nparams == 1 && !FD->isInvalidDecl()) {
5745    Diag(FD->getLocation(), diag::warn_main_one_arg);
5746  }
5747
5748  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5749    Diag(FD->getLocation(), diag::err_main_template_decl);
5750    FD->setInvalidDecl();
5751  }
5752}
5753
5754bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
5755  // FIXME: Need strict checking.  In C89, we need to check for
5756  // any assignment, increment, decrement, function-calls, or
5757  // commas outside of a sizeof.  In C99, it's the same list,
5758  // except that the aforementioned are allowed in unevaluated
5759  // expressions.  Everything else falls under the
5760  // "may accept other forms of constant expressions" exception.
5761  // (We never end up here for C++, so the constant expression
5762  // rules there don't matter.)
5763  if (Init->isConstantInitializer(Context, false))
5764    return false;
5765  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5766    << Init->getSourceRange();
5767  return true;
5768}
5769
5770namespace {
5771  // Visits an initialization expression to see if OrigDecl is evaluated in
5772  // its own initialization and throws a warning if it does.
5773  class SelfReferenceChecker
5774      : public EvaluatedExprVisitor<SelfReferenceChecker> {
5775    Sema &S;
5776    Decl *OrigDecl;
5777    bool isRecordType;
5778    bool isPODType;
5779
5780  public:
5781    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5782
5783    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5784                                                    S(S), OrigDecl(OrigDecl) {
5785      isPODType = false;
5786      isRecordType = false;
5787      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
5788        isPODType = VD->getType().isPODType(S.Context);
5789        isRecordType = VD->getType()->isRecordType();
5790      }
5791    }
5792
5793    void VisitExpr(Expr *E) {
5794      if (isa<ObjCMessageExpr>(*E)) return;
5795      if (isRecordType) {
5796        Expr *expr = E;
5797        if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5798          ValueDecl *VD = ME->getMemberDecl();
5799          if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
5800          expr = ME->getBase();
5801        }
5802        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
5803          HandleDeclRefExpr(DRE);
5804          return;
5805        }
5806      }
5807      Inherited::VisitExpr(E);
5808    }
5809
5810    void VisitMemberExpr(MemberExpr *E) {
5811      if (E->getType()->canDecayToPointerType()) return;
5812      if (isa<FieldDecl>(E->getMemberDecl()))
5813        if (DeclRefExpr *DRE
5814              = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
5815          HandleDeclRefExpr(DRE);
5816          return;
5817        }
5818      Inherited::VisitMemberExpr(E);
5819    }
5820
5821    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
5822      if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
5823          (isRecordType && E->getCastKind() == CK_NoOp)) {
5824        Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5825        if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
5826          SubExpr = ME->getBase()->IgnoreParenImpCasts();
5827        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
5828          HandleDeclRefExpr(DRE);
5829          return;
5830        }
5831      }
5832      Inherited::VisitImplicitCastExpr(E);
5833    }
5834
5835    void VisitUnaryOperator(UnaryOperator *E) {
5836      // For POD record types, addresses of its own members are well-defined.
5837      if (isRecordType && isPODType) return;
5838      Inherited::VisitUnaryOperator(E);
5839    }
5840
5841    void HandleDeclRefExpr(DeclRefExpr *DRE) {
5842      Decl* ReferenceDecl = DRE->getDecl();
5843      if (OrigDecl != ReferenceDecl) return;
5844      LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5845                          Sema::NotForRedeclaration);
5846      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
5847                            S.PDiag(diag::warn_uninit_self_reference_in_init)
5848                              << Result.getLookupName()
5849                              << OrigDecl->getLocation()
5850                              << DRE->getSourceRange());
5851    }
5852  };
5853}
5854
5855/// CheckSelfReference - Warns if OrigDecl is used in expression E.
5856void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
5857  SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
5858}
5859
5860/// AddInitializerToDecl - Adds the initializer Init to the
5861/// declaration dcl. If DirectInit is true, this is C++ direct
5862/// initialization rather than copy initialization.
5863void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5864                                bool DirectInit, bool TypeMayContainAuto) {
5865  // If there is no declaration, there was an error parsing it.  Just ignore
5866  // the initializer.
5867  if (RealDecl == 0 || RealDecl->isInvalidDecl())
5868    return;
5869
5870  // Check for self-references within variable initializers.
5871  if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5872    // Variables declared within a function/method body are handled
5873    // by a dataflow analysis.
5874    if (!vd->hasLocalStorage() && !vd->isStaticLocal())
5875      CheckSelfReference(RealDecl, Init);
5876  }
5877  else {
5878    CheckSelfReference(RealDecl, Init);
5879  }
5880
5881  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5882    // With declarators parsed the way they are, the parser cannot
5883    // distinguish between a normal initializer and a pure-specifier.
5884    // Thus this grotesque test.
5885    IntegerLiteral *IL;
5886    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
5887        Context.getCanonicalType(IL->getType()) == Context.IntTy)
5888      CheckPureMethod(Method, Init->getSourceRange());
5889    else {
5890      Diag(Method->getLocation(), diag::err_member_function_initialization)
5891        << Method->getDeclName() << Init->getSourceRange();
5892      Method->setInvalidDecl();
5893    }
5894    return;
5895  }
5896
5897  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5898  if (!VDecl) {
5899    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5900    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5901    RealDecl->setInvalidDecl();
5902    return;
5903  }
5904
5905  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5906  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
5907    TypeSourceInfo *DeducedType = 0;
5908    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
5909      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5910        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5911        << Init->getSourceRange();
5912    if (!DeducedType) {
5913      RealDecl->setInvalidDecl();
5914      return;
5915    }
5916    VDecl->setTypeSourceInfo(DeducedType);
5917    VDecl->setType(DeducedType->getType());
5918
5919    // In ARC, infer lifetime.
5920    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5921      VDecl->setInvalidDecl();
5922
5923    // If this is a redeclaration, check that the type we just deduced matches
5924    // the previously declared type.
5925    if (VarDecl *Old = VDecl->getPreviousDeclaration())
5926      MergeVarDeclTypes(VDecl, Old);
5927  }
5928
5929
5930  // A definition must end up with a complete type, which means it must be
5931  // complete with the restriction that an array type might be completed by the
5932  // initializer; note that later code assumes this restriction.
5933  QualType BaseDeclType = VDecl->getType();
5934  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5935    BaseDeclType = Array->getElementType();
5936  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
5937                          diag::err_typecheck_decl_incomplete_type)) {
5938    RealDecl->setInvalidDecl();
5939    return;
5940  }
5941
5942  // The variable can not have an abstract class type.
5943  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5944                             diag::err_abstract_type_in_decl,
5945                             AbstractVariableType))
5946    VDecl->setInvalidDecl();
5947
5948  const VarDecl *Def;
5949  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
5950    Diag(VDecl->getLocation(), diag::err_redefinition)
5951      << VDecl->getDeclName();
5952    Diag(Def->getLocation(), diag::note_previous_definition);
5953    VDecl->setInvalidDecl();
5954    return;
5955  }
5956
5957  const VarDecl* PrevInit = 0;
5958  if (getLangOptions().CPlusPlus) {
5959    // C++ [class.static.data]p4
5960    //   If a static data member is of const integral or const
5961    //   enumeration type, its declaration in the class definition can
5962    //   specify a constant-initializer which shall be an integral
5963    //   constant expression (5.19). In that case, the member can appear
5964    //   in integral constant expressions. The member shall still be
5965    //   defined in a namespace scope if it is used in the program and the
5966    //   namespace scope definition shall not contain an initializer.
5967    //
5968    // We already performed a redefinition check above, but for static
5969    // data members we also need to check whether there was an in-class
5970    // declaration with an initializer.
5971    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5972      Diag(VDecl->getLocation(), diag::err_redefinition)
5973        << VDecl->getDeclName();
5974      Diag(PrevInit->getLocation(), diag::note_previous_definition);
5975      return;
5976    }
5977
5978    if (VDecl->hasLocalStorage())
5979      getCurFunction()->setHasBranchProtectedScope();
5980
5981    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
5982      VDecl->setInvalidDecl();
5983      return;
5984    }
5985  }
5986
5987  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
5988  // a kernel function cannot be initialized."
5989  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
5990    Diag(VDecl->getLocation(), diag::err_local_cant_init);
5991    VDecl->setInvalidDecl();
5992    return;
5993  }
5994
5995  // Capture the variable that is being initialized and the style of
5996  // initialization.
5997  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5998
5999  // FIXME: Poor source location information.
6000  InitializationKind Kind
6001    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
6002                                                   Init->getLocStart(),
6003                                                   Init->getLocEnd())
6004                : InitializationKind::CreateCopy(VDecl->getLocation(),
6005                                                 Init->getLocStart());
6006
6007  // Get the decls type and save a reference for later, since
6008  // CheckInitializerTypes may change it.
6009  QualType DclT = VDecl->getType(), SavT = DclT;
6010  if (VDecl->isLocalVarDecl()) {
6011    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
6012      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6013      VDecl->setInvalidDecl();
6014    } else if (!VDecl->isInvalidDecl()) {
6015      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
6016      ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6017                                                MultiExprArg(*this, &Init, 1),
6018                                                &DclT);
6019      if (Result.isInvalid()) {
6020        VDecl->setInvalidDecl();
6021        return;
6022      }
6023
6024      Init = Result.takeAs<Expr>();
6025
6026      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
6027      // Don't check invalid declarations to avoid emitting useless diagnostics.
6028      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
6029        if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
6030          CheckForConstantInitializer(Init, DclT);
6031      }
6032    }
6033  } else if (VDecl->isStaticDataMember() &&
6034             VDecl->getLexicalDeclContext()->isRecord()) {
6035    // This is an in-class initialization for a static data member, e.g.,
6036    //
6037    // struct S {
6038    //   static const int value = 17;
6039    // };
6040
6041    // Try to perform the initialization regardless.
6042    if (!VDecl->isInvalidDecl()) {
6043      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
6044      ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6045                                          MultiExprArg(*this, &Init, 1),
6046                                          &DclT);
6047      if (Result.isInvalid()) {
6048        VDecl->setInvalidDecl();
6049        return;
6050      }
6051
6052      Init = Result.takeAs<Expr>();
6053    }
6054
6055    // C++ [class.mem]p4:
6056    //   A member-declarator can contain a constant-initializer only
6057    //   if it declares a static member (9.4) of const integral or
6058    //   const enumeration type, see 9.4.2.
6059    //
6060    // C++0x [class.static.data]p3:
6061    //   If a non-volatile const static data member is of integral or
6062    //   enumeration type, its declaration in the class definition can
6063    //   specify a brace-or-equal-initializer in which every initalizer-clause
6064    //   that is an assignment-expression is a constant expression. A static
6065    //   data member of literal type can be declared in the class definition
6066    //   with the constexpr specifier; if so, its declaration shall specify a
6067    //   brace-or-equal-initializer in which every initializer-clause that is
6068    //   an assignment-expression is a constant expression.
6069    QualType T = VDecl->getType();
6070
6071    // Do nothing on dependent types.
6072    if (T->isDependentType()) {
6073
6074    // Allow any 'static constexpr' members, whether or not they are of literal
6075    // type. We separately check that the initializer is a constant expression,
6076    // which implicitly requires the member to be of literal type.
6077    } else if (VDecl->isConstexpr()) {
6078
6079    // Require constness.
6080    } else if (!T.isConstQualified()) {
6081      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6082        << Init->getSourceRange();
6083      VDecl->setInvalidDecl();
6084
6085    // We allow integer constant expressions in all cases.
6086    } else if (T->isIntegralOrEnumerationType()) {
6087      // Check whether the expression is a constant expression.
6088      SourceLocation Loc;
6089      if (getLangOptions().CPlusPlus0x && T.isVolatileQualified())
6090        // In C++0x, a non-constexpr const static data member with an
6091        // in-class initializer cannot be volatile.
6092        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6093      else if (Init->isValueDependent())
6094        ; // Nothing to check.
6095      else if (Init->isIntegerConstantExpr(Context, &Loc))
6096        ; // Ok, it's an ICE!
6097      else if (Init->isEvaluatable(Context)) {
6098        // If we can constant fold the initializer through heroics, accept it,
6099        // but report this as a use of an extension for -pedantic.
6100        Diag(Loc, diag::ext_in_class_initializer_non_constant)
6101          << Init->getSourceRange();
6102      } else {
6103        // Otherwise, this is some crazy unknown case.  Report the issue at the
6104        // location provided by the isIntegerConstantExpr failed check.
6105        Diag(Loc, diag::err_in_class_initializer_non_constant)
6106          << Init->getSourceRange();
6107        VDecl->setInvalidDecl();
6108      }
6109
6110    // We allow floating-point constants as an extension.
6111    } else if (T->isFloatingType()) { // also permits complex, which is ok
6112      Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6113        << T << Init->getSourceRange();
6114      if (getLangOptions().CPlusPlus0x)
6115        Diag(VDecl->getLocation(),
6116             diag::note_in_class_initializer_float_type_constexpr)
6117          << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6118
6119      if (!Init->isValueDependent() &&
6120          !Init->isConstantInitializer(Context, false)) {
6121        Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6122          << Init->getSourceRange();
6123        VDecl->setInvalidDecl();
6124      }
6125
6126    // Suggest adding 'constexpr' in C++0x for literal types.
6127    } else if (getLangOptions().CPlusPlus0x && T->isLiteralType()) {
6128      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6129        << T << Init->getSourceRange()
6130        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6131      VDecl->setConstexpr(true);
6132
6133    } else {
6134      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6135        << T << Init->getSourceRange();
6136      VDecl->setInvalidDecl();
6137    }
6138  } else if (VDecl->isFileVarDecl()) {
6139    if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6140        (!getLangOptions().CPlusPlus ||
6141         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6142      Diag(VDecl->getLocation(), diag::warn_extern_init);
6143    if (!VDecl->isInvalidDecl()) {
6144      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
6145      ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6146                                                MultiExprArg(*this, &Init, 1),
6147                                                &DclT);
6148      if (Result.isInvalid()) {
6149        VDecl->setInvalidDecl();
6150        return;
6151      }
6152
6153      Init = Result.takeAs<Expr>();
6154    }
6155
6156    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
6157    // Don't check invalid declarations to avoid emitting useless diagnostics.
6158    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
6159      // C99 6.7.8p4. All file scoped initializers need to be constant.
6160      CheckForConstantInitializer(Init, DclT);
6161    }
6162  }
6163  // If the type changed, it means we had an incomplete type that was
6164  // completed by the initializer. For example:
6165  //   int ary[] = { 1, 3, 5 };
6166  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
6167  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
6168    VDecl->setType(DclT);
6169    Init->setType(DclT);
6170  }
6171
6172  // Check any implicit conversions within the expression.
6173  CheckImplicitConversions(Init, VDecl->getLocation());
6174
6175  if (!VDecl->isInvalidDecl())
6176    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6177
6178  if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
6179      !VDecl->getType()->isDependentType() &&
6180      !Init->isTypeDependent() && !Init->isValueDependent() &&
6181      !Init->isConstantInitializer(Context,
6182                                   VDecl->getType()->isReferenceType())) {
6183    // FIXME: Improve this diagnostic to explain why the initializer is not
6184    // a constant expression.
6185    Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
6186      << VDecl << Init->getSourceRange();
6187  }
6188
6189  Init = MaybeCreateExprWithCleanups(Init);
6190  // Attach the initializer to the decl.
6191  VDecl->setInit(Init);
6192
6193  CheckCompleteVariableDeclaration(VDecl);
6194}
6195
6196/// ActOnInitializerError - Given that there was an error parsing an
6197/// initializer for the given declaration, try to return to some form
6198/// of sanity.
6199void Sema::ActOnInitializerError(Decl *D) {
6200  // Our main concern here is re-establishing invariants like "a
6201  // variable's type is either dependent or complete".
6202  if (!D || D->isInvalidDecl()) return;
6203
6204  VarDecl *VD = dyn_cast<VarDecl>(D);
6205  if (!VD) return;
6206
6207  // Auto types are meaningless if we can't make sense of the initializer.
6208  if (ParsingInitForAutoVars.count(D)) {
6209    D->setInvalidDecl();
6210    return;
6211  }
6212
6213  QualType Ty = VD->getType();
6214  if (Ty->isDependentType()) return;
6215
6216  // Require a complete type.
6217  if (RequireCompleteType(VD->getLocation(),
6218                          Context.getBaseElementType(Ty),
6219                          diag::err_typecheck_decl_incomplete_type)) {
6220    VD->setInvalidDecl();
6221    return;
6222  }
6223
6224  // Require an abstract type.
6225  if (RequireNonAbstractType(VD->getLocation(), Ty,
6226                             diag::err_abstract_type_in_decl,
6227                             AbstractVariableType)) {
6228    VD->setInvalidDecl();
6229    return;
6230  }
6231
6232  // Don't bother complaining about constructors or destructors,
6233  // though.
6234}
6235
6236void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6237                                  bool TypeMayContainAuto) {
6238  // If there is no declaration, there was an error parsing it. Just ignore it.
6239  if (RealDecl == 0)
6240    return;
6241
6242  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6243    QualType Type = Var->getType();
6244
6245    // C++0x [dcl.spec.auto]p3
6246    if (TypeMayContainAuto && Type->getContainedAutoType()) {
6247      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6248        << Var->getDeclName() << Type;
6249      Var->setInvalidDecl();
6250      return;
6251    }
6252
6253    // C++0x [dcl.constexpr]p9: An object or reference declared constexpr must
6254    // have an initializer.
6255    // C++0x [class.static.data]p3: A static data member can be declared with
6256    // the constexpr specifier; if so, its declaration shall specify
6257    // a brace-or-equal-initializer.
6258    //
6259    // A static data member's definition may inherit an initializer from an
6260    // in-class declaration.
6261    if (Var->isConstexpr() && !Var->getAnyInitializer()) {
6262      Diag(Var->getLocation(), diag::err_constexpr_var_requires_init)
6263        << Var->getDeclName();
6264      Var->setInvalidDecl();
6265      return;
6266    }
6267
6268    switch (Var->isThisDeclarationADefinition()) {
6269    case VarDecl::Definition:
6270      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6271        break;
6272
6273      // We have an out-of-line definition of a static data member
6274      // that has an in-class initializer, so we type-check this like
6275      // a declaration.
6276      //
6277      // Fall through
6278
6279    case VarDecl::DeclarationOnly:
6280      // It's only a declaration.
6281
6282      // Block scope. C99 6.7p7: If an identifier for an object is
6283      // declared with no linkage (C99 6.2.2p6), the type for the
6284      // object shall be complete.
6285      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
6286          !Var->getLinkage() && !Var->isInvalidDecl() &&
6287          RequireCompleteType(Var->getLocation(), Type,
6288                              diag::err_typecheck_decl_incomplete_type))
6289        Var->setInvalidDecl();
6290
6291      // Make sure that the type is not abstract.
6292      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6293          RequireNonAbstractType(Var->getLocation(), Type,
6294                                 diag::err_abstract_type_in_decl,
6295                                 AbstractVariableType))
6296        Var->setInvalidDecl();
6297      return;
6298
6299    case VarDecl::TentativeDefinition:
6300      // File scope. C99 6.9.2p2: A declaration of an identifier for an
6301      // object that has file scope without an initializer, and without a
6302      // storage-class specifier or with the storage-class specifier "static",
6303      // constitutes a tentative definition. Note: A tentative definition with
6304      // external linkage is valid (C99 6.2.2p5).
6305      if (!Var->isInvalidDecl()) {
6306        if (const IncompleteArrayType *ArrayT
6307                                    = Context.getAsIncompleteArrayType(Type)) {
6308          if (RequireCompleteType(Var->getLocation(),
6309                                  ArrayT->getElementType(),
6310                                  diag::err_illegal_decl_array_incomplete_type))
6311            Var->setInvalidDecl();
6312        } else if (Var->getStorageClass() == SC_Static) {
6313          // C99 6.9.2p3: If the declaration of an identifier for an object is
6314          // a tentative definition and has internal linkage (C99 6.2.2p3), the
6315          // declared type shall not be an incomplete type.
6316          // NOTE: code such as the following
6317          //     static struct s;
6318          //     struct s { int a; };
6319          // is accepted by gcc. Hence here we issue a warning instead of
6320          // an error and we do not invalidate the static declaration.
6321          // NOTE: to avoid multiple warnings, only check the first declaration.
6322          if (Var->getPreviousDeclaration() == 0)
6323            RequireCompleteType(Var->getLocation(), Type,
6324                                diag::ext_typecheck_decl_incomplete_type);
6325        }
6326      }
6327
6328      // Record the tentative definition; we're done.
6329      if (!Var->isInvalidDecl())
6330        TentativeDefinitions.push_back(Var);
6331      return;
6332    }
6333
6334    // Provide a specific diagnostic for uninitialized variable
6335    // definitions with incomplete array type.
6336    if (Type->isIncompleteArrayType()) {
6337      Diag(Var->getLocation(),
6338           diag::err_typecheck_incomplete_array_needs_initializer);
6339      Var->setInvalidDecl();
6340      return;
6341    }
6342
6343    // Provide a specific diagnostic for uninitialized variable
6344    // definitions with reference type.
6345    if (Type->isReferenceType()) {
6346      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6347        << Var->getDeclName()
6348        << SourceRange(Var->getLocation(), Var->getLocation());
6349      Var->setInvalidDecl();
6350      return;
6351    }
6352
6353    // Do not attempt to type-check the default initializer for a
6354    // variable with dependent type.
6355    if (Type->isDependentType())
6356      return;
6357
6358    if (Var->isInvalidDecl())
6359      return;
6360
6361    if (RequireCompleteType(Var->getLocation(),
6362                            Context.getBaseElementType(Type),
6363                            diag::err_typecheck_decl_incomplete_type)) {
6364      Var->setInvalidDecl();
6365      return;
6366    }
6367
6368    // The variable can not have an abstract class type.
6369    if (RequireNonAbstractType(Var->getLocation(), Type,
6370                               diag::err_abstract_type_in_decl,
6371                               AbstractVariableType)) {
6372      Var->setInvalidDecl();
6373      return;
6374    }
6375
6376    // Check for jumps past the implicit initializer.  C++0x
6377    // clarifies that this applies to a "variable with automatic
6378    // storage duration", not a "local variable".
6379    // C++11 [stmt.dcl]p3
6380    //   A program that jumps from a point where a variable with automatic
6381    //   storage duration is not in scope to a point where it is in scope is
6382    //   ill-formed unless the variable has scalar type, class type with a
6383    //   trivial default constructor and a trivial destructor, a cv-qualified
6384    //   version of one of these types, or an array of one of the preceding
6385    //   types and is declared without an initializer.
6386    if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
6387      if (const RecordType *Record
6388            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6389        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6390        // Mark the function for further checking even if the looser rules of
6391        // C++11 do not require such checks, so that we can diagnose
6392        // incompatibilities with C++98.
6393        if (!CXXRecord->isPOD())
6394          getCurFunction()->setHasBranchProtectedScope();
6395      }
6396    }
6397
6398    // C++03 [dcl.init]p9:
6399    //   If no initializer is specified for an object, and the
6400    //   object is of (possibly cv-qualified) non-POD class type (or
6401    //   array thereof), the object shall be default-initialized; if
6402    //   the object is of const-qualified type, the underlying class
6403    //   type shall have a user-declared default
6404    //   constructor. Otherwise, if no initializer is specified for
6405    //   a non- static object, the object and its subobjects, if
6406    //   any, have an indeterminate initial value); if the object
6407    //   or any of its subobjects are of const-qualified type, the
6408    //   program is ill-formed.
6409    // C++0x [dcl.init]p11:
6410    //   If no initializer is specified for an object, the object is
6411    //   default-initialized; [...].
6412    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6413    InitializationKind Kind
6414      = InitializationKind::CreateDefault(Var->getLocation());
6415
6416    InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6417    ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6418                                      MultiExprArg(*this, 0, 0));
6419    if (Init.isInvalid())
6420      Var->setInvalidDecl();
6421    else if (Init.get())
6422      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6423
6424    CheckCompleteVariableDeclaration(Var);
6425  }
6426}
6427
6428void Sema::ActOnCXXForRangeDecl(Decl *D) {
6429  VarDecl *VD = dyn_cast<VarDecl>(D);
6430  if (!VD) {
6431    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6432    D->setInvalidDecl();
6433    return;
6434  }
6435
6436  VD->setCXXForRangeDecl(true);
6437
6438  // for-range-declaration cannot be given a storage class specifier.
6439  int Error = -1;
6440  switch (VD->getStorageClassAsWritten()) {
6441  case SC_None:
6442    break;
6443  case SC_Extern:
6444    Error = 0;
6445    break;
6446  case SC_Static:
6447    Error = 1;
6448    break;
6449  case SC_PrivateExtern:
6450    Error = 2;
6451    break;
6452  case SC_Auto:
6453    Error = 3;
6454    break;
6455  case SC_Register:
6456    Error = 4;
6457    break;
6458  case SC_OpenCLWorkGroupLocal:
6459    llvm_unreachable("Unexpected storage class");
6460  }
6461  if (VD->isConstexpr())
6462    Error = 5;
6463  if (Error != -1) {
6464    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6465      << VD->getDeclName() << Error;
6466    D->setInvalidDecl();
6467  }
6468}
6469
6470void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6471  if (var->isInvalidDecl()) return;
6472
6473  // In ARC, don't allow jumps past the implicit initialization of a
6474  // local retaining variable.
6475  if (getLangOptions().ObjCAutoRefCount &&
6476      var->hasLocalStorage()) {
6477    switch (var->getType().getObjCLifetime()) {
6478    case Qualifiers::OCL_None:
6479    case Qualifiers::OCL_ExplicitNone:
6480    case Qualifiers::OCL_Autoreleasing:
6481      break;
6482
6483    case Qualifiers::OCL_Weak:
6484    case Qualifiers::OCL_Strong:
6485      getCurFunction()->setHasBranchProtectedScope();
6486      break;
6487    }
6488  }
6489
6490  // All the following checks are C++ only.
6491  if (!getLangOptions().CPlusPlus) return;
6492
6493  QualType baseType = Context.getBaseElementType(var->getType());
6494  if (baseType->isDependentType()) return;
6495
6496  // __block variables might require us to capture a copy-initializer.
6497  if (var->hasAttr<BlocksAttr>()) {
6498    // It's currently invalid to ever have a __block variable with an
6499    // array type; should we diagnose that here?
6500
6501    // Regardless, we don't want to ignore array nesting when
6502    // constructing this copy.
6503    QualType type = var->getType();
6504
6505    if (type->isStructureOrClassType()) {
6506      SourceLocation poi = var->getLocation();
6507      Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
6508      ExprResult result =
6509        PerformCopyInitialization(
6510                        InitializedEntity::InitializeBlock(poi, type, false),
6511                                  poi, Owned(varRef));
6512      if (!result.isInvalid()) {
6513        result = MaybeCreateExprWithCleanups(result);
6514        Expr *init = result.takeAs<Expr>();
6515        Context.setBlockVarCopyInits(var, init);
6516      }
6517    }
6518  }
6519
6520  // Check for global constructors.
6521  if (!var->getDeclContext()->isDependentContext() &&
6522      var->hasGlobalStorage() &&
6523      !var->isStaticLocal() &&
6524      var->getInit() &&
6525      !var->getInit()->isConstantInitializer(Context,
6526                                             baseType->isReferenceType()))
6527    Diag(var->getLocation(), diag::warn_global_constructor)
6528      << var->getInit()->getSourceRange();
6529
6530  // Require the destructor.
6531  if (const RecordType *recordType = baseType->getAs<RecordType>())
6532    FinalizeVarWithDestructor(var, recordType);
6533}
6534
6535/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6536/// any semantic actions necessary after any initializer has been attached.
6537void
6538Sema::FinalizeDeclaration(Decl *ThisDecl) {
6539  // Note that we are no longer parsing the initializer for this declaration.
6540  ParsingInitForAutoVars.erase(ThisDecl);
6541}
6542
6543Sema::DeclGroupPtrTy
6544Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6545                              Decl **Group, unsigned NumDecls) {
6546  SmallVector<Decl*, 8> Decls;
6547
6548  if (DS.isTypeSpecOwned())
6549    Decls.push_back(DS.getRepAsDecl());
6550
6551  for (unsigned i = 0; i != NumDecls; ++i)
6552    if (Decl *D = Group[i])
6553      Decls.push_back(D);
6554
6555  return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6556                              DS.getTypeSpecType() == DeclSpec::TST_auto);
6557}
6558
6559/// BuildDeclaratorGroup - convert a list of declarations into a declaration
6560/// group, performing any necessary semantic checking.
6561Sema::DeclGroupPtrTy
6562Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6563                           bool TypeMayContainAuto) {
6564  // C++0x [dcl.spec.auto]p7:
6565  //   If the type deduced for the template parameter U is not the same in each
6566  //   deduction, the program is ill-formed.
6567  // FIXME: When initializer-list support is added, a distinction is needed
6568  // between the deduced type U and the deduced type which 'auto' stands for.
6569  //   auto a = 0, b = { 1, 2, 3 };
6570  // is legal because the deduced type U is 'int' in both cases.
6571  if (TypeMayContainAuto && NumDecls > 1) {
6572    QualType Deduced;
6573    CanQualType DeducedCanon;
6574    VarDecl *DeducedDecl = 0;
6575    for (unsigned i = 0; i != NumDecls; ++i) {
6576      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6577        AutoType *AT = D->getType()->getContainedAutoType();
6578        // Don't reissue diagnostics when instantiating a template.
6579        if (AT && D->isInvalidDecl())
6580          break;
6581        if (AT && AT->isDeduced()) {
6582          QualType U = AT->getDeducedType();
6583          CanQualType UCanon = Context.getCanonicalType(U);
6584          if (Deduced.isNull()) {
6585            Deduced = U;
6586            DeducedCanon = UCanon;
6587            DeducedDecl = D;
6588          } else if (DeducedCanon != UCanon) {
6589            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6590                 diag::err_auto_different_deductions)
6591              << Deduced << DeducedDecl->getDeclName()
6592              << U << D->getDeclName()
6593              << DeducedDecl->getInit()->getSourceRange()
6594              << D->getInit()->getSourceRange();
6595            D->setInvalidDecl();
6596            break;
6597          }
6598        }
6599      }
6600    }
6601  }
6602
6603  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6604}
6605
6606
6607/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6608/// to introduce parameters into function prototype scope.
6609Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6610  const DeclSpec &DS = D.getDeclSpec();
6611
6612  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6613  // C++03 [dcl.stc]p2 also permits 'auto'.
6614  VarDecl::StorageClass StorageClass = SC_None;
6615  VarDecl::StorageClass StorageClassAsWritten = SC_None;
6616  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6617    StorageClass = SC_Register;
6618    StorageClassAsWritten = SC_Register;
6619  } else if (getLangOptions().CPlusPlus &&
6620             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6621    StorageClass = SC_Auto;
6622    StorageClassAsWritten = SC_Auto;
6623  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6624    Diag(DS.getStorageClassSpecLoc(),
6625         diag::err_invalid_storage_class_in_func_decl);
6626    D.getMutableDeclSpec().ClearStorageClassSpecs();
6627  }
6628
6629  if (D.getDeclSpec().isThreadSpecified())
6630    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6631  if (D.getDeclSpec().isConstexprSpecified())
6632    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6633      << 0;
6634
6635  DiagnoseFunctionSpecifiers(D);
6636
6637  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6638  QualType parmDeclType = TInfo->getType();
6639
6640  if (getLangOptions().CPlusPlus) {
6641    // Check that there are no default arguments inside the type of this
6642    // parameter.
6643    CheckExtraCXXDefaultArguments(D);
6644
6645    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6646    if (D.getCXXScopeSpec().isSet()) {
6647      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6648        << D.getCXXScopeSpec().getRange();
6649      D.getCXXScopeSpec().clear();
6650    }
6651  }
6652
6653  // Ensure we have a valid name
6654  IdentifierInfo *II = 0;
6655  if (D.hasName()) {
6656    II = D.getIdentifier();
6657    if (!II) {
6658      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6659        << GetNameForDeclarator(D).getName().getAsString();
6660      D.setInvalidType(true);
6661    }
6662  }
6663
6664  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6665  if (II) {
6666    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6667                   ForRedeclaration);
6668    LookupName(R, S);
6669    if (R.isSingleResult()) {
6670      NamedDecl *PrevDecl = R.getFoundDecl();
6671      if (PrevDecl->isTemplateParameter()) {
6672        // Maybe we will complain about the shadowed template parameter.
6673        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6674        // Just pretend that we didn't see the previous declaration.
6675        PrevDecl = 0;
6676      } else if (S->isDeclScope(PrevDecl)) {
6677        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6678        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6679
6680        // Recover by removing the name
6681        II = 0;
6682        D.SetIdentifier(0, D.getIdentifierLoc());
6683        D.setInvalidType(true);
6684      }
6685    }
6686  }
6687
6688  // Temporarily put parameter variables in the translation unit, not
6689  // the enclosing context.  This prevents them from accidentally
6690  // looking like class members in C++.
6691  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6692                                    D.getSourceRange().getBegin(),
6693                                    D.getIdentifierLoc(), II,
6694                                    parmDeclType, TInfo,
6695                                    StorageClass, StorageClassAsWritten);
6696
6697  if (D.isInvalidType())
6698    New->setInvalidDecl();
6699
6700  assert(S->isFunctionPrototypeScope());
6701  assert(S->getFunctionPrototypeDepth() >= 1);
6702  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6703                    S->getNextFunctionPrototypeIndex());
6704
6705  // Add the parameter declaration into this scope.
6706  S->AddDecl(New);
6707  if (II)
6708    IdResolver.AddDecl(New);
6709
6710  ProcessDeclAttributes(S, New, D);
6711
6712  if (D.getDeclSpec().isModulePrivateSpecified())
6713    Diag(New->getLocation(), diag::err_module_private_local)
6714      << 1 << New->getDeclName()
6715      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6716      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6717
6718  if (New->hasAttr<BlocksAttr>()) {
6719    Diag(New->getLocation(), diag::err_block_on_nonlocal);
6720  }
6721  return New;
6722}
6723
6724/// \brief Synthesizes a variable for a parameter arising from a
6725/// typedef.
6726ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6727                                              SourceLocation Loc,
6728                                              QualType T) {
6729  /* FIXME: setting StartLoc == Loc.
6730     Would it be worth to modify callers so as to provide proper source
6731     location for the unnamed parameters, embedding the parameter's type? */
6732  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
6733                                T, Context.getTrivialTypeSourceInfo(T, Loc),
6734                                           SC_None, SC_None, 0);
6735  Param->setImplicit();
6736  return Param;
6737}
6738
6739void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6740                                    ParmVarDecl * const *ParamEnd) {
6741  // Don't diagnose unused-parameter errors in template instantiations; we
6742  // will already have done so in the template itself.
6743  if (!ActiveTemplateInstantiations.empty())
6744    return;
6745
6746  for (; Param != ParamEnd; ++Param) {
6747    if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6748        !(*Param)->hasAttr<UnusedAttr>()) {
6749      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6750        << (*Param)->getDeclName();
6751    }
6752  }
6753}
6754
6755void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6756                                                  ParmVarDecl * const *ParamEnd,
6757                                                  QualType ReturnTy,
6758                                                  NamedDecl *D) {
6759  if (LangOpts.NumLargeByValueCopy == 0) // No check.
6760    return;
6761
6762  // Warn if the return value is pass-by-value and larger than the specified
6763  // threshold.
6764  if (ReturnTy.isPODType(Context)) {
6765    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
6766    if (Size > LangOpts.NumLargeByValueCopy)
6767      Diag(D->getLocation(), diag::warn_return_value_size)
6768          << D->getDeclName() << Size;
6769  }
6770
6771  // Warn if any parameter is pass-by-value and larger than the specified
6772  // threshold.
6773  for (; Param != ParamEnd; ++Param) {
6774    QualType T = (*Param)->getType();
6775    if (!T.isPODType(Context))
6776      continue;
6777    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
6778    if (Size > LangOpts.NumLargeByValueCopy)
6779      Diag((*Param)->getLocation(), diag::warn_parameter_size)
6780          << (*Param)->getDeclName() << Size;
6781  }
6782}
6783
6784ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6785                                  SourceLocation NameLoc, IdentifierInfo *Name,
6786                                  QualType T, TypeSourceInfo *TSInfo,
6787                                  VarDecl::StorageClass StorageClass,
6788                                  VarDecl::StorageClass StorageClassAsWritten) {
6789  // In ARC, infer a lifetime qualifier for appropriate parameter types.
6790  if (getLangOptions().ObjCAutoRefCount &&
6791      T.getObjCLifetime() == Qualifiers::OCL_None &&
6792      T->isObjCLifetimeType()) {
6793
6794    Qualifiers::ObjCLifetime lifetime;
6795
6796    // Special cases for arrays:
6797    //   - if it's const, use __unsafe_unretained
6798    //   - otherwise, it's an error
6799    if (T->isArrayType()) {
6800      if (!T.isConstQualified()) {
6801        DelayedDiagnostics.add(
6802            sema::DelayedDiagnostic::makeForbiddenType(
6803            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
6804      }
6805      lifetime = Qualifiers::OCL_ExplicitNone;
6806    } else {
6807      lifetime = T->getObjCARCImplicitLifetime();
6808    }
6809    T = Context.getLifetimeQualifiedType(T, lifetime);
6810  }
6811
6812  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
6813                                         Context.getAdjustedParameterType(T),
6814                                         TSInfo,
6815                                         StorageClass, StorageClassAsWritten,
6816                                         0);
6817
6818  // Parameters can not be abstract class types.
6819  // For record types, this is done by the AbstractClassUsageDiagnoser once
6820  // the class has been completely parsed.
6821  if (!CurContext->isRecord() &&
6822      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6823                             AbstractParamType))
6824    New->setInvalidDecl();
6825
6826  // Parameter declarators cannot be interface types. All ObjC objects are
6827  // passed by reference.
6828  if (T->isObjCObjectType()) {
6829    Diag(NameLoc,
6830         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
6831      << FixItHint::CreateInsertion(NameLoc, "*");
6832    T = Context.getObjCObjectPointerType(T);
6833    New->setType(T);
6834  }
6835
6836  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6837  // duration shall not be qualified by an address-space qualifier."
6838  // Since all parameters have automatic store duration, they can not have
6839  // an address space.
6840  if (T.getAddressSpace() != 0) {
6841    Diag(NameLoc, diag::err_arg_with_address_space);
6842    New->setInvalidDecl();
6843  }
6844
6845  return New;
6846}
6847
6848void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6849                                           SourceLocation LocAfterDecls) {
6850  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6851
6852  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6853  // for a K&R function.
6854  if (!FTI.hasPrototype) {
6855    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6856      --i;
6857      if (FTI.ArgInfo[i].Param == 0) {
6858        llvm::SmallString<256> Code;
6859        llvm::raw_svector_ostream(Code) << "  int "
6860                                        << FTI.ArgInfo[i].Ident->getName()
6861                                        << ";\n";
6862        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
6863          << FTI.ArgInfo[i].Ident
6864          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
6865
6866        // Implicitly declare the argument as type 'int' for lack of a better
6867        // type.
6868        AttributeFactory attrs;
6869        DeclSpec DS(attrs);
6870        const char* PrevSpec; // unused
6871        unsigned DiagID; // unused
6872        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
6873                           PrevSpec, DiagID);
6874        Declarator ParamD(DS, Declarator::KNRTypeListContext);
6875        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
6876        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
6877      }
6878    }
6879  }
6880}
6881
6882Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6883                                         Declarator &D) {
6884  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
6885  assert(D.isFunctionDeclarator() && "Not a function declarator!");
6886  Scope *ParentScope = FnBodyScope->getParent();
6887
6888  D.setFunctionDefinition(true);
6889  Decl *DP = HandleDeclarator(ParentScope, D,
6890                              MultiTemplateParamsArg(*this));
6891  return ActOnStartOfFunctionDef(FnBodyScope, DP);
6892}
6893
6894static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6895  // Don't warn about invalid declarations.
6896  if (FD->isInvalidDecl())
6897    return false;
6898
6899  // Or declarations that aren't global.
6900  if (!FD->isGlobal())
6901    return false;
6902
6903  // Don't warn about C++ member functions.
6904  if (isa<CXXMethodDecl>(FD))
6905    return false;
6906
6907  // Don't warn about 'main'.
6908  if (FD->isMain())
6909    return false;
6910
6911  // Don't warn about inline functions.
6912  if (FD->isInlined())
6913    return false;
6914
6915  // Don't warn about function templates.
6916  if (FD->getDescribedFunctionTemplate())
6917    return false;
6918
6919  // Don't warn about function template specializations.
6920  if (FD->isFunctionTemplateSpecialization())
6921    return false;
6922
6923  bool MissingPrototype = true;
6924  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6925       Prev; Prev = Prev->getPreviousDeclaration()) {
6926    // Ignore any declarations that occur in function or method
6927    // scope, because they aren't visible from the header.
6928    if (Prev->getDeclContext()->isFunctionOrMethod())
6929      continue;
6930
6931    MissingPrototype = !Prev->getType()->isFunctionProtoType();
6932    break;
6933  }
6934
6935  return MissingPrototype;
6936}
6937
6938void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6939  // Don't complain if we're in GNU89 mode and the previous definition
6940  // was an extern inline function.
6941  const FunctionDecl *Definition;
6942  if (FD->isDefined(Definition) &&
6943      !canRedefineFunction(Definition, getLangOptions())) {
6944    if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6945        Definition->getStorageClass() == SC_Extern)
6946      Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6947        << FD->getDeclName() << getLangOptions().CPlusPlus;
6948    else
6949      Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6950    Diag(Definition->getLocation(), diag::note_previous_definition);
6951  }
6952}
6953
6954Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
6955  // Clear the last template instantiation error context.
6956  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6957
6958  if (!D)
6959    return D;
6960  FunctionDecl *FD = 0;
6961
6962  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
6963    FD = FunTmpl->getTemplatedDecl();
6964  else
6965    FD = cast<FunctionDecl>(D);
6966
6967  // Enter a new function scope
6968  PushFunctionScope();
6969
6970  // See if this is a redefinition.
6971  if (!FD->isLateTemplateParsed())
6972    CheckForFunctionRedefinition(FD);
6973
6974  // Builtin functions cannot be defined.
6975  if (unsigned BuiltinID = FD->getBuiltinID()) {
6976    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
6977      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
6978      FD->setInvalidDecl();
6979    }
6980  }
6981
6982  // The return type of a function definition must be complete
6983  // (C99 6.9.1p3, C++ [dcl.fct]p6).
6984  QualType ResultType = FD->getResultType();
6985  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
6986      !FD->isInvalidDecl() &&
6987      RequireCompleteType(FD->getLocation(), ResultType,
6988                          diag::err_func_def_incomplete_result))
6989    FD->setInvalidDecl();
6990
6991  // GNU warning -Wmissing-prototypes:
6992  //   Warn if a global function is defined without a previous
6993  //   prototype declaration. This warning is issued even if the
6994  //   definition itself provides a prototype. The aim is to detect
6995  //   global functions that fail to be declared in header files.
6996  if (ShouldWarnAboutMissingPrototype(FD))
6997    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
6998
6999  if (FnBodyScope)
7000    PushDeclContext(FnBodyScope, FD);
7001
7002  // Check the validity of our function parameters
7003  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7004                           /*CheckParameterNames=*/true);
7005
7006  // Introduce our parameters into the function scope
7007  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7008    ParmVarDecl *Param = FD->getParamDecl(p);
7009    Param->setOwningFunction(FD);
7010
7011    // If this has an identifier, add it to the scope stack.
7012    if (Param->getIdentifier() && FnBodyScope) {
7013      CheckShadow(FnBodyScope, Param);
7014
7015      PushOnScopeChains(Param, FnBodyScope);
7016    }
7017  }
7018
7019  // Checking attributes of current function definition
7020  // dllimport attribute.
7021  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7022  if (DA && (!FD->getAttr<DLLExportAttr>())) {
7023    // dllimport attribute cannot be directly applied to definition.
7024    // Microsoft accepts dllimport for functions defined within class scope.
7025    if (!DA->isInherited() &&
7026        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7027      Diag(FD->getLocation(),
7028           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7029        << "dllimport";
7030      FD->setInvalidDecl();
7031      return FD;
7032    }
7033
7034    // Visual C++ appears to not think this is an issue, so only issue
7035    // a warning when Microsoft extensions are disabled.
7036    if (!LangOpts.MicrosoftExt) {
7037      // If a symbol previously declared dllimport is later defined, the
7038      // attribute is ignored in subsequent references, and a warning is
7039      // emitted.
7040      Diag(FD->getLocation(),
7041           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7042        << FD->getName() << "dllimport";
7043    }
7044  }
7045  return FD;
7046}
7047
7048/// \brief Given the set of return statements within a function body,
7049/// compute the variables that are subject to the named return value
7050/// optimization.
7051///
7052/// Each of the variables that is subject to the named return value
7053/// optimization will be marked as NRVO variables in the AST, and any
7054/// return statement that has a marked NRVO variable as its NRVO candidate can
7055/// use the named return value optimization.
7056///
7057/// This function applies a very simplistic algorithm for NRVO: if every return
7058/// statement in the function has the same NRVO candidate, that candidate is
7059/// the NRVO variable.
7060///
7061/// FIXME: Employ a smarter algorithm that accounts for multiple return
7062/// statements and the lifetimes of the NRVO candidates. We should be able to
7063/// find a maximal set of NRVO variables.
7064void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7065  ReturnStmt **Returns = Scope->Returns.data();
7066
7067  const VarDecl *NRVOCandidate = 0;
7068  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7069    if (!Returns[I]->getNRVOCandidate())
7070      return;
7071
7072    if (!NRVOCandidate)
7073      NRVOCandidate = Returns[I]->getNRVOCandidate();
7074    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7075      return;
7076  }
7077
7078  if (NRVOCandidate)
7079    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7080}
7081
7082Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7083  return ActOnFinishFunctionBody(D, move(BodyArg), false);
7084}
7085
7086Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7087                                    bool IsInstantiation) {
7088  FunctionDecl *FD = 0;
7089  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7090  if (FunTmpl)
7091    FD = FunTmpl->getTemplatedDecl();
7092  else
7093    FD = dyn_cast_or_null<FunctionDecl>(dcl);
7094
7095  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7096  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7097
7098  if (FD) {
7099    FD->setBody(Body);
7100    if (FD->isMain()) {
7101      // C and C++ allow for main to automagically return 0.
7102      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7103      FD->setHasImplicitReturnZero(true);
7104      WP.disableCheckFallThrough();
7105    } else if (FD->hasAttr<NakedAttr>()) {
7106      // If the function is marked 'naked', don't complain about missing return
7107      // statements.
7108      WP.disableCheckFallThrough();
7109    }
7110
7111    // MSVC permits the use of pure specifier (=0) on function definition,
7112    // defined at class scope, warn about this non standard construct.
7113    if (getLangOptions().MicrosoftExt && FD->isPure())
7114      Diag(FD->getLocation(), diag::warn_pure_function_definition);
7115
7116    if (!FD->isInvalidDecl()) {
7117      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7118      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7119                                             FD->getResultType(), FD);
7120
7121      // If this is a constructor, we need a vtable.
7122      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7123        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7124
7125      computeNRVO(Body, getCurFunction());
7126    }
7127
7128    assert(FD == getCurFunctionDecl() && "Function parsing confused");
7129  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7130    assert(MD == getCurMethodDecl() && "Method parsing confused");
7131    MD->setBody(Body);
7132    if (Body)
7133      MD->setEndLoc(Body->getLocEnd());
7134    if (!MD->isInvalidDecl()) {
7135      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7136      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7137                                             MD->getResultType(), MD);
7138
7139      if (Body)
7140        computeNRVO(Body, getCurFunction());
7141    }
7142    if (ObjCShouldCallSuperDealloc) {
7143      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7144      ObjCShouldCallSuperDealloc = false;
7145    }
7146    if (ObjCShouldCallSuperFinalize) {
7147      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7148      ObjCShouldCallSuperFinalize = false;
7149    }
7150  } else {
7151    return 0;
7152  }
7153
7154  assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7155         "ObjC methods, which should have been handled in the block above.");
7156  assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7157         "ObjC methods, which should have been handled in the block above.");
7158
7159  // Verify and clean out per-function state.
7160  if (Body) {
7161    // C++ constructors that have function-try-blocks can't have return
7162    // statements in the handlers of that block. (C++ [except.handle]p14)
7163    // Verify this.
7164    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7165      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7166
7167    // Verify that gotos and switch cases don't jump into scopes illegally.
7168    if (getCurFunction()->NeedsScopeChecking() &&
7169        !dcl->isInvalidDecl() &&
7170        !hasAnyUnrecoverableErrorsInThisFunction())
7171      DiagnoseInvalidJumps(Body);
7172
7173    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7174      if (!Destructor->getParent()->isDependentType())
7175        CheckDestructor(Destructor);
7176
7177      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7178                                             Destructor->getParent());
7179    }
7180
7181    // If any errors have occurred, clear out any temporaries that may have
7182    // been leftover. This ensures that these temporaries won't be picked up for
7183    // deletion in some later function.
7184    if (PP.getDiagnostics().hasErrorOccurred() ||
7185        PP.getDiagnostics().getSuppressAllDiagnostics()) {
7186      ExprTemporaries.clear();
7187      ExprNeedsCleanups = false;
7188    } else if (!isa<FunctionTemplateDecl>(dcl)) {
7189      // Since the body is valid, issue any analysis-based warnings that are
7190      // enabled.
7191      ActivePolicy = &WP;
7192    }
7193
7194    if (FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7195        !CheckConstexprFunctionBody(FD, Body))
7196      FD->setInvalidDecl();
7197
7198    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
7199    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7200  }
7201
7202  if (!IsInstantiation)
7203    PopDeclContext();
7204
7205  PopFunctionOrBlockScope(ActivePolicy, dcl);
7206
7207  // If any errors have occurred, clear out any temporaries that may have
7208  // been leftover. This ensures that these temporaries won't be picked up for
7209  // deletion in some later function.
7210  if (getDiagnostics().hasErrorOccurred()) {
7211    ExprTemporaries.clear();
7212    ExprNeedsCleanups = false;
7213  }
7214
7215  return dcl;
7216}
7217
7218
7219/// When we finish delayed parsing of an attribute, we must attach it to the
7220/// relevant Decl.
7221void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7222                                       ParsedAttributes &Attrs) {
7223  ProcessDeclAttributeList(S, D, Attrs.getList());
7224}
7225
7226
7227/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7228/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7229NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7230                                          IdentifierInfo &II, Scope *S) {
7231  // Before we produce a declaration for an implicitly defined
7232  // function, see whether there was a locally-scoped declaration of
7233  // this name as a function or variable. If so, use that
7234  // (non-visible) declaration, and complain about it.
7235  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7236    = findLocallyScopedExternalDecl(&II);
7237  if (Pos != LocallyScopedExternalDecls.end()) {
7238    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7239    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7240    return Pos->second;
7241  }
7242
7243  // Extension in C99.  Legal in C90, but warn about it.
7244  if (II.getName().startswith("__builtin_"))
7245    Diag(Loc, diag::warn_builtin_unknown) << &II;
7246  else if (getLangOptions().C99)
7247    Diag(Loc, diag::ext_implicit_function_decl) << &II;
7248  else
7249    Diag(Loc, diag::warn_implicit_function_decl) << &II;
7250
7251  // Set a Declarator for the implicit definition: int foo();
7252  const char *Dummy;
7253  AttributeFactory attrFactory;
7254  DeclSpec DS(attrFactory);
7255  unsigned DiagID;
7256  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7257  (void)Error; // Silence warning.
7258  assert(!Error && "Error setting up implicit decl!");
7259  Declarator D(DS, Declarator::BlockContext);
7260  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7261                                             0, 0, true, SourceLocation(),
7262                                             SourceLocation(), SourceLocation(),
7263                                             SourceLocation(),
7264                                             EST_None, SourceLocation(),
7265                                             0, 0, 0, 0, Loc, Loc, D),
7266                DS.getAttributes(),
7267                SourceLocation());
7268  D.SetIdentifier(&II, Loc);
7269
7270  // Insert this function into translation-unit scope.
7271
7272  DeclContext *PrevDC = CurContext;
7273  CurContext = Context.getTranslationUnitDecl();
7274
7275  FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7276  FD->setImplicit();
7277
7278  CurContext = PrevDC;
7279
7280  AddKnownFunctionAttributes(FD);
7281
7282  return FD;
7283}
7284
7285/// \brief Adds any function attributes that we know a priori based on
7286/// the declaration of this function.
7287///
7288/// These attributes can apply both to implicitly-declared builtins
7289/// (like __builtin___printf_chk) or to library-declared functions
7290/// like NSLog or printf.
7291///
7292/// We need to check for duplicate attributes both here and where user-written
7293/// attributes are applied to declarations.
7294void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7295  if (FD->isInvalidDecl())
7296    return;
7297
7298  // If this is a built-in function, map its builtin attributes to
7299  // actual attributes.
7300  if (unsigned BuiltinID = FD->getBuiltinID()) {
7301    // Handle printf-formatting attributes.
7302    unsigned FormatIdx;
7303    bool HasVAListArg;
7304    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7305      if (!FD->getAttr<FormatAttr>())
7306        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7307                                                "printf", FormatIdx+1,
7308                                               HasVAListArg ? 0 : FormatIdx+2));
7309    }
7310    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7311                                             HasVAListArg)) {
7312     if (!FD->getAttr<FormatAttr>())
7313       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7314                                              "scanf", FormatIdx+1,
7315                                              HasVAListArg ? 0 : FormatIdx+2));
7316    }
7317
7318    // Mark const if we don't care about errno and that is the only
7319    // thing preventing the function from being const. This allows
7320    // IRgen to use LLVM intrinsics for such functions.
7321    if (!getLangOptions().MathErrno &&
7322        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7323      if (!FD->getAttr<ConstAttr>())
7324        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7325    }
7326
7327    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7328        !FD->getAttr<ReturnsTwiceAttr>())
7329      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7330    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7331      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7332    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7333      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7334  }
7335
7336  IdentifierInfo *Name = FD->getIdentifier();
7337  if (!Name)
7338    return;
7339  if ((!getLangOptions().CPlusPlus &&
7340       FD->getDeclContext()->isTranslationUnit()) ||
7341      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7342       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7343       LinkageSpecDecl::lang_c)) {
7344    // Okay: this could be a libc/libm/Objective-C function we know
7345    // about.
7346  } else
7347    return;
7348
7349  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
7350    // FIXME: NSLog and NSLogv should be target specific
7351    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
7352      // FIXME: We known better than our headers.
7353      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
7354    } else
7355      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7356                                             "printf", 1,
7357                                             Name->isStr("NSLogv") ? 0 : 2));
7358  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7359    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7360    // target-specific builtins, perhaps?
7361    if (!FD->getAttr<FormatAttr>())
7362      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7363                                             "printf", 2,
7364                                             Name->isStr("vasprintf") ? 0 : 3));
7365  }
7366}
7367
7368TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7369                                    TypeSourceInfo *TInfo) {
7370  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7371  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7372
7373  if (!TInfo) {
7374    assert(D.isInvalidType() && "no declarator info for valid type");
7375    TInfo = Context.getTrivialTypeSourceInfo(T);
7376  }
7377
7378  // Scope manipulation handled by caller.
7379  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7380                                           D.getSourceRange().getBegin(),
7381                                           D.getIdentifierLoc(),
7382                                           D.getIdentifier(),
7383                                           TInfo);
7384
7385  // Bail out immediately if we have an invalid declaration.
7386  if (D.isInvalidType()) {
7387    NewTD->setInvalidDecl();
7388    return NewTD;
7389  }
7390
7391  if (D.getDeclSpec().isModulePrivateSpecified()) {
7392    if (CurContext->isFunctionOrMethod())
7393      Diag(NewTD->getLocation(), diag::err_module_private_local)
7394        << 2 << NewTD->getDeclName()
7395        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7396        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7397    else
7398      NewTD->setModulePrivate();
7399  }
7400
7401  // C++ [dcl.typedef]p8:
7402  //   If the typedef declaration defines an unnamed class (or
7403  //   enum), the first typedef-name declared by the declaration
7404  //   to be that class type (or enum type) is used to denote the
7405  //   class type (or enum type) for linkage purposes only.
7406  // We need to check whether the type was declared in the declaration.
7407  switch (D.getDeclSpec().getTypeSpecType()) {
7408  case TST_enum:
7409  case TST_struct:
7410  case TST_union:
7411  case TST_class: {
7412    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7413
7414    // Do nothing if the tag is not anonymous or already has an
7415    // associated typedef (from an earlier typedef in this decl group).
7416    if (tagFromDeclSpec->getIdentifier()) break;
7417    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7418
7419    // A well-formed anonymous tag must always be a TUK_Definition.
7420    assert(tagFromDeclSpec->isThisDeclarationADefinition());
7421
7422    // The type must match the tag exactly;  no qualifiers allowed.
7423    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7424      break;
7425
7426    // Otherwise, set this is the anon-decl typedef for the tag.
7427    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7428    break;
7429  }
7430
7431  default:
7432    break;
7433  }
7434
7435  return NewTD;
7436}
7437
7438
7439/// \brief Determine whether a tag with a given kind is acceptable
7440/// as a redeclaration of the given tag declaration.
7441///
7442/// \returns true if the new tag kind is acceptable, false otherwise.
7443bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7444                                        TagTypeKind NewTag, bool isDefinition,
7445                                        SourceLocation NewTagLoc,
7446                                        const IdentifierInfo &Name) {
7447  // C++ [dcl.type.elab]p3:
7448  //   The class-key or enum keyword present in the
7449  //   elaborated-type-specifier shall agree in kind with the
7450  //   declaration to which the name in the elaborated-type-specifier
7451  //   refers. This rule also applies to the form of
7452  //   elaborated-type-specifier that declares a class-name or
7453  //   friend class since it can be construed as referring to the
7454  //   definition of the class. Thus, in any
7455  //   elaborated-type-specifier, the enum keyword shall be used to
7456  //   refer to an enumeration (7.2), the union class-key shall be
7457  //   used to refer to a union (clause 9), and either the class or
7458  //   struct class-key shall be used to refer to a class (clause 9)
7459  //   declared using the class or struct class-key.
7460  TagTypeKind OldTag = Previous->getTagKind();
7461  if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7462    if (OldTag == NewTag)
7463      return true;
7464
7465  if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7466      (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7467    // Warn about the struct/class tag mismatch.
7468    bool isTemplate = false;
7469    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7470      isTemplate = Record->getDescribedClassTemplate();
7471
7472    if (!ActiveTemplateInstantiations.empty()) {
7473      // In a template instantiation, do not offer fix-its for tag mismatches
7474      // since they usually mess up the template instead of fixing the problem.
7475      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7476        << (NewTag == TTK_Class) << isTemplate << &Name;
7477      return true;
7478    }
7479
7480    if (isDefinition) {
7481      // On definitions, check previous tags and issue a fix-it for each
7482      // one that doesn't match the current tag.
7483      if (Previous->getDefinition()) {
7484        // Don't suggest fix-its for redefinitions.
7485        return true;
7486      }
7487
7488      bool previousMismatch = false;
7489      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7490           E(Previous->redecls_end()); I != E; ++I) {
7491        if (I->getTagKind() != NewTag) {
7492          if (!previousMismatch) {
7493            previousMismatch = true;
7494            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7495              << (NewTag == TTK_Class) << isTemplate << &Name;
7496          }
7497          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7498            << (NewTag == TTK_Class)
7499            << FixItHint::CreateReplacement(I->getInnerLocStart(),
7500                                            NewTag == TTK_Class?
7501                                            "class" : "struct");
7502        }
7503      }
7504      return true;
7505    }
7506
7507    // Check for a previous definition.  If current tag and definition
7508    // are same type, do nothing.  If no definition, but disagree with
7509    // with previous tag type, give a warning, but no fix-it.
7510    const TagDecl *Redecl = Previous->getDefinition() ?
7511                            Previous->getDefinition() : Previous;
7512    if (Redecl->getTagKind() == NewTag) {
7513      return true;
7514    }
7515
7516    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7517      << (NewTag == TTK_Class)
7518      << isTemplate << &Name;
7519    Diag(Redecl->getLocation(), diag::note_previous_use);
7520
7521    // If there is a previous defintion, suggest a fix-it.
7522    if (Previous->getDefinition()) {
7523        Diag(NewTagLoc, diag::note_struct_class_suggestion)
7524          << (Redecl->getTagKind() == TTK_Class)
7525          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7526                        Redecl->getTagKind() == TTK_Class? "class" : "struct");
7527    }
7528
7529    return true;
7530  }
7531  return false;
7532}
7533
7534/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
7535/// former case, Name will be non-null.  In the later case, Name will be null.
7536/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7537/// reference/declaration/definition of a tag.
7538Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7539                     SourceLocation KWLoc, CXXScopeSpec &SS,
7540                     IdentifierInfo *Name, SourceLocation NameLoc,
7541                     AttributeList *Attr, AccessSpecifier AS,
7542                     SourceLocation ModulePrivateLoc,
7543                     MultiTemplateParamsArg TemplateParameterLists,
7544                     bool &OwnedDecl, bool &IsDependent,
7545                     bool ScopedEnum, bool ScopedEnumUsesClassTag,
7546                     TypeResult UnderlyingType) {
7547  // If this is not a definition, it must have a name.
7548  assert((Name != 0 || TUK == TUK_Definition) &&
7549         "Nameless record must be a definition!");
7550  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7551
7552  OwnedDecl = false;
7553  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7554
7555  // FIXME: Check explicit specializations more carefully.
7556  bool isExplicitSpecialization = false;
7557  bool Invalid = false;
7558
7559  // We only need to do this matching if we have template parameters
7560  // or a scope specifier, which also conveniently avoids this work
7561  // for non-C++ cases.
7562  if (TemplateParameterLists.size() > 0 ||
7563      (SS.isNotEmpty() && TUK != TUK_Reference)) {
7564    if (TemplateParameterList *TemplateParams
7565          = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7566                                                TemplateParameterLists.get(),
7567                                                TemplateParameterLists.size(),
7568                                                    TUK == TUK_Friend,
7569                                                    isExplicitSpecialization,
7570                                                    Invalid)) {
7571      if (TemplateParams->size() > 0) {
7572        // This is a declaration or definition of a class template (which may
7573        // be a member of another template).
7574
7575        if (Invalid)
7576          return 0;
7577
7578        OwnedDecl = false;
7579        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7580                                               SS, Name, NameLoc, Attr,
7581                                               TemplateParams, AS,
7582                                               ModulePrivateLoc,
7583                                           TemplateParameterLists.size() - 1,
7584                 (TemplateParameterList**) TemplateParameterLists.release());
7585        return Result.get();
7586      } else {
7587        // The "template<>" header is extraneous.
7588        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7589          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7590        isExplicitSpecialization = true;
7591      }
7592    }
7593  }
7594
7595  // Figure out the underlying type if this a enum declaration. We need to do
7596  // this early, because it's needed to detect if this is an incompatible
7597  // redeclaration.
7598  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
7599
7600  if (Kind == TTK_Enum) {
7601    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
7602      // No underlying type explicitly specified, or we failed to parse the
7603      // type, default to int.
7604      EnumUnderlying = Context.IntTy.getTypePtr();
7605    else if (UnderlyingType.get()) {
7606      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
7607      // integral type; any cv-qualification is ignored.
7608      TypeSourceInfo *TI = 0;
7609      QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
7610      EnumUnderlying = TI;
7611
7612      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7613
7614      if (!T->isDependentType() && !T->isIntegralType(Context)) {
7615        Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
7616          << T;
7617        // Recover by falling back to int.
7618        EnumUnderlying = Context.IntTy.getTypePtr();
7619      }
7620
7621      if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
7622                                          UPPC_FixedUnderlyingType))
7623        EnumUnderlying = Context.IntTy.getTypePtr();
7624
7625    } else if (getLangOptions().MicrosoftExt)
7626      // Microsoft enums are always of int type.
7627      EnumUnderlying = Context.IntTy.getTypePtr();
7628  }
7629
7630  DeclContext *SearchDC = CurContext;
7631  DeclContext *DC = CurContext;
7632  bool isStdBadAlloc = false;
7633
7634  RedeclarationKind Redecl = ForRedeclaration;
7635  if (TUK == TUK_Friend || TUK == TUK_Reference)
7636    Redecl = NotForRedeclaration;
7637
7638  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
7639
7640  if (Name && SS.isNotEmpty()) {
7641    // We have a nested-name tag ('struct foo::bar').
7642
7643    // Check for invalid 'foo::'.
7644    if (SS.isInvalid()) {
7645      Name = 0;
7646      goto CreateNewDecl;
7647    }
7648
7649    // If this is a friend or a reference to a class in a dependent
7650    // context, don't try to make a decl for it.
7651    if (TUK == TUK_Friend || TUK == TUK_Reference) {
7652      DC = computeDeclContext(SS, false);
7653      if (!DC) {
7654        IsDependent = true;
7655        return 0;
7656      }
7657    } else {
7658      DC = computeDeclContext(SS, true);
7659      if (!DC) {
7660        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
7661          << SS.getRange();
7662        return 0;
7663      }
7664    }
7665
7666    if (RequireCompleteDeclContext(SS, DC))
7667      return 0;
7668
7669    SearchDC = DC;
7670    // Look-up name inside 'foo::'.
7671    LookupQualifiedName(Previous, DC);
7672
7673    if (Previous.isAmbiguous())
7674      return 0;
7675
7676    if (Previous.empty()) {
7677      // Name lookup did not find anything. However, if the
7678      // nested-name-specifier refers to the current instantiation,
7679      // and that current instantiation has any dependent base
7680      // classes, we might find something at instantiation time: treat
7681      // this as a dependent elaborated-type-specifier.
7682      // But this only makes any sense for reference-like lookups.
7683      if (Previous.wasNotFoundInCurrentInstantiation() &&
7684          (TUK == TUK_Reference || TUK == TUK_Friend)) {
7685        IsDependent = true;
7686        return 0;
7687      }
7688
7689      // A tag 'foo::bar' must already exist.
7690      Diag(NameLoc, diag::err_not_tag_in_scope)
7691        << Kind << Name << DC << SS.getRange();
7692      Name = 0;
7693      Invalid = true;
7694      goto CreateNewDecl;
7695    }
7696  } else if (Name) {
7697    // If this is a named struct, check to see if there was a previous forward
7698    // declaration or definition.
7699    // FIXME: We're looking into outer scopes here, even when we
7700    // shouldn't be. Doing so can result in ambiguities that we
7701    // shouldn't be diagnosing.
7702    LookupName(Previous, S);
7703
7704    if (Previous.isAmbiguous() &&
7705        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
7706      LookupResult::Filter F = Previous.makeFilter();
7707      while (F.hasNext()) {
7708        NamedDecl *ND = F.next();
7709        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7710          F.erase();
7711      }
7712      F.done();
7713    }
7714
7715    // Note:  there used to be some attempt at recovery here.
7716    if (Previous.isAmbiguous())
7717      return 0;
7718
7719    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
7720      // FIXME: This makes sure that we ignore the contexts associated
7721      // with C structs, unions, and enums when looking for a matching
7722      // tag declaration or definition. See the similar lookup tweak
7723      // in Sema::LookupName; is there a better way to deal with this?
7724      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7725        SearchDC = SearchDC->getParent();
7726    }
7727  } else if (S->isFunctionPrototypeScope()) {
7728    // If this is an enum declaration in function prototype scope, set its
7729    // initial context to the translation unit.
7730    SearchDC = Context.getTranslationUnitDecl();
7731  }
7732
7733  if (Previous.isSingleResult() &&
7734      Previous.getFoundDecl()->isTemplateParameter()) {
7735    // Maybe we will complain about the shadowed template parameter.
7736    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
7737    // Just pretend that we didn't see the previous declaration.
7738    Previous.clear();
7739  }
7740
7741  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
7742      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
7743    // This is a declaration of or a reference to "std::bad_alloc".
7744    isStdBadAlloc = true;
7745
7746    if (Previous.empty() && StdBadAlloc) {
7747      // std::bad_alloc has been implicitly declared (but made invisible to
7748      // name lookup). Fill in this implicit declaration as the previous
7749      // declaration, so that the declarations get chained appropriately.
7750      Previous.addDecl(getStdBadAlloc());
7751    }
7752  }
7753
7754  // If we didn't find a previous declaration, and this is a reference
7755  // (or friend reference), move to the correct scope.  In C++, we
7756  // also need to do a redeclaration lookup there, just in case
7757  // there's a shadow friend decl.
7758  if (Name && Previous.empty() &&
7759      (TUK == TUK_Reference || TUK == TUK_Friend)) {
7760    if (Invalid) goto CreateNewDecl;
7761    assert(SS.isEmpty());
7762
7763    if (TUK == TUK_Reference) {
7764      // C++ [basic.scope.pdecl]p5:
7765      //   -- for an elaborated-type-specifier of the form
7766      //
7767      //          class-key identifier
7768      //
7769      //      if the elaborated-type-specifier is used in the
7770      //      decl-specifier-seq or parameter-declaration-clause of a
7771      //      function defined in namespace scope, the identifier is
7772      //      declared as a class-name in the namespace that contains
7773      //      the declaration; otherwise, except as a friend
7774      //      declaration, the identifier is declared in the smallest
7775      //      non-class, non-function-prototype scope that contains the
7776      //      declaration.
7777      //
7778      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7779      // C structs and unions.
7780      //
7781      // It is an error in C++ to declare (rather than define) an enum
7782      // type, including via an elaborated type specifier.  We'll
7783      // diagnose that later; for now, declare the enum in the same
7784      // scope as we would have picked for any other tag type.
7785      //
7786      // GNU C also supports this behavior as part of its incomplete
7787      // enum types extension, while GNU C++ does not.
7788      //
7789      // Find the context where we'll be declaring the tag.
7790      // FIXME: We would like to maintain the current DeclContext as the
7791      // lexical context,
7792      while (SearchDC->isRecord() || SearchDC->isTransparentContext())
7793        SearchDC = SearchDC->getParent();
7794
7795      // Find the scope where we'll be declaring the tag.
7796      while (S->isClassScope() ||
7797             (getLangOptions().CPlusPlus &&
7798              S->isFunctionPrototypeScope()) ||
7799             ((S->getFlags() & Scope::DeclScope) == 0) ||
7800             (S->getEntity() &&
7801              ((DeclContext *)S->getEntity())->isTransparentContext()))
7802        S = S->getParent();
7803    } else {
7804      assert(TUK == TUK_Friend);
7805      // C++ [namespace.memdef]p3:
7806      //   If a friend declaration in a non-local class first declares a
7807      //   class or function, the friend class or function is a member of
7808      //   the innermost enclosing namespace.
7809      SearchDC = SearchDC->getEnclosingNamespaceContext();
7810    }
7811
7812    // In C++, we need to do a redeclaration lookup to properly
7813    // diagnose some problems.
7814    if (getLangOptions().CPlusPlus) {
7815      Previous.setRedeclarationKind(ForRedeclaration);
7816      LookupQualifiedName(Previous, SearchDC);
7817    }
7818  }
7819
7820  if (!Previous.empty()) {
7821    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
7822
7823    // It's okay to have a tag decl in the same scope as a typedef
7824    // which hides a tag decl in the same scope.  Finding this
7825    // insanity with a redeclaration lookup can only actually happen
7826    // in C++.
7827    //
7828    // This is also okay for elaborated-type-specifiers, which is
7829    // technically forbidden by the current standard but which is
7830    // okay according to the likely resolution of an open issue;
7831    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7832    if (getLangOptions().CPlusPlus) {
7833      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7834        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7835          TagDecl *Tag = TT->getDecl();
7836          if (Tag->getDeclName() == Name &&
7837              Tag->getDeclContext()->getRedeclContext()
7838                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
7839            PrevDecl = Tag;
7840            Previous.clear();
7841            Previous.addDecl(Tag);
7842            Previous.resolveKind();
7843          }
7844        }
7845      }
7846    }
7847
7848    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
7849      // If this is a use of a previous tag, or if the tag is already declared
7850      // in the same scope (so that the definition/declaration completes or
7851      // rementions the tag), reuse the decl.
7852      if (TUK == TUK_Reference || TUK == TUK_Friend ||
7853          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
7854        // Make sure that this wasn't declared as an enum and now used as a
7855        // struct or something similar.
7856        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7857                                          TUK == TUK_Definition, KWLoc,
7858                                          *Name)) {
7859          bool SafeToContinue
7860            = (PrevTagDecl->getTagKind() != TTK_Enum &&
7861               Kind != TTK_Enum);
7862          if (SafeToContinue)
7863            Diag(KWLoc, diag::err_use_with_wrong_tag)
7864              << Name
7865              << FixItHint::CreateReplacement(SourceRange(KWLoc),
7866                                              PrevTagDecl->getKindName());
7867          else
7868            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
7869          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7870
7871          if (SafeToContinue)
7872            Kind = PrevTagDecl->getTagKind();
7873          else {
7874            // Recover by making this an anonymous redefinition.
7875            Name = 0;
7876            Previous.clear();
7877            Invalid = true;
7878          }
7879        }
7880
7881        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7882          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7883
7884          // All conflicts with previous declarations are recovered by
7885          // returning the previous declaration.
7886          if (ScopedEnum != PrevEnum->isScoped()) {
7887            Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7888              << PrevEnum->isScoped();
7889            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7890            return PrevTagDecl;
7891          }
7892          else if (EnumUnderlying && PrevEnum->isFixed()) {
7893            QualType T;
7894            if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7895                T = TI->getType();
7896            else
7897                T = QualType(EnumUnderlying.get<const Type*>(), 0);
7898
7899            if (!Context.hasSameUnqualifiedType(T,
7900                                                PrevEnum->getIntegerType())) {
7901              Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7902                   diag::err_enum_redeclare_type_mismatch)
7903                << T
7904                << PrevEnum->getIntegerType();
7905              Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7906              return PrevTagDecl;
7907            }
7908          }
7909          else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7910            Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7911              << PrevEnum->isFixed();
7912            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7913            return PrevTagDecl;
7914          }
7915        }
7916
7917        if (!Invalid) {
7918          // If this is a use, just return the declaration we found.
7919
7920          // FIXME: In the future, return a variant or some other clue
7921          // for the consumer of this Decl to know it doesn't own it.
7922          // For our current ASTs this shouldn't be a problem, but will
7923          // need to be changed with DeclGroups.
7924          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7925               getLangOptions().MicrosoftExt)) || TUK == TUK_Friend)
7926            return PrevTagDecl;
7927
7928          // Diagnose attempts to redefine a tag.
7929          if (TUK == TUK_Definition) {
7930            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
7931              // If we're defining a specialization and the previous definition
7932              // is from an implicit instantiation, don't emit an error
7933              // here; we'll catch this in the general case below.
7934              if (!isExplicitSpecialization ||
7935                  !isa<CXXRecordDecl>(Def) ||
7936                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7937                                               == TSK_ExplicitSpecialization) {
7938                Diag(NameLoc, diag::err_redefinition) << Name;
7939                Diag(Def->getLocation(), diag::note_previous_definition);
7940                // If this is a redefinition, recover by making this
7941                // struct be anonymous, which will make any later
7942                // references get the previous definition.
7943                Name = 0;
7944                Previous.clear();
7945                Invalid = true;
7946              }
7947            } else {
7948              // If the type is currently being defined, complain
7949              // about a nested redefinition.
7950              const TagType *Tag
7951                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
7952              if (Tag->isBeingDefined()) {
7953                Diag(NameLoc, diag::err_nested_redefinition) << Name;
7954                Diag(PrevTagDecl->getLocation(),
7955                     diag::note_previous_definition);
7956                Name = 0;
7957                Previous.clear();
7958                Invalid = true;
7959              }
7960            }
7961
7962            // Okay, this is definition of a previously declared or referenced
7963            // tag PrevDecl. We're going to create a new Decl for it.
7964          }
7965        }
7966        // If we get here we have (another) forward declaration or we
7967        // have a definition.  Just create a new decl.
7968
7969      } else {
7970        // If we get here, this is a definition of a new tag type in a nested
7971        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
7972        // new decl/type.  We set PrevDecl to NULL so that the entities
7973        // have distinct types.
7974        Previous.clear();
7975      }
7976      // If we get here, we're going to create a new Decl. If PrevDecl
7977      // is non-NULL, it's a definition of the tag declared by
7978      // PrevDecl. If it's NULL, we have a new definition.
7979
7980
7981    // Otherwise, PrevDecl is not a tag, but was found with tag
7982    // lookup.  This is only actually possible in C++, where a few
7983    // things like templates still live in the tag namespace.
7984    } else {
7985      assert(getLangOptions().CPlusPlus);
7986
7987      // Use a better diagnostic if an elaborated-type-specifier
7988      // found the wrong kind of type on the first
7989      // (non-redeclaration) lookup.
7990      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
7991          !Previous.isForRedeclaration()) {
7992        unsigned Kind = 0;
7993        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
7994        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7995        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
7996        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
7997        Diag(PrevDecl->getLocation(), diag::note_declared_at);
7998        Invalid = true;
7999
8000      // Otherwise, only diagnose if the declaration is in scope.
8001      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8002                                isExplicitSpecialization)) {
8003        // do nothing
8004
8005      // Diagnose implicit declarations introduced by elaborated types.
8006      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8007        unsigned Kind = 0;
8008        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8009        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8010        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8011        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8012        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8013        Invalid = true;
8014
8015      // Otherwise it's a declaration.  Call out a particularly common
8016      // case here.
8017      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8018        unsigned Kind = 0;
8019        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8020        Diag(NameLoc, diag::err_tag_definition_of_typedef)
8021          << Name << Kind << TND->getUnderlyingType();
8022        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8023        Invalid = true;
8024
8025      // Otherwise, diagnose.
8026      } else {
8027        // The tag name clashes with something else in the target scope,
8028        // issue an error and recover by making this tag be anonymous.
8029        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8030        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8031        Name = 0;
8032        Invalid = true;
8033      }
8034
8035      // The existing declaration isn't relevant to us; we're in a
8036      // new scope, so clear out the previous declaration.
8037      Previous.clear();
8038    }
8039  }
8040
8041CreateNewDecl:
8042
8043  TagDecl *PrevDecl = 0;
8044  if (Previous.isSingleResult())
8045    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8046
8047  // If there is an identifier, use the location of the identifier as the
8048  // location of the decl, otherwise use the location of the struct/union
8049  // keyword.
8050  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8051
8052  // Otherwise, create a new declaration. If there is a previous
8053  // declaration of the same entity, the two will be linked via
8054  // PrevDecl.
8055  TagDecl *New;
8056
8057  bool IsForwardReference = false;
8058  if (Kind == TTK_Enum) {
8059    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8060    // enum X { A, B, C } D;    D should chain to X.
8061    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8062                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8063                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8064    // If this is an undefined enum, warn.
8065    if (TUK != TUK_Definition && !Invalid) {
8066      TagDecl *Def;
8067      if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8068        // C++0x: 7.2p2: opaque-enum-declaration.
8069        // Conflicts are diagnosed above. Do nothing.
8070      }
8071      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8072        Diag(Loc, diag::ext_forward_ref_enum_def)
8073          << New;
8074        Diag(Def->getLocation(), diag::note_previous_definition);
8075      } else {
8076        unsigned DiagID = diag::ext_forward_ref_enum;
8077        if (getLangOptions().MicrosoftExt)
8078          DiagID = diag::ext_ms_forward_ref_enum;
8079        else if (getLangOptions().CPlusPlus)
8080          DiagID = diag::err_forward_ref_enum;
8081        Diag(Loc, DiagID);
8082
8083        // If this is a forward-declared reference to an enumeration, make a
8084        // note of it; we won't actually be introducing the declaration into
8085        // the declaration context.
8086        if (TUK == TUK_Reference)
8087          IsForwardReference = true;
8088      }
8089    }
8090
8091    if (EnumUnderlying) {
8092      EnumDecl *ED = cast<EnumDecl>(New);
8093      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8094        ED->setIntegerTypeSourceInfo(TI);
8095      else
8096        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8097      ED->setPromotionType(ED->getIntegerType());
8098    }
8099
8100  } else {
8101    // struct/union/class
8102
8103    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8104    // struct X { int A; } D;    D should chain to X.
8105    if (getLangOptions().CPlusPlus) {
8106      // FIXME: Look for a way to use RecordDecl for simple structs.
8107      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8108                                  cast_or_null<CXXRecordDecl>(PrevDecl));
8109
8110      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8111        StdBadAlloc = cast<CXXRecordDecl>(New);
8112    } else
8113      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8114                               cast_or_null<RecordDecl>(PrevDecl));
8115  }
8116
8117  // Maybe add qualifier info.
8118  if (SS.isNotEmpty()) {
8119    if (SS.isSet()) {
8120      New->setQualifierInfo(SS.getWithLocInContext(Context));
8121      if (TemplateParameterLists.size() > 0) {
8122        New->setTemplateParameterListsInfo(Context,
8123                                           TemplateParameterLists.size(),
8124                    (TemplateParameterList**) TemplateParameterLists.release());
8125      }
8126    }
8127    else
8128      Invalid = true;
8129  }
8130
8131  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8132    // Add alignment attributes if necessary; these attributes are checked when
8133    // the ASTContext lays out the structure.
8134    //
8135    // It is important for implementing the correct semantics that this
8136    // happen here (in act on tag decl). The #pragma pack stack is
8137    // maintained as a result of parser callbacks which can occur at
8138    // many points during the parsing of a struct declaration (because
8139    // the #pragma tokens are effectively skipped over during the
8140    // parsing of the struct).
8141    AddAlignmentAttributesForRecord(RD);
8142
8143    AddMsStructLayoutForRecord(RD);
8144  }
8145
8146  if (PrevDecl && PrevDecl->isModulePrivate())
8147    New->setModulePrivate();
8148  else if (ModulePrivateLoc.isValid()) {
8149    if (isExplicitSpecialization)
8150      Diag(New->getLocation(), diag::err_module_private_specialization)
8151        << 2
8152        << FixItHint::CreateRemoval(ModulePrivateLoc);
8153    else if (PrevDecl && !PrevDecl->isModulePrivate())
8154      diagnoseModulePrivateRedeclaration(New, PrevDecl, ModulePrivateLoc);
8155    // __module_private__ does not apply to local classes. However, we only
8156    // diagnose this as an error when the declaration specifiers are
8157    // freestanding. Here, we just ignore the __module_private__.
8158    // foobar
8159    else if (!SearchDC->isFunctionOrMethod())
8160      New->setModulePrivate();
8161  }
8162
8163  // If this is a specialization of a member class (of a class template),
8164  // check the specialization.
8165  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8166    Invalid = true;
8167
8168  if (Invalid)
8169    New->setInvalidDecl();
8170
8171  if (Attr)
8172    ProcessDeclAttributeList(S, New, Attr);
8173
8174  // If we're declaring or defining a tag in function prototype scope
8175  // in C, note that this type can only be used within the function.
8176  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
8177    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8178
8179  // Set the lexical context. If the tag has a C++ scope specifier, the
8180  // lexical context will be different from the semantic context.
8181  New->setLexicalDeclContext(CurContext);
8182
8183  // Mark this as a friend decl if applicable.
8184  // In Microsoft mode, a friend declaration also acts as a forward
8185  // declaration so we always pass true to setObjectOfFriendDecl to make
8186  // the tag name visible.
8187  if (TUK == TUK_Friend)
8188    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8189                               getLangOptions().MicrosoftExt);
8190
8191  // Set the access specifier.
8192  if (!Invalid && SearchDC->isRecord())
8193    SetMemberAccessSpecifier(New, PrevDecl, AS);
8194
8195  if (TUK == TUK_Definition)
8196    New->startDefinition();
8197
8198  // If this has an identifier, add it to the scope stack.
8199  if (TUK == TUK_Friend) {
8200    // We might be replacing an existing declaration in the lookup tables;
8201    // if so, borrow its access specifier.
8202    if (PrevDecl)
8203      New->setAccess(PrevDecl->getAccess());
8204
8205    DeclContext *DC = New->getDeclContext()->getRedeclContext();
8206    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
8207    if (Name) // can be null along some error paths
8208      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8209        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8210  } else if (Name) {
8211    S = getNonFieldDeclScope(S);
8212    PushOnScopeChains(New, S, !IsForwardReference);
8213    if (IsForwardReference)
8214      SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
8215
8216  } else {
8217    CurContext->addDecl(New);
8218  }
8219
8220  // If this is the C FILE type, notify the AST context.
8221  if (IdentifierInfo *II = New->getIdentifier())
8222    if (!New->isInvalidDecl() &&
8223        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8224        II->isStr("FILE"))
8225      Context.setFILEDecl(New);
8226
8227  OwnedDecl = true;
8228  return New;
8229}
8230
8231void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8232  AdjustDeclIfTemplate(TagD);
8233  TagDecl *Tag = cast<TagDecl>(TagD);
8234
8235  // Enter the tag context.
8236  PushDeclContext(S, Tag);
8237}
8238
8239Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8240  assert(isa<ObjCContainerDecl>(IDecl) &&
8241         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8242  DeclContext *OCD = cast<DeclContext>(IDecl);
8243  assert(getContainingDC(OCD) == CurContext &&
8244      "The next DeclContext should be lexically contained in the current one.");
8245  CurContext = OCD;
8246  return IDecl;
8247}
8248
8249void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8250                                           SourceLocation FinalLoc,
8251                                           SourceLocation LBraceLoc) {
8252  AdjustDeclIfTemplate(TagD);
8253  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8254
8255  FieldCollector->StartClass();
8256
8257  if (!Record->getIdentifier())
8258    return;
8259
8260  if (FinalLoc.isValid())
8261    Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8262
8263  // C++ [class]p2:
8264  //   [...] The class-name is also inserted into the scope of the
8265  //   class itself; this is known as the injected-class-name. For
8266  //   purposes of access checking, the injected-class-name is treated
8267  //   as if it were a public member name.
8268  CXXRecordDecl *InjectedClassName
8269    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8270                            Record->getLocStart(), Record->getLocation(),
8271                            Record->getIdentifier(),
8272                            /*PrevDecl=*/0,
8273                            /*DelayTypeCreation=*/true);
8274  Context.getTypeDeclType(InjectedClassName, Record);
8275  InjectedClassName->setImplicit();
8276  InjectedClassName->setAccess(AS_public);
8277  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8278      InjectedClassName->setDescribedClassTemplate(Template);
8279  PushOnScopeChains(InjectedClassName, S);
8280  assert(InjectedClassName->isInjectedClassName() &&
8281         "Broken injected-class-name");
8282}
8283
8284void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8285                                    SourceLocation RBraceLoc) {
8286  AdjustDeclIfTemplate(TagD);
8287  TagDecl *Tag = cast<TagDecl>(TagD);
8288  Tag->setRBraceLoc(RBraceLoc);
8289
8290  if (isa<CXXRecordDecl>(Tag))
8291    FieldCollector->FinishClass();
8292
8293  // Exit this scope of this tag's definition.
8294  PopDeclContext();
8295
8296  // Notify the consumer that we've defined a tag.
8297  Consumer.HandleTagDeclDefinition(Tag);
8298}
8299
8300void Sema::ActOnObjCContainerFinishDefinition() {
8301  // Exit this scope of this interface definition.
8302  PopDeclContext();
8303}
8304
8305void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8306  assert(DC == CurContext && "Mismatch of container contexts");
8307  OriginalLexicalContext = DC;
8308  ActOnObjCContainerFinishDefinition();
8309}
8310
8311void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8312  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8313  OriginalLexicalContext = 0;
8314}
8315
8316void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8317  AdjustDeclIfTemplate(TagD);
8318  TagDecl *Tag = cast<TagDecl>(TagD);
8319  Tag->setInvalidDecl();
8320
8321  // We're undoing ActOnTagStartDefinition here, not
8322  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8323  // the FieldCollector.
8324
8325  PopDeclContext();
8326}
8327
8328// Note that FieldName may be null for anonymous bitfields.
8329bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
8330                          QualType FieldTy, const Expr *BitWidth,
8331                          bool *ZeroWidth) {
8332  // Default to true; that shouldn't confuse checks for emptiness
8333  if (ZeroWidth)
8334    *ZeroWidth = true;
8335
8336  // C99 6.7.2.1p4 - verify the field type.
8337  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8338  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8339    // Handle incomplete types with specific error.
8340    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8341      return true;
8342    if (FieldName)
8343      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8344        << FieldName << FieldTy << BitWidth->getSourceRange();
8345    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8346      << FieldTy << BitWidth->getSourceRange();
8347  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8348                                             UPPC_BitFieldWidth))
8349    return true;
8350
8351  // If the bit-width is type- or value-dependent, don't try to check
8352  // it now.
8353  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8354    return false;
8355
8356  llvm::APSInt Value;
8357  if (VerifyIntegerConstantExpression(BitWidth, &Value))
8358    return true;
8359
8360  if (Value != 0 && ZeroWidth)
8361    *ZeroWidth = false;
8362
8363  // Zero-width bitfield is ok for anonymous field.
8364  if (Value == 0 && FieldName)
8365    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8366
8367  if (Value.isSigned() && Value.isNegative()) {
8368    if (FieldName)
8369      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8370               << FieldName << Value.toString(10);
8371    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8372      << Value.toString(10);
8373  }
8374
8375  if (!FieldTy->isDependentType()) {
8376    uint64_t TypeSize = Context.getTypeSize(FieldTy);
8377    if (Value.getZExtValue() > TypeSize) {
8378      if (!getLangOptions().CPlusPlus) {
8379        if (FieldName)
8380          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8381            << FieldName << (unsigned)Value.getZExtValue()
8382            << (unsigned)TypeSize;
8383
8384        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8385          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8386      }
8387
8388      if (FieldName)
8389        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8390          << FieldName << (unsigned)Value.getZExtValue()
8391          << (unsigned)TypeSize;
8392      else
8393        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8394          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8395    }
8396  }
8397
8398  return false;
8399}
8400
8401/// ActOnField - Each field of a C struct/union is passed into this in order
8402/// to create a FieldDecl object for it.
8403Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8404                       Declarator &D, Expr *BitfieldWidth) {
8405  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8406                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8407                               /*HasInit=*/false, AS_public);
8408  return Res;
8409}
8410
8411/// HandleField - Analyze a field of a C struct or a C++ data member.
8412///
8413FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8414                             SourceLocation DeclStart,
8415                             Declarator &D, Expr *BitWidth, bool HasInit,
8416                             AccessSpecifier AS) {
8417  IdentifierInfo *II = D.getIdentifier();
8418  SourceLocation Loc = DeclStart;
8419  if (II) Loc = D.getIdentifierLoc();
8420
8421  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8422  QualType T = TInfo->getType();
8423  if (getLangOptions().CPlusPlus) {
8424    CheckExtraCXXDefaultArguments(D);
8425
8426    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8427                                        UPPC_DataMemberType)) {
8428      D.setInvalidType();
8429      T = Context.IntTy;
8430      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8431    }
8432  }
8433
8434  DiagnoseFunctionSpecifiers(D);
8435
8436  if (D.getDeclSpec().isThreadSpecified())
8437    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8438  if (D.getDeclSpec().isConstexprSpecified())
8439    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8440      << 2;
8441
8442  // Check to see if this name was declared as a member previously
8443  NamedDecl *PrevDecl = 0;
8444  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8445  LookupName(Previous, S);
8446  switch (Previous.getResultKind()) {
8447    case LookupResult::Found:
8448    case LookupResult::FoundUnresolvedValue:
8449      PrevDecl = Previous.getAsSingle<NamedDecl>();
8450      break;
8451
8452    case LookupResult::FoundOverloaded:
8453      PrevDecl = Previous.getRepresentativeDecl();
8454      break;
8455
8456    case LookupResult::NotFound:
8457    case LookupResult::NotFoundInCurrentInstantiation:
8458    case LookupResult::Ambiguous:
8459      break;
8460  }
8461  Previous.suppressDiagnostics();
8462
8463  if (PrevDecl && PrevDecl->isTemplateParameter()) {
8464    // Maybe we will complain about the shadowed template parameter.
8465    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8466    // Just pretend that we didn't see the previous declaration.
8467    PrevDecl = 0;
8468  }
8469
8470  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8471    PrevDecl = 0;
8472
8473  bool Mutable
8474    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8475  SourceLocation TSSL = D.getSourceRange().getBegin();
8476  FieldDecl *NewFD
8477    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8478                     TSSL, AS, PrevDecl, &D);
8479
8480  if (NewFD->isInvalidDecl())
8481    Record->setInvalidDecl();
8482
8483  if (D.getDeclSpec().isModulePrivateSpecified())
8484    NewFD->setModulePrivate();
8485
8486  if (NewFD->isInvalidDecl() && PrevDecl) {
8487    // Don't introduce NewFD into scope; there's already something
8488    // with the same name in the same scope.
8489  } else if (II) {
8490    PushOnScopeChains(NewFD, S);
8491  } else
8492    Record->addDecl(NewFD);
8493
8494  return NewFD;
8495}
8496
8497/// \brief Build a new FieldDecl and check its well-formedness.
8498///
8499/// This routine builds a new FieldDecl given the fields name, type,
8500/// record, etc. \p PrevDecl should refer to any previous declaration
8501/// with the same name and in the same scope as the field to be
8502/// created.
8503///
8504/// \returns a new FieldDecl.
8505///
8506/// \todo The Declarator argument is a hack. It will be removed once
8507FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8508                                TypeSourceInfo *TInfo,
8509                                RecordDecl *Record, SourceLocation Loc,
8510                                bool Mutable, Expr *BitWidth, bool HasInit,
8511                                SourceLocation TSSL,
8512                                AccessSpecifier AS, NamedDecl *PrevDecl,
8513                                Declarator *D) {
8514  IdentifierInfo *II = Name.getAsIdentifierInfo();
8515  bool InvalidDecl = false;
8516  if (D) InvalidDecl = D->isInvalidType();
8517
8518  // If we receive a broken type, recover by assuming 'int' and
8519  // marking this declaration as invalid.
8520  if (T.isNull()) {
8521    InvalidDecl = true;
8522    T = Context.IntTy;
8523  }
8524
8525  QualType EltTy = Context.getBaseElementType(T);
8526  if (!EltTy->isDependentType() &&
8527      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8528    // Fields of incomplete type force their record to be invalid.
8529    Record->setInvalidDecl();
8530    InvalidDecl = true;
8531  }
8532
8533  // C99 6.7.2.1p8: A member of a structure or union may have any type other
8534  // than a variably modified type.
8535  if (!InvalidDecl && T->isVariablyModifiedType()) {
8536    bool SizeIsNegative;
8537    llvm::APSInt Oversized;
8538    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8539                                                           SizeIsNegative,
8540                                                           Oversized);
8541    if (!FixedTy.isNull()) {
8542      Diag(Loc, diag::warn_illegal_constant_array_size);
8543      T = FixedTy;
8544    } else {
8545      if (SizeIsNegative)
8546        Diag(Loc, diag::err_typecheck_negative_array_size);
8547      else if (Oversized.getBoolValue())
8548        Diag(Loc, diag::err_array_too_large)
8549          << Oversized.toString(10);
8550      else
8551        Diag(Loc, diag::err_typecheck_field_variable_size);
8552      InvalidDecl = true;
8553    }
8554  }
8555
8556  // Fields can not have abstract class types
8557  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8558                                             diag::err_abstract_type_in_decl,
8559                                             AbstractFieldType))
8560    InvalidDecl = true;
8561
8562  bool ZeroWidth = false;
8563  // If this is declared as a bit-field, check the bit-field.
8564  if (!InvalidDecl && BitWidth &&
8565      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
8566    InvalidDecl = true;
8567    BitWidth = 0;
8568    ZeroWidth = false;
8569  }
8570
8571  // Check that 'mutable' is consistent with the type of the declaration.
8572  if (!InvalidDecl && Mutable) {
8573    unsigned DiagID = 0;
8574    if (T->isReferenceType())
8575      DiagID = diag::err_mutable_reference;
8576    else if (T.isConstQualified())
8577      DiagID = diag::err_mutable_const;
8578
8579    if (DiagID) {
8580      SourceLocation ErrLoc = Loc;
8581      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
8582        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
8583      Diag(ErrLoc, DiagID);
8584      Mutable = false;
8585      InvalidDecl = true;
8586    }
8587  }
8588
8589  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
8590                                       BitWidth, Mutable, HasInit);
8591  if (InvalidDecl)
8592    NewFD->setInvalidDecl();
8593
8594  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
8595    Diag(Loc, diag::err_duplicate_member) << II;
8596    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8597    NewFD->setInvalidDecl();
8598  }
8599
8600  if (!InvalidDecl && getLangOptions().CPlusPlus) {
8601    if (Record->isUnion()) {
8602      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8603        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8604        if (RDecl->getDefinition()) {
8605          // C++ [class.union]p1: An object of a class with a non-trivial
8606          // constructor, a non-trivial copy constructor, a non-trivial
8607          // destructor, or a non-trivial copy assignment operator
8608          // cannot be a member of a union, nor can an array of such
8609          // objects.
8610          if (CheckNontrivialField(NewFD))
8611            NewFD->setInvalidDecl();
8612        }
8613      }
8614
8615      // C++ [class.union]p1: If a union contains a member of reference type,
8616      // the program is ill-formed.
8617      if (EltTy->isReferenceType()) {
8618        Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
8619          << NewFD->getDeclName() << EltTy;
8620        NewFD->setInvalidDecl();
8621      }
8622    }
8623  }
8624
8625  // FIXME: We need to pass in the attributes given an AST
8626  // representation, not a parser representation.
8627  if (D)
8628    // FIXME: What to pass instead of TUScope?
8629    ProcessDeclAttributes(TUScope, NewFD, *D);
8630
8631  // In auto-retain/release, infer strong retension for fields of
8632  // retainable type.
8633  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
8634    NewFD->setInvalidDecl();
8635
8636  if (T.isObjCGCWeak())
8637    Diag(Loc, diag::warn_attribute_weak_on_field);
8638
8639  NewFD->setAccess(AS);
8640  return NewFD;
8641}
8642
8643bool Sema::CheckNontrivialField(FieldDecl *FD) {
8644  assert(FD);
8645  assert(getLangOptions().CPlusPlus && "valid check only for C++");
8646
8647  if (FD->isInvalidDecl())
8648    return true;
8649
8650  QualType EltTy = Context.getBaseElementType(FD->getType());
8651  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
8652    CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
8653    if (RDecl->getDefinition()) {
8654      // We check for copy constructors before constructors
8655      // because otherwise we'll never get complaints about
8656      // copy constructors.
8657
8658      CXXSpecialMember member = CXXInvalid;
8659      if (!RDecl->hasTrivialCopyConstructor())
8660        member = CXXCopyConstructor;
8661      else if (!RDecl->hasTrivialDefaultConstructor())
8662        member = CXXDefaultConstructor;
8663      else if (!RDecl->hasTrivialCopyAssignment())
8664        member = CXXCopyAssignment;
8665      else if (!RDecl->hasTrivialDestructor())
8666        member = CXXDestructor;
8667
8668      if (member != CXXInvalid) {
8669        if (!getLangOptions().CPlusPlus0x &&
8670            getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
8671          // Objective-C++ ARC: it is an error to have a non-trivial field of
8672          // a union. However, system headers in Objective-C programs
8673          // occasionally have Objective-C lifetime objects within unions,
8674          // and rather than cause the program to fail, we make those
8675          // members unavailable.
8676          SourceLocation Loc = FD->getLocation();
8677          if (getSourceManager().isInSystemHeader(Loc)) {
8678            if (!FD->hasAttr<UnavailableAttr>())
8679              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
8680                                  "this system field has retaining ownership"));
8681            return false;
8682          }
8683        }
8684
8685        Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ?
8686               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
8687               diag::err_illegal_union_or_anon_struct_member)
8688          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
8689        DiagnoseNontrivial(RT, member);
8690        return !getLangOptions().CPlusPlus0x;
8691      }
8692    }
8693  }
8694
8695  return false;
8696}
8697
8698/// DiagnoseNontrivial - Given that a class has a non-trivial
8699/// special member, figure out why.
8700void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
8701  QualType QT(T, 0U);
8702  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
8703
8704  // Check whether the member was user-declared.
8705  switch (member) {
8706  case CXXInvalid:
8707    break;
8708
8709  case CXXDefaultConstructor:
8710    if (RD->hasUserDeclaredConstructor()) {
8711      typedef CXXRecordDecl::ctor_iterator ctor_iter;
8712      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
8713        const FunctionDecl *body = 0;
8714        ci->hasBody(body);
8715        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
8716          SourceLocation CtorLoc = ci->getLocation();
8717          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8718          return;
8719        }
8720      }
8721
8722      llvm_unreachable("found no user-declared constructors");
8723    }
8724    break;
8725
8726  case CXXCopyConstructor:
8727    if (RD->hasUserDeclaredCopyConstructor()) {
8728      SourceLocation CtorLoc =
8729        RD->getCopyConstructor(0)->getLocation();
8730      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8731      return;
8732    }
8733    break;
8734
8735  case CXXMoveConstructor:
8736    if (RD->hasUserDeclaredMoveConstructor()) {
8737      SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
8738      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8739      return;
8740    }
8741    break;
8742
8743  case CXXCopyAssignment:
8744    if (RD->hasUserDeclaredCopyAssignment()) {
8745      // FIXME: this should use the location of the copy
8746      // assignment, not the type.
8747      SourceLocation TyLoc = RD->getSourceRange().getBegin();
8748      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
8749      return;
8750    }
8751    break;
8752
8753  case CXXMoveAssignment:
8754    if (RD->hasUserDeclaredMoveAssignment()) {
8755      SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
8756      Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
8757      return;
8758    }
8759    break;
8760
8761  case CXXDestructor:
8762    if (RD->hasUserDeclaredDestructor()) {
8763      SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
8764      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8765      return;
8766    }
8767    break;
8768  }
8769
8770  typedef CXXRecordDecl::base_class_iterator base_iter;
8771
8772  // Virtual bases and members inhibit trivial copying/construction,
8773  // but not trivial destruction.
8774  if (member != CXXDestructor) {
8775    // Check for virtual bases.  vbases includes indirect virtual bases,
8776    // so we just iterate through the direct bases.
8777    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8778      if (bi->isVirtual()) {
8779        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8780        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8781        return;
8782      }
8783
8784    // Check for virtual methods.
8785    typedef CXXRecordDecl::method_iterator meth_iter;
8786    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8787         ++mi) {
8788      if (mi->isVirtual()) {
8789        SourceLocation MLoc = mi->getSourceRange().getBegin();
8790        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8791        return;
8792      }
8793    }
8794  }
8795
8796  bool (CXXRecordDecl::*hasTrivial)() const;
8797  switch (member) {
8798  case CXXDefaultConstructor:
8799    hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
8800  case CXXCopyConstructor:
8801    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8802  case CXXCopyAssignment:
8803    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8804  case CXXDestructor:
8805    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8806  default:
8807    llvm_unreachable("unexpected special member");
8808  }
8809
8810  // Check for nontrivial bases (and recurse).
8811  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
8812    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
8813    assert(BaseRT && "Don't know how to handle dependent bases");
8814    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8815    if (!(BaseRecTy->*hasTrivial)()) {
8816      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8817      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8818      DiagnoseNontrivial(BaseRT, member);
8819      return;
8820    }
8821  }
8822
8823  // Check for nontrivial members (and recurse).
8824  typedef RecordDecl::field_iterator field_iter;
8825  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8826       ++fi) {
8827    QualType EltTy = Context.getBaseElementType((*fi)->getType());
8828    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
8829      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8830
8831      if (!(EltRD->*hasTrivial)()) {
8832        SourceLocation FLoc = (*fi)->getLocation();
8833        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8834        DiagnoseNontrivial(EltRT, member);
8835        return;
8836      }
8837    }
8838
8839    if (EltTy->isObjCLifetimeType()) {
8840      switch (EltTy.getObjCLifetime()) {
8841      case Qualifiers::OCL_None:
8842      case Qualifiers::OCL_ExplicitNone:
8843        break;
8844
8845      case Qualifiers::OCL_Autoreleasing:
8846      case Qualifiers::OCL_Weak:
8847      case Qualifiers::OCL_Strong:
8848        Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
8849          << QT << EltTy.getObjCLifetime();
8850        return;
8851      }
8852    }
8853  }
8854
8855  llvm_unreachable("found no explanation for non-trivial member");
8856}
8857
8858/// TranslateIvarVisibility - Translate visibility from a token ID to an
8859///  AST enum value.
8860static ObjCIvarDecl::AccessControl
8861TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
8862  switch (ivarVisibility) {
8863  default: llvm_unreachable("Unknown visitibility kind");
8864  case tok::objc_private: return ObjCIvarDecl::Private;
8865  case tok::objc_public: return ObjCIvarDecl::Public;
8866  case tok::objc_protected: return ObjCIvarDecl::Protected;
8867  case tok::objc_package: return ObjCIvarDecl::Package;
8868  }
8869}
8870
8871/// ActOnIvar - Each ivar field of an objective-c class is passed into this
8872/// in order to create an IvarDecl object for it.
8873Decl *Sema::ActOnIvar(Scope *S,
8874                                SourceLocation DeclStart,
8875                                Declarator &D, Expr *BitfieldWidth,
8876                                tok::ObjCKeywordKind Visibility) {
8877
8878  IdentifierInfo *II = D.getIdentifier();
8879  Expr *BitWidth = (Expr*)BitfieldWidth;
8880  SourceLocation Loc = DeclStart;
8881  if (II) Loc = D.getIdentifierLoc();
8882
8883  // FIXME: Unnamed fields can be handled in various different ways, for
8884  // example, unnamed unions inject all members into the struct namespace!
8885
8886  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8887  QualType T = TInfo->getType();
8888
8889  if (BitWidth) {
8890    // 6.7.2.1p3, 6.7.2.1p4
8891    if (VerifyBitField(Loc, II, T, BitWidth)) {
8892      D.setInvalidType();
8893      BitWidth = 0;
8894    }
8895  } else {
8896    // Not a bitfield.
8897
8898    // validate II.
8899
8900  }
8901  if (T->isReferenceType()) {
8902    Diag(Loc, diag::err_ivar_reference_type);
8903    D.setInvalidType();
8904  }
8905  // C99 6.7.2.1p8: A member of a structure or union may have any type other
8906  // than a variably modified type.
8907  else if (T->isVariablyModifiedType()) {
8908    Diag(Loc, diag::err_typecheck_ivar_variable_size);
8909    D.setInvalidType();
8910  }
8911
8912  // Get the visibility (access control) for this ivar.
8913  ObjCIvarDecl::AccessControl ac =
8914    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8915                                        : ObjCIvarDecl::None;
8916  // Must set ivar's DeclContext to its enclosing interface.
8917  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
8918  ObjCContainerDecl *EnclosingContext;
8919  if (ObjCImplementationDecl *IMPDecl =
8920      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
8921    if (!LangOpts.ObjCNonFragileABI2) {
8922    // Case of ivar declared in an implementation. Context is that of its class.
8923      EnclosingContext = IMPDecl->getClassInterface();
8924      assert(EnclosingContext && "Implementation has no class interface!");
8925    }
8926    else
8927      EnclosingContext = EnclosingDecl;
8928  } else {
8929    if (ObjCCategoryDecl *CDecl =
8930        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8931      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8932        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
8933        return 0;
8934      }
8935    }
8936    EnclosingContext = EnclosingDecl;
8937  }
8938
8939  // Construct the decl.
8940  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8941                                             DeclStart, Loc, II, T,
8942                                             TInfo, ac, (Expr *)BitfieldWidth);
8943
8944  if (II) {
8945    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
8946                                           ForRedeclaration);
8947    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
8948        && !isa<TagDecl>(PrevDecl)) {
8949      Diag(Loc, diag::err_duplicate_member) << II;
8950      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8951      NewID->setInvalidDecl();
8952    }
8953  }
8954
8955  // Process attributes attached to the ivar.
8956  ProcessDeclAttributes(S, NewID, D);
8957
8958  if (D.isInvalidType())
8959    NewID->setInvalidDecl();
8960
8961  // In ARC, infer 'retaining' for ivars of retainable type.
8962  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
8963    NewID->setInvalidDecl();
8964
8965  if (D.getDeclSpec().isModulePrivateSpecified())
8966    NewID->setModulePrivate();
8967
8968  if (II) {
8969    // FIXME: When interfaces are DeclContexts, we'll need to add
8970    // these to the interface.
8971    S->AddDecl(NewID);
8972    IdResolver.AddDecl(NewID);
8973  }
8974
8975  return NewID;
8976}
8977
8978/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
8979/// class and class extensions. For every class @interface and class
8980/// extension @interface, if the last ivar is a bitfield of any type,
8981/// then add an implicit `char :0` ivar to the end of that interface.
8982void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
8983                             SmallVectorImpl<Decl *> &AllIvarDecls) {
8984  if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
8985    return;
8986
8987  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
8988  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
8989
8990  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
8991    return;
8992  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
8993  if (!ID) {
8994    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
8995      if (!CD->IsClassExtension())
8996        return;
8997    }
8998    // No need to add this to end of @implementation.
8999    else
9000      return;
9001  }
9002  // All conditions are met. Add a new bitfield to the tail end of ivars.
9003  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9004  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9005
9006  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9007                              DeclLoc, DeclLoc, 0,
9008                              Context.CharTy,
9009                              Context.getTrivialTypeSourceInfo(Context.CharTy,
9010                                                               DeclLoc),
9011                              ObjCIvarDecl::Private, BW,
9012                              true);
9013  AllIvarDecls.push_back(Ivar);
9014}
9015
9016void Sema::ActOnFields(Scope* S,
9017                       SourceLocation RecLoc, Decl *EnclosingDecl,
9018                       llvm::ArrayRef<Decl *> Fields,
9019                       SourceLocation LBrac, SourceLocation RBrac,
9020                       AttributeList *Attr) {
9021  assert(EnclosingDecl && "missing record or interface decl");
9022
9023  // If the decl this is being inserted into is invalid, then it may be a
9024  // redeclaration or some other bogus case.  Don't try to add fields to it.
9025  if (EnclosingDecl->isInvalidDecl())
9026    return;
9027
9028  // Verify that all the fields are okay.
9029  unsigned NumNamedMembers = 0;
9030  SmallVector<FieldDecl*, 32> RecFields;
9031
9032  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9033  bool ARCErrReported = false;
9034  for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9035       i != end; ++i) {
9036    FieldDecl *FD = cast<FieldDecl>(*i);
9037
9038    // Get the type for the field.
9039    const Type *FDTy = FD->getType().getTypePtr();
9040
9041    if (!FD->isAnonymousStructOrUnion()) {
9042      // Remember all fields written by the user.
9043      RecFields.push_back(FD);
9044    }
9045
9046    // If the field is already invalid for some reason, don't emit more
9047    // diagnostics about it.
9048    if (FD->isInvalidDecl()) {
9049      EnclosingDecl->setInvalidDecl();
9050      continue;
9051    }
9052
9053    // C99 6.7.2.1p2:
9054    //   A structure or union shall not contain a member with
9055    //   incomplete or function type (hence, a structure shall not
9056    //   contain an instance of itself, but may contain a pointer to
9057    //   an instance of itself), except that the last member of a
9058    //   structure with more than one named member may have incomplete
9059    //   array type; such a structure (and any union containing,
9060    //   possibly recursively, a member that is such a structure)
9061    //   shall not be a member of a structure or an element of an
9062    //   array.
9063    if (FDTy->isFunctionType()) {
9064      // Field declared as a function.
9065      Diag(FD->getLocation(), diag::err_field_declared_as_function)
9066        << FD->getDeclName();
9067      FD->setInvalidDecl();
9068      EnclosingDecl->setInvalidDecl();
9069      continue;
9070    } else if (FDTy->isIncompleteArrayType() && Record &&
9071               ((i + 1 == Fields.end() && !Record->isUnion()) ||
9072                ((getLangOptions().MicrosoftExt ||
9073                  getLangOptions().CPlusPlus) &&
9074                 (i + 1 == Fields.end() || Record->isUnion())))) {
9075      // Flexible array member.
9076      // Microsoft and g++ is more permissive regarding flexible array.
9077      // It will accept flexible array in union and also
9078      // as the sole element of a struct/class.
9079      if (getLangOptions().MicrosoftExt) {
9080        if (Record->isUnion())
9081          Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9082            << FD->getDeclName();
9083        else if (Fields.size() == 1)
9084          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9085            << FD->getDeclName() << Record->getTagKind();
9086      } else if (getLangOptions().CPlusPlus) {
9087        if (Record->isUnion())
9088          Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9089            << FD->getDeclName();
9090        else if (Fields.size() == 1)
9091          Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9092            << FD->getDeclName() << Record->getTagKind();
9093      } else if (NumNamedMembers < 1) {
9094        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9095          << FD->getDeclName();
9096        FD->setInvalidDecl();
9097        EnclosingDecl->setInvalidDecl();
9098        continue;
9099      }
9100      if (!FD->getType()->isDependentType() &&
9101          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9102        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9103          << FD->getDeclName() << FD->getType();
9104        FD->setInvalidDecl();
9105        EnclosingDecl->setInvalidDecl();
9106        continue;
9107      }
9108      // Okay, we have a legal flexible array member at the end of the struct.
9109      if (Record)
9110        Record->setHasFlexibleArrayMember(true);
9111    } else if (!FDTy->isDependentType() &&
9112               RequireCompleteType(FD->getLocation(), FD->getType(),
9113                                   diag::err_field_incomplete)) {
9114      // Incomplete type
9115      FD->setInvalidDecl();
9116      EnclosingDecl->setInvalidDecl();
9117      continue;
9118    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9119      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9120        // If this is a member of a union, then entire union becomes "flexible".
9121        if (Record && Record->isUnion()) {
9122          Record->setHasFlexibleArrayMember(true);
9123        } else {
9124          // If this is a struct/class and this is not the last element, reject
9125          // it.  Note that GCC supports variable sized arrays in the middle of
9126          // structures.
9127          if (i + 1 != Fields.end())
9128            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9129              << FD->getDeclName() << FD->getType();
9130          else {
9131            // We support flexible arrays at the end of structs in
9132            // other structs as an extension.
9133            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9134              << FD->getDeclName();
9135            if (Record)
9136              Record->setHasFlexibleArrayMember(true);
9137          }
9138        }
9139      }
9140      if (Record && FDTTy->getDecl()->hasObjectMember())
9141        Record->setHasObjectMember(true);
9142    } else if (FDTy->isObjCObjectType()) {
9143      /// A field cannot be an Objective-c object
9144      Diag(FD->getLocation(), diag::err_statically_allocated_object)
9145        << FixItHint::CreateInsertion(FD->getLocation(), "*");
9146      QualType T = Context.getObjCObjectPointerType(FD->getType());
9147      FD->setType(T);
9148    }
9149    else if (!getLangOptions().CPlusPlus) {
9150      if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
9151        // It's an error in ARC if a field has lifetime.
9152        // We don't want to report this in a system header, though,
9153        // so we just make the field unavailable.
9154        // FIXME: that's really not sufficient; we need to make the type
9155        // itself invalid to, say, initialize or copy.
9156        QualType T = FD->getType();
9157        Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9158        if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9159          SourceLocation loc = FD->getLocation();
9160          if (getSourceManager().isInSystemHeader(loc)) {
9161            if (!FD->hasAttr<UnavailableAttr>()) {
9162              FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9163                                "this system field has retaining ownership"));
9164            }
9165          } else {
9166            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
9167          }
9168          ARCErrReported = true;
9169        }
9170      }
9171      else if (getLangOptions().ObjC1 &&
9172               getLangOptions().getGC() != LangOptions::NonGC &&
9173               Record && !Record->hasObjectMember()) {
9174        if (FD->getType()->isObjCObjectPointerType() ||
9175            FD->getType().isObjCGCStrong())
9176          Record->setHasObjectMember(true);
9177        else if (Context.getAsArrayType(FD->getType())) {
9178          QualType BaseType = Context.getBaseElementType(FD->getType());
9179          if (BaseType->isRecordType() &&
9180              BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9181            Record->setHasObjectMember(true);
9182          else if (BaseType->isObjCObjectPointerType() ||
9183                   BaseType.isObjCGCStrong())
9184                 Record->setHasObjectMember(true);
9185        }
9186      }
9187    }
9188    // Keep track of the number of named members.
9189    if (FD->getIdentifier())
9190      ++NumNamedMembers;
9191  }
9192
9193  // Okay, we successfully defined 'Record'.
9194  if (Record) {
9195    bool Completed = false;
9196    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9197      if (!CXXRecord->isInvalidDecl()) {
9198        // Set access bits correctly on the directly-declared conversions.
9199        UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9200        for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9201             I != E; ++I)
9202          Convs->setAccess(I, (*I)->getAccess());
9203
9204        if (!CXXRecord->isDependentType()) {
9205          // Objective-C Automatic Reference Counting:
9206          //   If a class has a non-static data member of Objective-C pointer
9207          //   type (or array thereof), it is a non-POD type and its
9208          //   default constructor (if any), copy constructor, copy assignment
9209          //   operator, and destructor are non-trivial.
9210          //
9211          // This rule is also handled by CXXRecordDecl::completeDefinition().
9212          // However, here we check whether this particular class is only
9213          // non-POD because of the presence of an Objective-C pointer member.
9214          // If so, objects of this type cannot be shared between code compiled
9215          // with instant objects and code compiled with manual retain/release.
9216          if (getLangOptions().ObjCAutoRefCount &&
9217              CXXRecord->hasObjectMember() &&
9218              CXXRecord->getLinkage() == ExternalLinkage) {
9219            if (CXXRecord->isPOD()) {
9220              Diag(CXXRecord->getLocation(),
9221                   diag::warn_arc_non_pod_class_with_object_member)
9222               << CXXRecord;
9223            } else {
9224              // FIXME: Fix-Its would be nice here, but finding a good location
9225              // for them is going to be tricky.
9226              if (CXXRecord->hasTrivialCopyConstructor())
9227                Diag(CXXRecord->getLocation(),
9228                     diag::warn_arc_trivial_member_function_with_object_member)
9229                  << CXXRecord << 0;
9230              if (CXXRecord->hasTrivialCopyAssignment())
9231                Diag(CXXRecord->getLocation(),
9232                     diag::warn_arc_trivial_member_function_with_object_member)
9233                << CXXRecord << 1;
9234              if (CXXRecord->hasTrivialDestructor())
9235                Diag(CXXRecord->getLocation(),
9236                     diag::warn_arc_trivial_member_function_with_object_member)
9237                << CXXRecord << 2;
9238            }
9239          }
9240
9241          // Adjust user-defined destructor exception spec.
9242          if (getLangOptions().CPlusPlus0x &&
9243              CXXRecord->hasUserDeclaredDestructor())
9244            AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9245
9246          // Add any implicitly-declared members to this class.
9247          AddImplicitlyDeclaredMembersToClass(CXXRecord);
9248
9249          // If we have virtual base classes, we may end up finding multiple
9250          // final overriders for a given virtual function. Check for this
9251          // problem now.
9252          if (CXXRecord->getNumVBases()) {
9253            CXXFinalOverriderMap FinalOverriders;
9254            CXXRecord->getFinalOverriders(FinalOverriders);
9255
9256            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9257                                             MEnd = FinalOverriders.end();
9258                 M != MEnd; ++M) {
9259              for (OverridingMethods::iterator SO = M->second.begin(),
9260                                            SOEnd = M->second.end();
9261                   SO != SOEnd; ++SO) {
9262                assert(SO->second.size() > 0 &&
9263                       "Virtual function without overridding functions?");
9264                if (SO->second.size() == 1)
9265                  continue;
9266
9267                // C++ [class.virtual]p2:
9268                //   In a derived class, if a virtual member function of a base
9269                //   class subobject has more than one final overrider the
9270                //   program is ill-formed.
9271                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9272                  << (NamedDecl *)M->first << Record;
9273                Diag(M->first->getLocation(),
9274                     diag::note_overridden_virtual_function);
9275                for (OverridingMethods::overriding_iterator
9276                          OM = SO->second.begin(),
9277                       OMEnd = SO->second.end();
9278                     OM != OMEnd; ++OM)
9279                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
9280                    << (NamedDecl *)M->first << OM->Method->getParent();
9281
9282                Record->setInvalidDecl();
9283              }
9284            }
9285            CXXRecord->completeDefinition(&FinalOverriders);
9286            Completed = true;
9287          }
9288        }
9289      }
9290    }
9291
9292    if (!Completed)
9293      Record->completeDefinition();
9294
9295    // Now that the record is complete, do any delayed exception spec checks
9296    // we were missing.
9297    while (!DelayedDestructorExceptionSpecChecks.empty()) {
9298      const CXXDestructorDecl *Dtor =
9299              DelayedDestructorExceptionSpecChecks.back().first;
9300      if (Dtor->getParent() != Record)
9301        break;
9302
9303      assert(!Dtor->getParent()->isDependentType() &&
9304          "Should not ever add destructors of templates into the list.");
9305      CheckOverridingFunctionExceptionSpec(Dtor,
9306          DelayedDestructorExceptionSpecChecks.back().second);
9307      DelayedDestructorExceptionSpecChecks.pop_back();
9308    }
9309
9310  } else {
9311    ObjCIvarDecl **ClsFields =
9312      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9313    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9314      ID->setLocEnd(RBrac);
9315      // Add ivar's to class's DeclContext.
9316      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9317        ClsFields[i]->setLexicalDeclContext(ID);
9318        ID->addDecl(ClsFields[i]);
9319      }
9320      // Must enforce the rule that ivars in the base classes may not be
9321      // duplicates.
9322      if (ID->getSuperClass())
9323        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9324    } else if (ObjCImplementationDecl *IMPDecl =
9325                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9326      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9327      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9328        // Ivar declared in @implementation never belongs to the implementation.
9329        // Only it is in implementation's lexical context.
9330        ClsFields[I]->setLexicalDeclContext(IMPDecl);
9331      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9332    } else if (ObjCCategoryDecl *CDecl =
9333                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9334      // case of ivars in class extension; all other cases have been
9335      // reported as errors elsewhere.
9336      // FIXME. Class extension does not have a LocEnd field.
9337      // CDecl->setLocEnd(RBrac);
9338      // Add ivar's to class extension's DeclContext.
9339      // Diagnose redeclaration of private ivars.
9340      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9341      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9342        if (IDecl) {
9343          if (const ObjCIvarDecl *ClsIvar =
9344              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9345            Diag(ClsFields[i]->getLocation(),
9346                 diag::err_duplicate_ivar_declaration);
9347            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9348            continue;
9349          }
9350          for (const ObjCCategoryDecl *ClsExtDecl =
9351                IDecl->getFirstClassExtension();
9352               ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9353            if (const ObjCIvarDecl *ClsExtIvar =
9354                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9355              Diag(ClsFields[i]->getLocation(),
9356                   diag::err_duplicate_ivar_declaration);
9357              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9358              continue;
9359            }
9360          }
9361        }
9362        ClsFields[i]->setLexicalDeclContext(CDecl);
9363        CDecl->addDecl(ClsFields[i]);
9364      }
9365    }
9366  }
9367
9368  if (Attr)
9369    ProcessDeclAttributeList(S, Record, Attr);
9370
9371  // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9372  // set the visibility of this record.
9373  if (Record && !Record->getDeclContext()->isRecord())
9374    AddPushedVisibilityAttribute(Record);
9375}
9376
9377/// \brief Determine whether the given integral value is representable within
9378/// the given type T.
9379static bool isRepresentableIntegerValue(ASTContext &Context,
9380                                        llvm::APSInt &Value,
9381                                        QualType T) {
9382  assert(T->isIntegralType(Context) && "Integral type required!");
9383  unsigned BitWidth = Context.getIntWidth(T);
9384
9385  if (Value.isUnsigned() || Value.isNonNegative()) {
9386    if (T->isSignedIntegerOrEnumerationType())
9387      --BitWidth;
9388    return Value.getActiveBits() <= BitWidth;
9389  }
9390  return Value.getMinSignedBits() <= BitWidth;
9391}
9392
9393// \brief Given an integral type, return the next larger integral type
9394// (or a NULL type of no such type exists).
9395static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9396  // FIXME: Int128/UInt128 support, which also needs to be introduced into
9397  // enum checking below.
9398  assert(T->isIntegralType(Context) && "Integral type required!");
9399  const unsigned NumTypes = 4;
9400  QualType SignedIntegralTypes[NumTypes] = {
9401    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9402  };
9403  QualType UnsignedIntegralTypes[NumTypes] = {
9404    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9405    Context.UnsignedLongLongTy
9406  };
9407
9408  unsigned BitWidth = Context.getTypeSize(T);
9409  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9410                                                        : UnsignedIntegralTypes;
9411  for (unsigned I = 0; I != NumTypes; ++I)
9412    if (Context.getTypeSize(Types[I]) > BitWidth)
9413      return Types[I];
9414
9415  return QualType();
9416}
9417
9418EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9419                                          EnumConstantDecl *LastEnumConst,
9420                                          SourceLocation IdLoc,
9421                                          IdentifierInfo *Id,
9422                                          Expr *Val) {
9423  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9424  llvm::APSInt EnumVal(IntWidth);
9425  QualType EltTy;
9426
9427  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9428    Val = 0;
9429
9430  if (Val) {
9431    if (Enum->isDependentType() || Val->isTypeDependent())
9432      EltTy = Context.DependentTy;
9433    else {
9434      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9435      SourceLocation ExpLoc;
9436      if (!Val->isValueDependent() &&
9437          VerifyIntegerConstantExpression(Val, &EnumVal)) {
9438        Val = 0;
9439      } else {
9440        if (!getLangOptions().CPlusPlus) {
9441          // C99 6.7.2.2p2:
9442          //   The expression that defines the value of an enumeration constant
9443          //   shall be an integer constant expression that has a value
9444          //   representable as an int.
9445
9446          // Complain if the value is not representable in an int.
9447          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9448            Diag(IdLoc, diag::ext_enum_value_not_int)
9449              << EnumVal.toString(10) << Val->getSourceRange()
9450              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9451          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9452            // Force the type of the expression to 'int'.
9453            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9454          }
9455        }
9456
9457        if (Enum->isFixed()) {
9458          EltTy = Enum->getIntegerType();
9459
9460          // C++0x [dcl.enum]p5:
9461          //   ... if the initializing value of an enumerator cannot be
9462          //   represented by the underlying type, the program is ill-formed.
9463          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9464            if (getLangOptions().MicrosoftExt) {
9465              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9466              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9467            } else
9468              Diag(IdLoc, diag::err_enumerator_too_large)
9469                << EltTy;
9470          } else
9471            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9472        }
9473        else {
9474          // C++0x [dcl.enum]p5:
9475          //   If the underlying type is not fixed, the type of each enumerator
9476          //   is the type of its initializing value:
9477          //     - If an initializer is specified for an enumerator, the
9478          //       initializing value has the same type as the expression.
9479          EltTy = Val->getType();
9480        }
9481      }
9482    }
9483  }
9484
9485  if (!Val) {
9486    if (Enum->isDependentType())
9487      EltTy = Context.DependentTy;
9488    else if (!LastEnumConst) {
9489      // C++0x [dcl.enum]p5:
9490      //   If the underlying type is not fixed, the type of each enumerator
9491      //   is the type of its initializing value:
9492      //     - If no initializer is specified for the first enumerator, the
9493      //       initializing value has an unspecified integral type.
9494      //
9495      // GCC uses 'int' for its unspecified integral type, as does
9496      // C99 6.7.2.2p3.
9497      if (Enum->isFixed()) {
9498        EltTy = Enum->getIntegerType();
9499      }
9500      else {
9501        EltTy = Context.IntTy;
9502      }
9503    } else {
9504      // Assign the last value + 1.
9505      EnumVal = LastEnumConst->getInitVal();
9506      ++EnumVal;
9507      EltTy = LastEnumConst->getType();
9508
9509      // Check for overflow on increment.
9510      if (EnumVal < LastEnumConst->getInitVal()) {
9511        // C++0x [dcl.enum]p5:
9512        //   If the underlying type is not fixed, the type of each enumerator
9513        //   is the type of its initializing value:
9514        //
9515        //     - Otherwise the type of the initializing value is the same as
9516        //       the type of the initializing value of the preceding enumerator
9517        //       unless the incremented value is not representable in that type,
9518        //       in which case the type is an unspecified integral type
9519        //       sufficient to contain the incremented value. If no such type
9520        //       exists, the program is ill-formed.
9521        QualType T = getNextLargerIntegralType(Context, EltTy);
9522        if (T.isNull() || Enum->isFixed()) {
9523          // There is no integral type larger enough to represent this
9524          // value. Complain, then allow the value to wrap around.
9525          EnumVal = LastEnumConst->getInitVal();
9526          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
9527          ++EnumVal;
9528          if (Enum->isFixed())
9529            // When the underlying type is fixed, this is ill-formed.
9530            Diag(IdLoc, diag::err_enumerator_wrapped)
9531              << EnumVal.toString(10)
9532              << EltTy;
9533          else
9534            Diag(IdLoc, diag::warn_enumerator_too_large)
9535              << EnumVal.toString(10);
9536        } else {
9537          EltTy = T;
9538        }
9539
9540        // Retrieve the last enumerator's value, extent that type to the
9541        // type that is supposed to be large enough to represent the incremented
9542        // value, then increment.
9543        EnumVal = LastEnumConst->getInitVal();
9544        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9545        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
9546        ++EnumVal;
9547
9548        // If we're not in C++, diagnose the overflow of enumerator values,
9549        // which in C99 means that the enumerator value is not representable in
9550        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
9551        // permits enumerator values that are representable in some larger
9552        // integral type.
9553        if (!getLangOptions().CPlusPlus && !T.isNull())
9554          Diag(IdLoc, diag::warn_enum_value_overflow);
9555      } else if (!getLangOptions().CPlusPlus &&
9556                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9557        // Enforce C99 6.7.2.2p2 even when we compute the next value.
9558        Diag(IdLoc, diag::ext_enum_value_not_int)
9559          << EnumVal.toString(10) << 1;
9560      }
9561    }
9562  }
9563
9564  if (!EltTy->isDependentType()) {
9565    // Make the enumerator value match the signedness and size of the
9566    // enumerator's type.
9567    EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
9568    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
9569  }
9570
9571  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
9572                                  Val, EnumVal);
9573}
9574
9575
9576Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
9577                              SourceLocation IdLoc, IdentifierInfo *Id,
9578                              AttributeList *Attr,
9579                              SourceLocation EqualLoc, Expr *val) {
9580  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
9581  EnumConstantDecl *LastEnumConst =
9582    cast_or_null<EnumConstantDecl>(lastEnumConst);
9583  Expr *Val = static_cast<Expr*>(val);
9584
9585  // The scope passed in may not be a decl scope.  Zip up the scope tree until
9586  // we find one that is.
9587  S = getNonFieldDeclScope(S);
9588
9589  // Verify that there isn't already something declared with this name in this
9590  // scope.
9591  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
9592                                         ForRedeclaration);
9593  if (PrevDecl && PrevDecl->isTemplateParameter()) {
9594    // Maybe we will complain about the shadowed template parameter.
9595    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
9596    // Just pretend that we didn't see the previous declaration.
9597    PrevDecl = 0;
9598  }
9599
9600  if (PrevDecl) {
9601    // When in C++, we may get a TagDecl with the same name; in this case the
9602    // enum constant will 'hide' the tag.
9603    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
9604           "Received TagDecl when not in C++!");
9605    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
9606      if (isa<EnumConstantDecl>(PrevDecl))
9607        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
9608      else
9609        Diag(IdLoc, diag::err_redefinition) << Id;
9610      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9611      return 0;
9612    }
9613  }
9614
9615  // C++ [class.mem]p13:
9616  //   If T is the name of a class, then each of the following shall have a
9617  //   name different from T:
9618  //     - every enumerator of every member of class T that is an enumerated
9619  //       type
9620  if (CXXRecordDecl *Record
9621                      = dyn_cast<CXXRecordDecl>(
9622                             TheEnumDecl->getDeclContext()->getRedeclContext()))
9623    if (Record->getIdentifier() && Record->getIdentifier() == Id)
9624      Diag(IdLoc, diag::err_member_name_of_class) << Id;
9625
9626  EnumConstantDecl *New =
9627    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
9628
9629  if (New) {
9630    // Process attributes.
9631    if (Attr) ProcessDeclAttributeList(S, New, Attr);
9632
9633    // Register this decl in the current scope stack.
9634    New->setAccess(TheEnumDecl->getAccess());
9635    PushOnScopeChains(New, S);
9636  }
9637
9638  return New;
9639}
9640
9641void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
9642                         SourceLocation RBraceLoc, Decl *EnumDeclX,
9643                         Decl **Elements, unsigned NumElements,
9644                         Scope *S, AttributeList *Attr) {
9645  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
9646  QualType EnumType = Context.getTypeDeclType(Enum);
9647
9648  if (Attr)
9649    ProcessDeclAttributeList(S, Enum, Attr);
9650
9651  if (Enum->isDependentType()) {
9652    for (unsigned i = 0; i != NumElements; ++i) {
9653      EnumConstantDecl *ECD =
9654        cast_or_null<EnumConstantDecl>(Elements[i]);
9655      if (!ECD) continue;
9656
9657      ECD->setType(EnumType);
9658    }
9659
9660    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
9661    return;
9662  }
9663
9664  // TODO: If the result value doesn't fit in an int, it must be a long or long
9665  // long value.  ISO C does not support this, but GCC does as an extension,
9666  // emit a warning.
9667  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9668  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
9669  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
9670
9671  // Verify that all the values are okay, compute the size of the values, and
9672  // reverse the list.
9673  unsigned NumNegativeBits = 0;
9674  unsigned NumPositiveBits = 0;
9675
9676  // Keep track of whether all elements have type int.
9677  bool AllElementsInt = true;
9678
9679  for (unsigned i = 0; i != NumElements; ++i) {
9680    EnumConstantDecl *ECD =
9681      cast_or_null<EnumConstantDecl>(Elements[i]);
9682    if (!ECD) continue;  // Already issued a diagnostic.
9683
9684    const llvm::APSInt &InitVal = ECD->getInitVal();
9685
9686    // Keep track of the size of positive and negative values.
9687    if (InitVal.isUnsigned() || InitVal.isNonNegative())
9688      NumPositiveBits = std::max(NumPositiveBits,
9689                                 (unsigned)InitVal.getActiveBits());
9690    else
9691      NumNegativeBits = std::max(NumNegativeBits,
9692                                 (unsigned)InitVal.getMinSignedBits());
9693
9694    // Keep track of whether every enum element has type int (very commmon).
9695    if (AllElementsInt)
9696      AllElementsInt = ECD->getType() == Context.IntTy;
9697  }
9698
9699  // Figure out the type that should be used for this enum.
9700  QualType BestType;
9701  unsigned BestWidth;
9702
9703  // C++0x N3000 [conv.prom]p3:
9704  //   An rvalue of an unscoped enumeration type whose underlying
9705  //   type is not fixed can be converted to an rvalue of the first
9706  //   of the following types that can represent all the values of
9707  //   the enumeration: int, unsigned int, long int, unsigned long
9708  //   int, long long int, or unsigned long long int.
9709  // C99 6.4.4.3p2:
9710  //   An identifier declared as an enumeration constant has type int.
9711  // The C99 rule is modified by a gcc extension
9712  QualType BestPromotionType;
9713
9714  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
9715  // -fshort-enums is the equivalent to specifying the packed attribute on all
9716  // enum definitions.
9717  if (LangOpts.ShortEnums)
9718    Packed = true;
9719
9720  if (Enum->isFixed()) {
9721    BestType = Enum->getIntegerType();
9722    if (BestType->isPromotableIntegerType())
9723      BestPromotionType = Context.getPromotedIntegerType(BestType);
9724    else
9725      BestPromotionType = BestType;
9726    // We don't need to set BestWidth, because BestType is going to be the type
9727    // of the enumerators, but we do anyway because otherwise some compilers
9728    // warn that it might be used uninitialized.
9729    BestWidth = CharWidth;
9730  }
9731  else if (NumNegativeBits) {
9732    // If there is a negative value, figure out the smallest integer type (of
9733    // int/long/longlong) that fits.
9734    // If it's packed, check also if it fits a char or a short.
9735    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
9736      BestType = Context.SignedCharTy;
9737      BestWidth = CharWidth;
9738    } else if (Packed && NumNegativeBits <= ShortWidth &&
9739               NumPositiveBits < ShortWidth) {
9740      BestType = Context.ShortTy;
9741      BestWidth = ShortWidth;
9742    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
9743      BestType = Context.IntTy;
9744      BestWidth = IntWidth;
9745    } else {
9746      BestWidth = Context.getTargetInfo().getLongWidth();
9747
9748      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
9749        BestType = Context.LongTy;
9750      } else {
9751        BestWidth = Context.getTargetInfo().getLongLongWidth();
9752
9753        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
9754          Diag(Enum->getLocation(), diag::warn_enum_too_large);
9755        BestType = Context.LongLongTy;
9756      }
9757    }
9758    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
9759  } else {
9760    // If there is no negative value, figure out the smallest type that fits
9761    // all of the enumerator values.
9762    // If it's packed, check also if it fits a char or a short.
9763    if (Packed && NumPositiveBits <= CharWidth) {
9764      BestType = Context.UnsignedCharTy;
9765      BestPromotionType = Context.IntTy;
9766      BestWidth = CharWidth;
9767    } else if (Packed && NumPositiveBits <= ShortWidth) {
9768      BestType = Context.UnsignedShortTy;
9769      BestPromotionType = Context.IntTy;
9770      BestWidth = ShortWidth;
9771    } else if (NumPositiveBits <= IntWidth) {
9772      BestType = Context.UnsignedIntTy;
9773      BestWidth = IntWidth;
9774      BestPromotionType
9775        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9776                           ? Context.UnsignedIntTy : Context.IntTy;
9777    } else if (NumPositiveBits <=
9778               (BestWidth = Context.getTargetInfo().getLongWidth())) {
9779      BestType = Context.UnsignedLongTy;
9780      BestPromotionType
9781        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9782                           ? Context.UnsignedLongTy : Context.LongTy;
9783    } else {
9784      BestWidth = Context.getTargetInfo().getLongLongWidth();
9785      assert(NumPositiveBits <= BestWidth &&
9786             "How could an initializer get larger than ULL?");
9787      BestType = Context.UnsignedLongLongTy;
9788      BestPromotionType
9789        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9790                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
9791    }
9792  }
9793
9794  // Loop over all of the enumerator constants, changing their types to match
9795  // the type of the enum if needed.
9796  for (unsigned i = 0; i != NumElements; ++i) {
9797    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
9798    if (!ECD) continue;  // Already issued a diagnostic.
9799
9800    // Standard C says the enumerators have int type, but we allow, as an
9801    // extension, the enumerators to be larger than int size.  If each
9802    // enumerator value fits in an int, type it as an int, otherwise type it the
9803    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
9804    // that X has type 'int', not 'unsigned'.
9805
9806    // Determine whether the value fits into an int.
9807    llvm::APSInt InitVal = ECD->getInitVal();
9808
9809    // If it fits into an integer type, force it.  Otherwise force it to match
9810    // the enum decl type.
9811    QualType NewTy;
9812    unsigned NewWidth;
9813    bool NewSign;
9814    if (!getLangOptions().CPlusPlus &&
9815        !Enum->isFixed() &&
9816        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
9817      NewTy = Context.IntTy;
9818      NewWidth = IntWidth;
9819      NewSign = true;
9820    } else if (ECD->getType() == BestType) {
9821      // Already the right type!
9822      if (getLangOptions().CPlusPlus)
9823        // C++ [dcl.enum]p4: Following the closing brace of an
9824        // enum-specifier, each enumerator has the type of its
9825        // enumeration.
9826        ECD->setType(EnumType);
9827      continue;
9828    } else {
9829      NewTy = BestType;
9830      NewWidth = BestWidth;
9831      NewSign = BestType->isSignedIntegerOrEnumerationType();
9832    }
9833
9834    // Adjust the APSInt value.
9835    InitVal = InitVal.extOrTrunc(NewWidth);
9836    InitVal.setIsSigned(NewSign);
9837    ECD->setInitVal(InitVal);
9838
9839    // Adjust the Expr initializer and type.
9840    if (ECD->getInitExpr() &&
9841        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
9842      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
9843                                                CK_IntegralCast,
9844                                                ECD->getInitExpr(),
9845                                                /*base paths*/ 0,
9846                                                VK_RValue));
9847    if (getLangOptions().CPlusPlus)
9848      // C++ [dcl.enum]p4: Following the closing brace of an
9849      // enum-specifier, each enumerator has the type of its
9850      // enumeration.
9851      ECD->setType(EnumType);
9852    else
9853      ECD->setType(NewTy);
9854  }
9855
9856  Enum->completeDefinition(BestType, BestPromotionType,
9857                           NumPositiveBits, NumNegativeBits);
9858}
9859
9860Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9861                                  SourceLocation StartLoc,
9862                                  SourceLocation EndLoc) {
9863  StringLiteral *AsmString = cast<StringLiteral>(expr);
9864
9865  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
9866                                                   AsmString, StartLoc,
9867                                                   EndLoc);
9868  CurContext->addDecl(New);
9869  return New;
9870}
9871
9872DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc,
9873                                   IdentifierInfo &ModuleName,
9874                                   SourceLocation ModuleNameLoc) {
9875  ModuleKey Module = PP.getModuleLoader().loadModule(ImportLoc,
9876                                                     ModuleName, ModuleNameLoc);
9877  if (!Module)
9878    return true;
9879
9880  // FIXME: Actually create a declaration to describe the module import.
9881  (void)Module;
9882  return DeclResult((Decl *)0);
9883}
9884
9885void
9886Sema::diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old,
9887                                         SourceLocation ModulePrivateKeyword) {
9888  assert(!Old->isModulePrivate() && "Old is module-private!");
9889
9890  Diag(New->getLocation(), diag::err_module_private_follows_public)
9891    << New->getDeclName() << SourceRange(ModulePrivateKeyword);
9892  Diag(Old->getLocation(), diag::note_previous_declaration)
9893    << Old->getDeclName();
9894
9895  // Drop the __module_private__ from the new declaration, since it's invalid.
9896  New->setModulePrivate(false);
9897}
9898
9899void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9900                             SourceLocation PragmaLoc,
9901                             SourceLocation NameLoc) {
9902  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
9903
9904  if (PrevDecl) {
9905    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
9906  } else {
9907    (void)WeakUndeclaredIdentifiers.insert(
9908      std::pair<IdentifierInfo*,WeakInfo>
9909        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
9910  }
9911}
9912
9913void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9914                                IdentifierInfo* AliasName,
9915                                SourceLocation PragmaLoc,
9916                                SourceLocation NameLoc,
9917                                SourceLocation AliasNameLoc) {
9918  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9919                                    LookupOrdinaryName);
9920  WeakInfo W = WeakInfo(Name, NameLoc);
9921
9922  if (PrevDecl) {
9923    if (!PrevDecl->hasAttr<AliasAttr>())
9924      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
9925        DeclApplyPragmaWeak(TUScope, ND, W);
9926  } else {
9927    (void)WeakUndeclaredIdentifiers.insert(
9928      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
9929  }
9930}
9931
9932Decl *Sema::getObjCDeclContext() const {
9933  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
9934}
9935
9936AvailabilityResult Sema::getCurContextAvailability() const {
9937  const Decl *D = cast<Decl>(getCurLexicalContext());
9938  // A category implicitly has the availability of the interface.
9939  if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
9940    D = CatD->getClassInterface();
9941
9942  return D->getAvailability();
9943}
9944