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