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