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