SemaDecl.cpp revision 7a1dc562d4ad59237ed9fe7e8cef56f9eaa7a26c
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/AST/CXXInheritance.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/Parse/DeclSpec.h"
28#include "clang/Parse/ParseDiagnostic.h"
29#include "clang/Parse/Template.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Lex/HeaderSearch.h"
36#include "llvm/ADT/BitVector.h"
37#include "llvm/ADT/STLExtras.h"
38#include <algorithm>
39#include <cstring>
40#include <functional>
41#include <queue>
42using namespace clang;
43
44/// getDeclName - Return a pretty name for the specified decl if possible, or
45/// an empty string if not.  This is used for pretty crash reporting.
46std::string Sema::getDeclName(DeclPtrTy d) {
47  Decl *D = d.getAs<Decl>();
48  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
49    return DN->getQualifiedNameAsString();
50  return "";
51}
52
53Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
54  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
55}
56
57/// \brief If the identifier refers to a type name within this scope,
58/// return the declaration of that type.
59///
60/// This routine performs ordinary name lookup of the identifier II
61/// within the given scope, with optional C++ scope specifier SS, to
62/// determine whether the name refers to a type. If so, returns an
63/// opaque pointer (actually a QualType) corresponding to that
64/// type. Otherwise, returns NULL.
65///
66/// If name lookup results in an ambiguity, this routine will complain
67/// and then return NULL.
68Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
69                                Scope *S, const CXXScopeSpec *SS,
70                                bool isClassName,
71                                TypeTy *ObjectTypePtr) {
72  // Determine where we will perform name lookup.
73  DeclContext *LookupCtx = 0;
74  if (ObjectTypePtr) {
75    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
76    if (ObjectType->isRecordType())
77      LookupCtx = computeDeclContext(ObjectType);
78  } else if (SS && SS->isSet()) {
79    LookupCtx = computeDeclContext(*SS, false);
80
81    if (!LookupCtx) {
82      if (isDependentScopeSpecifier(*SS)) {
83        // C++ [temp.res]p3:
84        //   A qualified-id that refers to a type and in which the
85        //   nested-name-specifier depends on a template-parameter (14.6.2)
86        //   shall be prefixed by the keyword typename to indicate that the
87        //   qualified-id denotes a type, forming an
88        //   elaborated-type-specifier (7.1.5.3).
89        //
90        // We therefore do not perform any name lookup if the result would
91        // refer to a member of an unknown specialization.
92        if (!isClassName)
93          return 0;
94
95        // We know from the grammar that this name refers to a type, so build a
96        // TypenameType node to describe the type.
97        // FIXME: Record somewhere that this TypenameType node has no "typename"
98        // keyword associated with it.
99        return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
100                                 II, SS->getRange()).getAsOpaquePtr();
101      }
102
103      return 0;
104    }
105
106    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
107      return 0;
108  }
109
110  LookupResult Result(*this, &II, NameLoc, LookupOrdinaryName);
111  if (LookupCtx) {
112    // Perform "qualified" name lookup into the declaration context we
113    // computed, which is either the type of the base of a member access
114    // expression or the declaration context associated with a prior
115    // nested-name-specifier.
116    LookupQualifiedName(Result, LookupCtx);
117
118    if (ObjectTypePtr && Result.empty()) {
119      // C++ [basic.lookup.classref]p3:
120      //   If the unqualified-id is ~type-name, the type-name is looked up
121      //   in the context of the entire postfix-expression. If the type T of
122      //   the object expression is of a class type C, the type-name is also
123      //   looked up in the scope of class C. At least one of the lookups shall
124      //   find a name that refers to (possibly cv-qualified) T.
125      LookupName(Result, S);
126    }
127  } else {
128    // Perform unqualified name lookup.
129    LookupName(Result, S);
130  }
131
132  NamedDecl *IIDecl = 0;
133  switch (Result.getResultKind()) {
134  case LookupResult::NotFound:
135  case LookupResult::FoundOverloaded:
136  case LookupResult::FoundUnresolvedValue:
137    return 0;
138
139  case LookupResult::Ambiguous:
140    // Recover from type-hiding ambiguities by hiding the type.  We'll
141    // do the lookup again when looking for an object, and we can
142    // diagnose the error then.  If we don't do this, then the error
143    // about hiding the type will be immediately followed by an error
144    // that only makes sense if the identifier was treated like a type.
145    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
146      Result.suppressDiagnostics();
147      return 0;
148    }
149
150    // Look to see if we have a type anywhere in the list of results.
151    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
152         Res != ResEnd; ++Res) {
153      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
154        if (!IIDecl ||
155            (*Res)->getLocation().getRawEncoding() <
156              IIDecl->getLocation().getRawEncoding())
157          IIDecl = *Res;
158      }
159    }
160
161    if (!IIDecl) {
162      // None of the entities we found is a type, so there is no way
163      // to even assume that the result is a type. In this case, don't
164      // complain about the ambiguity. The parser will either try to
165      // perform this lookup again (e.g., as an object name), which
166      // will produce the ambiguity, or will complain that it expected
167      // a type name.
168      Result.suppressDiagnostics();
169      return 0;
170    }
171
172    // We found a type within the ambiguous lookup; diagnose the
173    // ambiguity and then return that type. This might be the right
174    // answer, or it might not be, but it suppresses any attempt to
175    // perform the name lookup again.
176    break;
177
178  case LookupResult::Found:
179    IIDecl = Result.getFoundDecl();
180    break;
181  }
182
183  assert(IIDecl && "Didn't find decl");
184
185  QualType T;
186  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
187    DiagnoseUseOfDecl(IIDecl, NameLoc);
188
189    // C++ [temp.local]p2:
190    //   Within the scope of a class template specialization or
191    //   partial specialization, when the injected-class-name is
192    //   not followed by a <, it is equivalent to the
193    //   injected-class-name followed by the template-argument s
194    //   of the class template specialization or partial
195    //   specialization enclosed in <>.
196    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
197      if (RD->isInjectedClassName())
198        if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
199          T = Template->getInjectedClassNameType(Context);
200
201    if (T.isNull())
202      T = Context.getTypeDeclType(TD);
203
204    if (SS)
205      T = getQualifiedNameType(*SS, T);
206
207  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
208    T = Context.getObjCInterfaceType(IDecl);
209  } else if (UnresolvedUsingTypenameDecl *UUDecl =
210               dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
211    // FIXME: preserve source structure information.
212    T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
213  } else {
214    // If it's not plausibly a type, suppress diagnostics.
215    Result.suppressDiagnostics();
216    return 0;
217  }
218
219  return T.getAsOpaquePtr();
220}
221
222/// isTagName() - This method is called *for error recovery purposes only*
223/// to determine if the specified name is a valid tag name ("struct foo").  If
224/// so, this returns the TST for the tag corresponding to it (TST_enum,
225/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
226/// where the user forgot to specify the tag.
227DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
228  // Do a tag name lookup in this scope.
229  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
230  LookupName(R, S, false);
231  R.suppressDiagnostics();
232  if (R.getResultKind() == LookupResult::Found)
233    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
234      switch (TD->getTagKind()) {
235      case TagDecl::TK_struct: return DeclSpec::TST_struct;
236      case TagDecl::TK_union:  return DeclSpec::TST_union;
237      case TagDecl::TK_class:  return DeclSpec::TST_class;
238      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
239      }
240    }
241
242  return DeclSpec::TST_unspecified;
243}
244
245bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
246                                   SourceLocation IILoc,
247                                   Scope *S,
248                                   const CXXScopeSpec *SS,
249                                   TypeTy *&SuggestedType) {
250  // We don't have anything to suggest (yet).
251  SuggestedType = 0;
252
253  // FIXME: Should we move the logic that tries to recover from a missing tag
254  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
255
256  if (!SS)
257    Diag(IILoc, diag::err_unknown_typename) << &II;
258  else if (DeclContext *DC = computeDeclContext(*SS, false))
259    Diag(IILoc, diag::err_typename_nested_not_found)
260      << &II << DC << SS->getRange();
261  else if (isDependentScopeSpecifier(*SS)) {
262    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
263      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
264      << SourceRange(SS->getRange().getBegin(), IILoc)
265      << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
266                                               "typename ");
267    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
268  } else {
269    assert(SS && SS->isInvalid() &&
270           "Invalid scope specifier has already been diagnosed");
271  }
272
273  return true;
274}
275
276// Determines the context to return to after temporarily entering a
277// context.  This depends in an unnecessarily complicated way on the
278// exact ordering of callbacks from the parser.
279DeclContext *Sema::getContainingDC(DeclContext *DC) {
280
281  // Functions defined inline within classes aren't parsed until we've
282  // finished parsing the top-level class, so the top-level class is
283  // the context we'll need to return to.
284  if (isa<FunctionDecl>(DC)) {
285    DC = DC->getLexicalParent();
286
287    // A function not defined within a class will always return to its
288    // lexical context.
289    if (!isa<CXXRecordDecl>(DC))
290      return DC;
291
292    // A C++ inline method/friend is parsed *after* the topmost class
293    // it was declared in is fully parsed ("complete");  the topmost
294    // class is the context we need to return to.
295    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
296      DC = RD;
297
298    // Return the declaration context of the topmost class the inline method is
299    // declared in.
300    return DC;
301  }
302
303  if (isa<ObjCMethodDecl>(DC))
304    return Context.getTranslationUnitDecl();
305
306  return DC->getLexicalParent();
307}
308
309void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
310  assert(getContainingDC(DC) == CurContext &&
311      "The next DeclContext should be lexically contained in the current one.");
312  CurContext = DC;
313  S->setEntity(DC);
314}
315
316void Sema::PopDeclContext() {
317  assert(CurContext && "DeclContext imbalance!");
318
319  CurContext = getContainingDC(CurContext);
320}
321
322/// EnterDeclaratorContext - Used when we must lookup names in the context
323/// of a declarator's nested name specifier.
324///
325void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
326  // C++0x [basic.lookup.unqual]p13:
327  //   A name used in the definition of a static data member of class
328  //   X (after the qualified-id of the static member) is looked up as
329  //   if the name was used in a member function of X.
330  // C++0x [basic.lookup.unqual]p14:
331  //   If a variable member of a namespace is defined outside of the
332  //   scope of its namespace then any name used in the definition of
333  //   the variable member (after the declarator-id) is looked up as
334  //   if the definition of the variable member occurred in its
335  //   namespace.
336  // Both of these imply that we should push a scope whose context
337  // is the semantic context of the declaration.  We can't use
338  // PushDeclContext here because that context is not necessarily
339  // lexically contained in the current context.  Fortunately,
340  // the containing scope should have the appropriate information.
341
342  assert(!S->getEntity() && "scope already has entity");
343
344#ifndef NDEBUG
345  Scope *Ancestor = S->getParent();
346  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
347  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
348#endif
349
350  CurContext = DC;
351  S->setEntity(DC);
352}
353
354void Sema::ExitDeclaratorContext(Scope *S) {
355  assert(S->getEntity() == CurContext && "Context imbalance!");
356
357  // Switch back to the lexical context.  The safety of this is
358  // enforced by an assert in EnterDeclaratorContext.
359  Scope *Ancestor = S->getParent();
360  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
361  CurContext = (DeclContext*) Ancestor->getEntity();
362
363  // We don't need to do anything with the scope, which is going to
364  // disappear.
365}
366
367/// \brief Determine whether we allow overloading of the function
368/// PrevDecl with another declaration.
369///
370/// This routine determines whether overloading is possible, not
371/// whether some new function is actually an overload. It will return
372/// true in C++ (where we can always provide overloads) or, as an
373/// extension, in C when the previous function is already an
374/// overloaded function declaration or has the "overloadable"
375/// attribute.
376static bool AllowOverloadingOfFunction(LookupResult &Previous,
377                                       ASTContext &Context) {
378  if (Context.getLangOptions().CPlusPlus)
379    return true;
380
381  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
382    return true;
383
384  return (Previous.getResultKind() == LookupResult::Found
385          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
386}
387
388/// Add this decl to the scope shadowed decl chains.
389void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
390  // Move up the scope chain until we find the nearest enclosing
391  // non-transparent context. The declaration will be introduced into this
392  // scope.
393  while (S->getEntity() &&
394         ((DeclContext *)S->getEntity())->isTransparentContext())
395    S = S->getParent();
396
397  // Add scoped declarations into their context, so that they can be
398  // found later. Declarations without a context won't be inserted
399  // into any context.
400  if (AddToContext)
401    CurContext->addDecl(D);
402
403  // Out-of-line function and variable definitions should not be pushed into
404  // scope.
405  if ((isa<FunctionTemplateDecl>(D) &&
406       cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
407      (isa<FunctionDecl>(D) &&
408       (cast<FunctionDecl>(D)->isFunctionTemplateSpecialization() ||
409        cast<FunctionDecl>(D)->isOutOfLine())) ||
410      (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
411    return;
412
413  // If this replaces anything in the current scope,
414  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
415                               IEnd = IdResolver.end();
416  for (; I != IEnd; ++I) {
417    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
418      S->RemoveDecl(DeclPtrTy::make(*I));
419      IdResolver.RemoveDecl(*I);
420
421      // Should only need to replace one decl.
422      break;
423    }
424  }
425
426  S->AddDecl(DeclPtrTy::make(D));
427  IdResolver.AddDecl(D);
428}
429
430bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
431  return IdResolver.isDeclInScope(D, Ctx, Context, S);
432}
433
434static bool isOutOfScopePreviousDeclaration(NamedDecl *,
435                                            DeclContext*,
436                                            ASTContext&);
437
438/// Filters out lookup results that don't fall within the given scope
439/// as determined by isDeclInScope.
440static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
441                                 DeclContext *Ctx, Scope *S,
442                                 bool ConsiderLinkage) {
443  LookupResult::Filter F = R.makeFilter();
444  while (F.hasNext()) {
445    NamedDecl *D = F.next();
446
447    if (SemaRef.isDeclInScope(D, Ctx, S))
448      continue;
449
450    if (ConsiderLinkage &&
451        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
452      continue;
453
454    F.erase();
455  }
456
457  F.done();
458}
459
460static bool isUsingDecl(NamedDecl *D) {
461  return isa<UsingShadowDecl>(D) ||
462         isa<UnresolvedUsingTypenameDecl>(D) ||
463         isa<UnresolvedUsingValueDecl>(D);
464}
465
466/// Removes using shadow declarations from the lookup results.
467static void RemoveUsingDecls(LookupResult &R) {
468  LookupResult::Filter F = R.makeFilter();
469  while (F.hasNext())
470    if (isUsingDecl(F.next()))
471      F.erase();
472
473  F.done();
474}
475
476static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
477  if (D->isUsed() || D->hasAttr<UnusedAttr>())
478    return false;
479
480  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
481    if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
482      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
483        if (!RD->hasTrivialConstructor())
484          return false;
485        if (!RD->hasTrivialDestructor())
486          return false;
487      }
488    }
489  }
490
491  return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
492          !isa<ImplicitParamDecl>(D) &&
493          D->getDeclContext()->isFunctionOrMethod());
494}
495
496void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
497  if (S->decl_empty()) return;
498  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
499         "Scope shouldn't contain decls!");
500
501  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
502       I != E; ++I) {
503    Decl *TmpD = (*I).getAs<Decl>();
504    assert(TmpD && "This decl didn't get pushed??");
505
506    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
507    NamedDecl *D = cast<NamedDecl>(TmpD);
508
509    if (!D->getDeclName()) continue;
510
511    // Diagnose unused variables in this scope.
512    if (ShouldDiagnoseUnusedDecl(D))
513      Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
514
515    // Remove this name from our lexical scope.
516    IdResolver.RemoveDecl(D);
517  }
518}
519
520/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
521/// return 0 if one not found.
522ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
523  // The third "scope" argument is 0 since we aren't enabling lazy built-in
524  // creation from this context.
525  NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
526
527  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
528}
529
530/// getNonFieldDeclScope - Retrieves the innermost scope, starting
531/// from S, where a non-field would be declared. This routine copes
532/// with the difference between C and C++ scoping rules in structs and
533/// unions. For example, the following code is well-formed in C but
534/// ill-formed in C++:
535/// @code
536/// struct S6 {
537///   enum { BAR } e;
538/// };
539///
540/// void test_S6() {
541///   struct S6 a;
542///   a.e = BAR;
543/// }
544/// @endcode
545/// For the declaration of BAR, this routine will return a different
546/// scope. The scope S will be the scope of the unnamed enumeration
547/// within S6. In C++, this routine will return the scope associated
548/// with S6, because the enumeration's scope is a transparent
549/// context but structures can contain non-field names. In C, this
550/// routine will return the translation unit scope, since the
551/// enumeration's scope is a transparent context and structures cannot
552/// contain non-field names.
553Scope *Sema::getNonFieldDeclScope(Scope *S) {
554  while (((S->getFlags() & Scope::DeclScope) == 0) ||
555         (S->getEntity() &&
556          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
557         (S->isClassScope() && !getLangOptions().CPlusPlus))
558    S = S->getParent();
559  return S;
560}
561
562void Sema::InitBuiltinVaListType() {
563  if (!Context.getBuiltinVaListType().isNull())
564    return;
565
566  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
567  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
568  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
569  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
570}
571
572/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
573/// file scope.  lazily create a decl for it. ForRedeclaration is true
574/// if we're creating this built-in in anticipation of redeclaring the
575/// built-in.
576NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
577                                     Scope *S, bool ForRedeclaration,
578                                     SourceLocation Loc) {
579  Builtin::ID BID = (Builtin::ID)bid;
580
581  if (Context.BuiltinInfo.hasVAListUse(BID))
582    InitBuiltinVaListType();
583
584  ASTContext::GetBuiltinTypeError Error;
585  QualType R = Context.GetBuiltinType(BID, Error);
586  switch (Error) {
587  case ASTContext::GE_None:
588    // Okay
589    break;
590
591  case ASTContext::GE_Missing_stdio:
592    if (ForRedeclaration)
593      Diag(Loc, diag::err_implicit_decl_requires_stdio)
594        << Context.BuiltinInfo.GetName(BID);
595    return 0;
596
597  case ASTContext::GE_Missing_setjmp:
598    if (ForRedeclaration)
599      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
600        << Context.BuiltinInfo.GetName(BID);
601    return 0;
602  }
603
604  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
605    Diag(Loc, diag::ext_implicit_lib_function_decl)
606      << Context.BuiltinInfo.GetName(BID)
607      << R;
608    if (Context.BuiltinInfo.getHeaderName(BID) &&
609        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
610          != Diagnostic::Ignored)
611      Diag(Loc, diag::note_please_include_header)
612        << Context.BuiltinInfo.getHeaderName(BID)
613        << Context.BuiltinInfo.GetName(BID);
614  }
615
616  FunctionDecl *New = FunctionDecl::Create(Context,
617                                           Context.getTranslationUnitDecl(),
618                                           Loc, II, R, /*TInfo=*/0,
619                                           FunctionDecl::Extern, false,
620                                           /*hasPrototype=*/true);
621  New->setImplicit();
622
623  // Create Decl objects for each parameter, adding them to the
624  // FunctionDecl.
625  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
626    llvm::SmallVector<ParmVarDecl*, 16> Params;
627    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
628      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
629                                           FT->getArgType(i), /*TInfo=*/0,
630                                           VarDecl::None, 0));
631    New->setParams(Context, Params.data(), Params.size());
632  }
633
634  AddKnownFunctionAttributes(New);
635
636  // TUScope is the translation-unit scope to insert this function into.
637  // FIXME: This is hideous. We need to teach PushOnScopeChains to
638  // relate Scopes to DeclContexts, and probably eliminate CurContext
639  // entirely, but we're not there yet.
640  DeclContext *SavedContext = CurContext;
641  CurContext = Context.getTranslationUnitDecl();
642  PushOnScopeChains(New, TUScope);
643  CurContext = SavedContext;
644  return New;
645}
646
647/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
648/// same name and scope as a previous declaration 'Old'.  Figure out
649/// how to resolve this situation, merging decls or emitting
650/// diagnostics as appropriate. If there was an error, set New to be invalid.
651///
652void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
653  // If the new decl is known invalid already, don't bother doing any
654  // merging checks.
655  if (New->isInvalidDecl()) return;
656
657  // Allow multiple definitions for ObjC built-in typedefs.
658  // FIXME: Verify the underlying types are equivalent!
659  if (getLangOptions().ObjC1) {
660    const IdentifierInfo *TypeID = New->getIdentifier();
661    switch (TypeID->getLength()) {
662    default: break;
663    case 2:
664      if (!TypeID->isStr("id"))
665        break;
666      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
667      // Install the built-in type for 'id', ignoring the current definition.
668      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
669      return;
670    case 5:
671      if (!TypeID->isStr("Class"))
672        break;
673      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
674      // Install the built-in type for 'Class', ignoring the current definition.
675      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
676      return;
677    case 3:
678      if (!TypeID->isStr("SEL"))
679        break;
680      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
681      // Install the built-in type for 'SEL', ignoring the current definition.
682      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
683      return;
684    case 8:
685      if (!TypeID->isStr("Protocol"))
686        break;
687      Context.setObjCProtoType(New->getUnderlyingType());
688      return;
689    }
690    // Fall through - the typedef name was not a builtin type.
691  }
692
693  // Verify the old decl was also a type.
694  TypeDecl *Old = 0;
695  if (!OldDecls.isSingleResult() ||
696      !(Old = dyn_cast<TypeDecl>(OldDecls.getFoundDecl()))) {
697    Diag(New->getLocation(), diag::err_redefinition_different_kind)
698      << New->getDeclName();
699
700    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
701    if (OldD->getLocation().isValid())
702      Diag(OldD->getLocation(), diag::note_previous_definition);
703
704    return New->setInvalidDecl();
705  }
706
707  // If the old declaration is invalid, just give up here.
708  if (Old->isInvalidDecl())
709    return New->setInvalidDecl();
710
711  // Determine the "old" type we'll use for checking and diagnostics.
712  QualType OldType;
713  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
714    OldType = OldTypedef->getUnderlyingType();
715  else
716    OldType = Context.getTypeDeclType(Old);
717
718  // If the typedef types are not identical, reject them in all languages and
719  // with any extensions enabled.
720
721  if (OldType != New->getUnderlyingType() &&
722      Context.getCanonicalType(OldType) !=
723      Context.getCanonicalType(New->getUnderlyingType())) {
724    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
725      << New->getUnderlyingType() << OldType;
726    if (Old->getLocation().isValid())
727      Diag(Old->getLocation(), diag::note_previous_definition);
728    return New->setInvalidDecl();
729  }
730
731  if (getLangOptions().Microsoft)
732    return;
733
734  // C++ [dcl.typedef]p2:
735  //   In a given non-class scope, a typedef specifier can be used to
736  //   redefine the name of any type declared in that scope to refer
737  //   to the type to which it already refers.
738  if (getLangOptions().CPlusPlus) {
739    if (!isa<CXXRecordDecl>(CurContext))
740      return;
741    Diag(New->getLocation(), diag::err_redefinition)
742      << New->getDeclName();
743    Diag(Old->getLocation(), diag::note_previous_definition);
744    return New->setInvalidDecl();
745  }
746
747  // If we have a redefinition of a typedef in C, emit a warning.  This warning
748  // is normally mapped to an error, but can be controlled with
749  // -Wtypedef-redefinition.  If either the original or the redefinition is
750  // in a system header, don't emit this for compatibility with GCC.
751  if (PP.getDiagnostics().getSuppressSystemWarnings() &&
752      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
753       Context.getSourceManager().isInSystemHeader(New->getLocation())))
754    return;
755
756  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
757    << New->getDeclName();
758  Diag(Old->getLocation(), diag::note_previous_definition);
759  return;
760}
761
762/// DeclhasAttr - returns true if decl Declaration already has the target
763/// attribute.
764static bool
765DeclHasAttr(const Decl *decl, const Attr *target) {
766  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
767    if (attr->getKind() == target->getKind())
768      return true;
769
770  return false;
771}
772
773/// MergeAttributes - append attributes from the Old decl to the New one.
774static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
775  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
776    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
777      Attr *NewAttr = attr->clone(C);
778      NewAttr->setInherited(true);
779      New->addAttr(NewAttr);
780    }
781  }
782}
783
784/// Used in MergeFunctionDecl to keep track of function parameters in
785/// C.
786struct GNUCompatibleParamWarning {
787  ParmVarDecl *OldParm;
788  ParmVarDecl *NewParm;
789  QualType PromotedType;
790};
791
792
793/// getSpecialMember - get the special member enum for a method.
794static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
795                                               const CXXMethodDecl *MD) {
796  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
797    if (Ctor->isDefaultConstructor())
798      return Sema::CXXDefaultConstructor;
799    if (Ctor->isCopyConstructor(Ctx))
800      return Sema::CXXCopyConstructor;
801  }
802
803  if (isa<CXXDestructorDecl>(MD))
804    return Sema::CXXDestructor;
805
806  assert(MD->isCopyAssignment() && "Must have copy assignment operator");
807  return Sema::CXXCopyAssignment;
808}
809
810/// MergeFunctionDecl - We just parsed a function 'New' from
811/// declarator D which has the same name and scope as a previous
812/// declaration 'Old'.  Figure out how to resolve this situation,
813/// merging decls or emitting diagnostics as appropriate.
814///
815/// In C++, New and Old must be declarations that are not
816/// overloaded. Use IsOverload to determine whether New and Old are
817/// overloaded, and to select the Old declaration that New should be
818/// merged with.
819///
820/// Returns true if there was an error, false otherwise.
821bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
822  // Verify the old decl was also a function.
823  FunctionDecl *Old = 0;
824  if (FunctionTemplateDecl *OldFunctionTemplate
825        = dyn_cast<FunctionTemplateDecl>(OldD))
826    Old = OldFunctionTemplate->getTemplatedDecl();
827  else
828    Old = dyn_cast<FunctionDecl>(OldD);
829  if (!Old) {
830    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
831      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
832      Diag(Shadow->getTargetDecl()->getLocation(),
833           diag::note_using_decl_target);
834      Diag(Shadow->getUsingDecl()->getLocation(),
835           diag::note_using_decl) << 0;
836      return true;
837    }
838
839    Diag(New->getLocation(), diag::err_redefinition_different_kind)
840      << New->getDeclName();
841    Diag(OldD->getLocation(), diag::note_previous_definition);
842    return true;
843  }
844
845  // Determine whether the previous declaration was a definition,
846  // implicit declaration, or a declaration.
847  diag::kind PrevDiag;
848  if (Old->isThisDeclarationADefinition())
849    PrevDiag = diag::note_previous_definition;
850  else if (Old->isImplicit())
851    PrevDiag = diag::note_previous_implicit_declaration;
852  else
853    PrevDiag = diag::note_previous_declaration;
854
855  QualType OldQType = Context.getCanonicalType(Old->getType());
856  QualType NewQType = Context.getCanonicalType(New->getType());
857
858  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
859      New->getStorageClass() == FunctionDecl::Static &&
860      Old->getStorageClass() != FunctionDecl::Static) {
861    Diag(New->getLocation(), diag::err_static_non_static)
862      << New;
863    Diag(Old->getLocation(), PrevDiag);
864    return true;
865  }
866
867  if (getLangOptions().CPlusPlus) {
868    // (C++98 13.1p2):
869    //   Certain function declarations cannot be overloaded:
870    //     -- Function declarations that differ only in the return type
871    //        cannot be overloaded.
872    QualType OldReturnType
873      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
874    QualType NewReturnType
875      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
876    if (OldReturnType != NewReturnType) {
877      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
878      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
879      return true;
880    }
881
882    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
883    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
884    if (OldMethod && NewMethod) {
885      if (!NewMethod->getFriendObjectKind() &&
886          NewMethod->getLexicalDeclContext()->isRecord()) {
887        //    -- Member function declarations with the same name and the
888        //       same parameter types cannot be overloaded if any of them
889        //       is a static member function declaration.
890        if (OldMethod->isStatic() || NewMethod->isStatic()) {
891          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
892          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
893          return true;
894        }
895
896        // C++ [class.mem]p1:
897        //   [...] A member shall not be declared twice in the
898        //   member-specification, except that a nested class or member
899        //   class template can be declared and then later defined.
900        unsigned NewDiag;
901        if (isa<CXXConstructorDecl>(OldMethod))
902          NewDiag = diag::err_constructor_redeclared;
903        else if (isa<CXXDestructorDecl>(NewMethod))
904          NewDiag = diag::err_destructor_redeclared;
905        else if (isa<CXXConversionDecl>(NewMethod))
906          NewDiag = diag::err_conv_function_redeclared;
907        else
908          NewDiag = diag::err_member_redeclared;
909
910        Diag(New->getLocation(), NewDiag);
911        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
912      } else {
913        if (OldMethod->isImplicit()) {
914          Diag(NewMethod->getLocation(),
915               diag::err_definition_of_implicitly_declared_member)
916          << New << getSpecialMember(Context, OldMethod);
917
918          Diag(OldMethod->getLocation(),
919               diag::note_previous_implicit_declaration);
920          return true;
921        }
922      }
923    }
924
925    // (C++98 8.3.5p3):
926    //   All declarations for a function shall agree exactly in both the
927    //   return type and the parameter-type-list.
928    if (OldQType == NewQType)
929      return MergeCompatibleFunctionDecls(New, Old);
930
931    // Fall through for conflicting redeclarations and redefinitions.
932  }
933
934  // C: Function types need to be compatible, not identical. This handles
935  // duplicate function decls like "void f(int); void f(enum X);" properly.
936  if (!getLangOptions().CPlusPlus &&
937      Context.typesAreCompatible(OldQType, NewQType)) {
938    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
939    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
940    const FunctionProtoType *OldProto = 0;
941    if (isa<FunctionNoProtoType>(NewFuncType) &&
942        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
943      // The old declaration provided a function prototype, but the
944      // new declaration does not. Merge in the prototype.
945      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
946      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
947                                                 OldProto->arg_type_end());
948      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
949                                         ParamTypes.data(), ParamTypes.size(),
950                                         OldProto->isVariadic(),
951                                         OldProto->getTypeQuals());
952      New->setType(NewQType);
953      New->setHasInheritedPrototype();
954
955      // Synthesize a parameter for each argument type.
956      llvm::SmallVector<ParmVarDecl*, 16> Params;
957      for (FunctionProtoType::arg_type_iterator
958             ParamType = OldProto->arg_type_begin(),
959             ParamEnd = OldProto->arg_type_end();
960           ParamType != ParamEnd; ++ParamType) {
961        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
962                                                 SourceLocation(), 0,
963                                                 *ParamType, /*TInfo=*/0,
964                                                 VarDecl::None, 0);
965        Param->setImplicit();
966        Params.push_back(Param);
967      }
968
969      New->setParams(Context, Params.data(), Params.size());
970    }
971
972    return MergeCompatibleFunctionDecls(New, Old);
973  }
974
975  // GNU C permits a K&R definition to follow a prototype declaration
976  // if the declared types of the parameters in the K&R definition
977  // match the types in the prototype declaration, even when the
978  // promoted types of the parameters from the K&R definition differ
979  // from the types in the prototype. GCC then keeps the types from
980  // the prototype.
981  //
982  // If a variadic prototype is followed by a non-variadic K&R definition,
983  // the K&R definition becomes variadic.  This is sort of an edge case, but
984  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
985  // C99 6.9.1p8.
986  if (!getLangOptions().CPlusPlus &&
987      Old->hasPrototype() && !New->hasPrototype() &&
988      New->getType()->getAs<FunctionProtoType>() &&
989      Old->getNumParams() == New->getNumParams()) {
990    llvm::SmallVector<QualType, 16> ArgTypes;
991    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
992    const FunctionProtoType *OldProto
993      = Old->getType()->getAs<FunctionProtoType>();
994    const FunctionProtoType *NewProto
995      = New->getType()->getAs<FunctionProtoType>();
996
997    // Determine whether this is the GNU C extension.
998    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
999                                               NewProto->getResultType());
1000    bool LooseCompatible = !MergedReturn.isNull();
1001    for (unsigned Idx = 0, End = Old->getNumParams();
1002         LooseCompatible && Idx != End; ++Idx) {
1003      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1004      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1005      if (Context.typesAreCompatible(OldParm->getType(),
1006                                     NewProto->getArgType(Idx))) {
1007        ArgTypes.push_back(NewParm->getType());
1008      } else if (Context.typesAreCompatible(OldParm->getType(),
1009                                            NewParm->getType())) {
1010        GNUCompatibleParamWarning Warn
1011          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1012        Warnings.push_back(Warn);
1013        ArgTypes.push_back(NewParm->getType());
1014      } else
1015        LooseCompatible = false;
1016    }
1017
1018    if (LooseCompatible) {
1019      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1020        Diag(Warnings[Warn].NewParm->getLocation(),
1021             diag::ext_param_promoted_not_compatible_with_prototype)
1022          << Warnings[Warn].PromotedType
1023          << Warnings[Warn].OldParm->getType();
1024        Diag(Warnings[Warn].OldParm->getLocation(),
1025             diag::note_previous_declaration);
1026      }
1027
1028      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1029                                           ArgTypes.size(),
1030                                           OldProto->isVariadic(), 0));
1031      return MergeCompatibleFunctionDecls(New, Old);
1032    }
1033
1034    // Fall through to diagnose conflicting types.
1035  }
1036
1037  // A function that has already been declared has been redeclared or defined
1038  // with a different type- show appropriate diagnostic
1039  if (unsigned BuiltinID = Old->getBuiltinID()) {
1040    // The user has declared a builtin function with an incompatible
1041    // signature.
1042    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1043      // The function the user is redeclaring is a library-defined
1044      // function like 'malloc' or 'printf'. Warn about the
1045      // redeclaration, then pretend that we don't know about this
1046      // library built-in.
1047      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1048      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1049        << Old << Old->getType();
1050      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1051      Old->setInvalidDecl();
1052      return false;
1053    }
1054
1055    PrevDiag = diag::note_previous_builtin_declaration;
1056  }
1057
1058  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1059  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1060  return true;
1061}
1062
1063/// \brief Completes the merge of two function declarations that are
1064/// known to be compatible.
1065///
1066/// This routine handles the merging of attributes and other
1067/// properties of function declarations form the old declaration to
1068/// the new declaration, once we know that New is in fact a
1069/// redeclaration of Old.
1070///
1071/// \returns false
1072bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1073  // Merge the attributes
1074  MergeAttributes(New, Old, Context);
1075
1076  // Merge the storage class.
1077  if (Old->getStorageClass() != FunctionDecl::Extern &&
1078      Old->getStorageClass() != FunctionDecl::None)
1079    New->setStorageClass(Old->getStorageClass());
1080
1081  // Merge "pure" flag.
1082  if (Old->isPure())
1083    New->setPure();
1084
1085  // Merge the "deleted" flag.
1086  if (Old->isDeleted())
1087    New->setDeleted();
1088
1089  if (getLangOptions().CPlusPlus)
1090    return MergeCXXFunctionDecl(New, Old);
1091
1092  return false;
1093}
1094
1095/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1096/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1097/// situation, merging decls or emitting diagnostics as appropriate.
1098///
1099/// Tentative definition rules (C99 6.9.2p2) are checked by
1100/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1101/// definitions here, since the initializer hasn't been attached.
1102///
1103void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1104  // If the new decl is already invalid, don't do any other checking.
1105  if (New->isInvalidDecl())
1106    return;
1107
1108  // Verify the old decl was also a variable.
1109  VarDecl *Old = 0;
1110  if (!Previous.isSingleResult() ||
1111      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1112    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1113      << New->getDeclName();
1114    Diag(Previous.getRepresentativeDecl()->getLocation(),
1115         diag::note_previous_definition);
1116    return New->setInvalidDecl();
1117  }
1118
1119  MergeAttributes(New, Old, Context);
1120
1121  // Merge the types
1122  QualType MergedT;
1123  if (getLangOptions().CPlusPlus) {
1124    if (Context.hasSameType(New->getType(), Old->getType()))
1125      MergedT = New->getType();
1126    // C++ [basic.link]p10:
1127    //   [...] the types specified by all declarations referring to a given
1128    //   object or function shall be identical, except that declarations for an
1129    //   array object can specify array types that differ by the presence or
1130    //   absence of a major array bound (8.3.4).
1131    else if (Old->getType()->isIncompleteArrayType() &&
1132             New->getType()->isArrayType()) {
1133      CanQual<ArrayType> OldArray
1134        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1135      CanQual<ArrayType> NewArray
1136        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1137      if (OldArray->getElementType() == NewArray->getElementType())
1138        MergedT = New->getType();
1139    } else if (Old->getType()->isArrayType() &&
1140             New->getType()->isIncompleteArrayType()) {
1141      CanQual<ArrayType> OldArray
1142        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1143      CanQual<ArrayType> NewArray
1144        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1145      if (OldArray->getElementType() == NewArray->getElementType())
1146        MergedT = Old->getType();
1147    }
1148  } else {
1149    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1150  }
1151  if (MergedT.isNull()) {
1152    Diag(New->getLocation(), diag::err_redefinition_different_type)
1153      << New->getDeclName();
1154    Diag(Old->getLocation(), diag::note_previous_definition);
1155    return New->setInvalidDecl();
1156  }
1157  New->setType(MergedT);
1158
1159  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1160  if (New->getStorageClass() == VarDecl::Static &&
1161      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1162    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1163    Diag(Old->getLocation(), diag::note_previous_definition);
1164    return New->setInvalidDecl();
1165  }
1166  // C99 6.2.2p4:
1167  //   For an identifier declared with the storage-class specifier
1168  //   extern in a scope in which a prior declaration of that
1169  //   identifier is visible,23) if the prior declaration specifies
1170  //   internal or external linkage, the linkage of the identifier at
1171  //   the later declaration is the same as the linkage specified at
1172  //   the prior declaration. If no prior declaration is visible, or
1173  //   if the prior declaration specifies no linkage, then the
1174  //   identifier has external linkage.
1175  if (New->hasExternalStorage() && Old->hasLinkage())
1176    /* Okay */;
1177  else if (New->getStorageClass() != VarDecl::Static &&
1178           Old->getStorageClass() == VarDecl::Static) {
1179    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1180    Diag(Old->getLocation(), diag::note_previous_definition);
1181    return New->setInvalidDecl();
1182  }
1183
1184  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1185
1186  // FIXME: The test for external storage here seems wrong? We still
1187  // need to check for mismatches.
1188  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1189      // Don't complain about out-of-line definitions of static members.
1190      !(Old->getLexicalDeclContext()->isRecord() &&
1191        !New->getLexicalDeclContext()->isRecord())) {
1192    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1193    Diag(Old->getLocation(), diag::note_previous_definition);
1194    return New->setInvalidDecl();
1195  }
1196
1197  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1198    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1199    Diag(Old->getLocation(), diag::note_previous_definition);
1200  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1201    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1202    Diag(Old->getLocation(), diag::note_previous_definition);
1203  }
1204
1205  // Keep a chain of previous declarations.
1206  New->setPreviousDeclaration(Old);
1207}
1208
1209/// CheckFallThrough - Check that we don't fall off the end of a
1210/// Statement that should return a value.
1211///
1212/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1213/// MaybeFallThrough iff we might or might not fall off the end,
1214/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1215/// return.  We assume NeverFallThrough iff we never fall off the end of the
1216/// statement but we may return.  We assume that functions not marked noreturn
1217/// will return.
1218Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1219  // FIXME: Eventually share this CFG object when we have other warnings based
1220  // of the CFG.  This can be done using AnalysisContext.
1221  llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1222
1223  // FIXME: They should never return 0, fix that, delete this code.
1224  if (cfg == 0)
1225    // FIXME: This should be NeverFallThrough
1226    return NeverFallThroughOrReturn;
1227  // The CFG leaves in dead things, and we don't want to dead code paths to
1228  // confuse us, so we mark all live things first.
1229  std::queue<CFGBlock*> workq;
1230  llvm::BitVector live(cfg->getNumBlockIDs());
1231  // Prep work queue
1232  workq.push(&cfg->getEntry());
1233  // Solve
1234  while (!workq.empty()) {
1235    CFGBlock *item = workq.front();
1236    workq.pop();
1237    live.set(item->getBlockID());
1238    for (CFGBlock::succ_iterator I=item->succ_begin(),
1239           E=item->succ_end();
1240         I != E;
1241         ++I) {
1242      if ((*I) && !live[(*I)->getBlockID()]) {
1243        live.set((*I)->getBlockID());
1244        workq.push(*I);
1245      }
1246    }
1247  }
1248
1249  // Now we know what is live, we check the live precessors of the exit block
1250  // and look for fall through paths, being careful to ignore normal returns,
1251  // and exceptional paths.
1252  bool HasLiveReturn = false;
1253  bool HasFakeEdge = false;
1254  bool HasPlainEdge = false;
1255  for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
1256         E = cfg->getExit().pred_end();
1257       I != E;
1258       ++I) {
1259    CFGBlock& B = **I;
1260    if (!live[B.getBlockID()])
1261      continue;
1262    if (B.size() == 0) {
1263      // A labeled empty statement, or the entry block...
1264      HasPlainEdge = true;
1265      continue;
1266    }
1267    Stmt *S = B[B.size()-1];
1268    if (isa<ReturnStmt>(S)) {
1269      HasLiveReturn = true;
1270      continue;
1271    }
1272    if (isa<ObjCAtThrowStmt>(S)) {
1273      HasFakeEdge = true;
1274      continue;
1275    }
1276    if (isa<CXXThrowExpr>(S)) {
1277      HasFakeEdge = true;
1278      continue;
1279    }
1280    bool NoReturnEdge = false;
1281    if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1282      Expr *CEE = C->getCallee()->IgnoreParenCasts();
1283      if (CEE->getType().getNoReturnAttr()) {
1284        NoReturnEdge = true;
1285        HasFakeEdge = true;
1286      } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1287        ValueDecl *VD = DRE->getDecl();
1288        if (VD->hasAttr<NoReturnAttr>()) {
1289          NoReturnEdge = true;
1290          HasFakeEdge = true;
1291        }
1292      }
1293    }
1294    // FIXME: Add noreturn message sends.
1295    if (NoReturnEdge == false)
1296      HasPlainEdge = true;
1297  }
1298  if (!HasPlainEdge) {
1299    if (HasLiveReturn)
1300      return NeverFallThrough;
1301    return NeverFallThroughOrReturn;
1302  }
1303  if (HasFakeEdge || HasLiveReturn)
1304    return MaybeFallThrough;
1305  // This says AlwaysFallThrough for calls to functions that are not marked
1306  // noreturn, that don't return.  If people would like this warning to be more
1307  // accurate, such functions should be marked as noreturn.
1308  return AlwaysFallThrough;
1309}
1310
1311/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1312/// function that should return a value.  Check that we don't fall off the end
1313/// of a noreturn function.  We assume that functions and blocks not marked
1314/// noreturn will return.
1315void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1316  // FIXME: Would be nice if we had a better way to control cascading errors,
1317  // but for now, avoid them.  The problem is that when Parse sees:
1318  //   int foo() { return a; }
1319  // The return is eaten and the Sema code sees just:
1320  //   int foo() { }
1321  // which this code would then warn about.
1322  if (getDiagnostics().hasErrorOccurred())
1323    return;
1324
1325  bool ReturnsVoid = false;
1326  bool HasNoReturn = false;
1327  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1328    // If the result type of the function is a dependent type, we don't know
1329    // whether it will be void or not, so don't
1330    if (FD->getResultType()->isDependentType())
1331      return;
1332    if (FD->getResultType()->isVoidType())
1333      ReturnsVoid = true;
1334    if (FD->hasAttr<NoReturnAttr>())
1335      HasNoReturn = true;
1336  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1337    if (MD->getResultType()->isVoidType())
1338      ReturnsVoid = true;
1339    if (MD->hasAttr<NoReturnAttr>())
1340      HasNoReturn = true;
1341  }
1342
1343  // Short circuit for compilation speed.
1344  if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1345       == Diagnostic::Ignored || ReturnsVoid)
1346      && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1347          == Diagnostic::Ignored || !HasNoReturn)
1348      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1349          == Diagnostic::Ignored || !ReturnsVoid))
1350    return;
1351  // FIXME: Function try block
1352  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1353    switch (CheckFallThrough(Body)) {
1354    case MaybeFallThrough:
1355      if (HasNoReturn)
1356        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1357      else if (!ReturnsVoid)
1358        Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1359      break;
1360    case AlwaysFallThrough:
1361      if (HasNoReturn)
1362        Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1363      else if (!ReturnsVoid)
1364        Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1365      break;
1366    case NeverFallThroughOrReturn:
1367      if (ReturnsVoid && !HasNoReturn)
1368        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1369      break;
1370    case NeverFallThrough:
1371      break;
1372    }
1373  }
1374}
1375
1376/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1377/// that should return a value.  Check that we don't fall off the end of a
1378/// noreturn block.  We assume that functions and blocks not marked noreturn
1379/// will return.
1380void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1381  // FIXME: Would be nice if we had a better way to control cascading errors,
1382  // but for now, avoid them.  The problem is that when Parse sees:
1383  //   int foo() { return a; }
1384  // The return is eaten and the Sema code sees just:
1385  //   int foo() { }
1386  // which this code would then warn about.
1387  if (getDiagnostics().hasErrorOccurred())
1388    return;
1389  bool ReturnsVoid = false;
1390  bool HasNoReturn = false;
1391  if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
1392    if (FT->getResultType()->isVoidType())
1393      ReturnsVoid = true;
1394    if (FT->getNoReturnAttr())
1395      HasNoReturn = true;
1396  }
1397
1398  // Short circuit for compilation speed.
1399  if (ReturnsVoid
1400      && !HasNoReturn
1401      && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1402          == Diagnostic::Ignored || !ReturnsVoid))
1403    return;
1404  // FIXME: Funtion try block
1405  if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1406    switch (CheckFallThrough(Body)) {
1407    case MaybeFallThrough:
1408      if (HasNoReturn)
1409        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1410      else if (!ReturnsVoid)
1411        Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1412      break;
1413    case AlwaysFallThrough:
1414      if (HasNoReturn)
1415        Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1416      else if (!ReturnsVoid)
1417        Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1418      break;
1419    case NeverFallThroughOrReturn:
1420      if (ReturnsVoid)
1421        Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1422      break;
1423    case NeverFallThrough:
1424      break;
1425    }
1426  }
1427}
1428
1429/// CheckParmsForFunctionDef - Check that the parameters of the given
1430/// function are appropriate for the definition of a function. This
1431/// takes care of any checks that cannot be performed on the
1432/// declaration itself, e.g., that the types of each of the function
1433/// parameters are complete.
1434bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1435  bool HasInvalidParm = false;
1436  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1437    ParmVarDecl *Param = FD->getParamDecl(p);
1438
1439    // C99 6.7.5.3p4: the parameters in a parameter type list in a
1440    // function declarator that is part of a function definition of
1441    // that function shall not have incomplete type.
1442    //
1443    // This is also C++ [dcl.fct]p6.
1444    if (!Param->isInvalidDecl() &&
1445        RequireCompleteType(Param->getLocation(), Param->getType(),
1446                               diag::err_typecheck_decl_incomplete_type)) {
1447      Param->setInvalidDecl();
1448      HasInvalidParm = true;
1449    }
1450
1451    // C99 6.9.1p5: If the declarator includes a parameter type list, the
1452    // declaration of each parameter shall include an identifier.
1453    if (Param->getIdentifier() == 0 &&
1454        !Param->isImplicit() &&
1455        !getLangOptions().CPlusPlus)
1456      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1457  }
1458
1459  return HasInvalidParm;
1460}
1461
1462/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1463/// no declarator (e.g. "struct foo;") is parsed.
1464Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1465  // FIXME: Error on auto/register at file scope
1466  // FIXME: Error on inline/virtual/explicit
1467  // FIXME: Warn on useless __thread
1468  // FIXME: Warn on useless const/volatile
1469  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1470  // FIXME: Warn on useless attributes
1471  Decl *TagD = 0;
1472  TagDecl *Tag = 0;
1473  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1474      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1475      DS.getTypeSpecType() == DeclSpec::TST_union ||
1476      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1477    TagD = static_cast<Decl *>(DS.getTypeRep());
1478
1479    if (!TagD) // We probably had an error
1480      return DeclPtrTy();
1481
1482    // Note that the above type specs guarantee that the
1483    // type rep is a Decl, whereas in many of the others
1484    // it's a Type.
1485    Tag = dyn_cast<TagDecl>(TagD);
1486  }
1487
1488  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1489    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1490    // or incomplete types shall not be restrict-qualified."
1491    if (TypeQuals & DeclSpec::TQ_restrict)
1492      Diag(DS.getRestrictSpecLoc(),
1493           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1494           << DS.getSourceRange();
1495  }
1496
1497  if (DS.isFriendSpecified()) {
1498    // If we're dealing with a class template decl, assume that the
1499    // template routines are handling it.
1500    if (TagD && isa<ClassTemplateDecl>(TagD))
1501      return DeclPtrTy();
1502    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1503  }
1504
1505  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1506    // If there are attributes in the DeclSpec, apply them to the record.
1507    if (const AttributeList *AL = DS.getAttributes())
1508      ProcessDeclAttributeList(S, Record, AL);
1509
1510    if (!Record->getDeclName() && Record->isDefinition() &&
1511        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1512      if (getLangOptions().CPlusPlus ||
1513          Record->getDeclContext()->isRecord())
1514        return BuildAnonymousStructOrUnion(S, DS, Record);
1515
1516      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1517        << DS.getSourceRange();
1518    }
1519
1520    // Microsoft allows unnamed struct/union fields. Don't complain
1521    // about them.
1522    // FIXME: Should we support Microsoft's extensions in this area?
1523    if (Record->getDeclName() && getLangOptions().Microsoft)
1524      return DeclPtrTy::make(Tag);
1525  }
1526
1527  if (!DS.isMissingDeclaratorOk() &&
1528      DS.getTypeSpecType() != DeclSpec::TST_error) {
1529    // Warn about typedefs of enums without names, since this is an
1530    // extension in both Microsoft an GNU.
1531    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1532        Tag && isa<EnumDecl>(Tag)) {
1533      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1534        << DS.getSourceRange();
1535      return DeclPtrTy::make(Tag);
1536    }
1537
1538    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1539      << DS.getSourceRange();
1540    return DeclPtrTy();
1541  }
1542
1543  return DeclPtrTy::make(Tag);
1544}
1545
1546/// We are trying to inject an anonymous member into the given scope;
1547/// check if there's an existing declaration that can't be overloaded.
1548///
1549/// \return true if this is a forbidden redeclaration
1550static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1551                                         Scope *S,
1552                                         DeclarationName Name,
1553                                         SourceLocation NameLoc,
1554                                         unsigned diagnostic) {
1555  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1556                 Sema::ForRedeclaration);
1557  if (!SemaRef.LookupName(R, S)) return false;
1558
1559  if (R.getAsSingle<TagDecl>())
1560    return false;
1561
1562  // Pick a representative declaration.
1563  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1564
1565  SemaRef.Diag(NameLoc, diagnostic) << Name;
1566  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1567
1568  return true;
1569}
1570
1571/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1572/// anonymous struct or union AnonRecord into the owning context Owner
1573/// and scope S. This routine will be invoked just after we realize
1574/// that an unnamed union or struct is actually an anonymous union or
1575/// struct, e.g.,
1576///
1577/// @code
1578/// union {
1579///   int i;
1580///   float f;
1581/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1582///    // f into the surrounding scope.x
1583/// @endcode
1584///
1585/// This routine is recursive, injecting the names of nested anonymous
1586/// structs/unions into the owning context and scope as well.
1587bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1588                                               RecordDecl *AnonRecord) {
1589  unsigned diagKind
1590    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1591                            : diag::err_anonymous_struct_member_redecl;
1592
1593  bool Invalid = false;
1594  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1595                               FEnd = AnonRecord->field_end();
1596       F != FEnd; ++F) {
1597    if ((*F)->getDeclName()) {
1598      if (CheckAnonMemberRedeclaration(*this, S, (*F)->getDeclName(),
1599                                       (*F)->getLocation(), diagKind)) {
1600        // C++ [class.union]p2:
1601        //   The names of the members of an anonymous union shall be
1602        //   distinct from the names of any other entity in the
1603        //   scope in which the anonymous union is declared.
1604        Invalid = true;
1605      } else {
1606        // C++ [class.union]p2:
1607        //   For the purpose of name lookup, after the anonymous union
1608        //   definition, the members of the anonymous union are
1609        //   considered to have been defined in the scope in which the
1610        //   anonymous union is declared.
1611        Owner->makeDeclVisibleInContext(*F);
1612        S->AddDecl(DeclPtrTy::make(*F));
1613        IdResolver.AddDecl(*F);
1614      }
1615    } else if (const RecordType *InnerRecordType
1616                 = (*F)->getType()->getAs<RecordType>()) {
1617      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1618      if (InnerRecord->isAnonymousStructOrUnion())
1619        Invalid = Invalid ||
1620          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1621    }
1622  }
1623
1624  return Invalid;
1625}
1626
1627/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1628/// anonymous structure or union. Anonymous unions are a C++ feature
1629/// (C++ [class.union]) and a GNU C extension; anonymous structures
1630/// are a GNU C and GNU C++ extension.
1631Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1632                                                  RecordDecl *Record) {
1633  DeclContext *Owner = Record->getDeclContext();
1634
1635  // Diagnose whether this anonymous struct/union is an extension.
1636  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1637    Diag(Record->getLocation(), diag::ext_anonymous_union);
1638  else if (!Record->isUnion())
1639    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1640
1641  // C and C++ require different kinds of checks for anonymous
1642  // structs/unions.
1643  bool Invalid = false;
1644  if (getLangOptions().CPlusPlus) {
1645    const char* PrevSpec = 0;
1646    unsigned DiagID;
1647    // C++ [class.union]p3:
1648    //   Anonymous unions declared in a named namespace or in the
1649    //   global namespace shall be declared static.
1650    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1651        (isa<TranslationUnitDecl>(Owner) ||
1652         (isa<NamespaceDecl>(Owner) &&
1653          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1654      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1655      Invalid = true;
1656
1657      // Recover by adding 'static'.
1658      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1659                             PrevSpec, DiagID);
1660    }
1661    // C++ [class.union]p3:
1662    //   A storage class is not allowed in a declaration of an
1663    //   anonymous union in a class scope.
1664    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1665             isa<RecordDecl>(Owner)) {
1666      Diag(DS.getStorageClassSpecLoc(),
1667           diag::err_anonymous_union_with_storage_spec);
1668      Invalid = true;
1669
1670      // Recover by removing the storage specifier.
1671      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1672                             PrevSpec, DiagID);
1673    }
1674
1675    // C++ [class.union]p2:
1676    //   The member-specification of an anonymous union shall only
1677    //   define non-static data members. [Note: nested types and
1678    //   functions cannot be declared within an anonymous union. ]
1679    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1680                                 MemEnd = Record->decls_end();
1681         Mem != MemEnd; ++Mem) {
1682      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1683        // C++ [class.union]p3:
1684        //   An anonymous union shall not have private or protected
1685        //   members (clause 11).
1686        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1687          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1688            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1689          Invalid = true;
1690        }
1691      } else if ((*Mem)->isImplicit()) {
1692        // Any implicit members are fine.
1693      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1694        // This is a type that showed up in an
1695        // elaborated-type-specifier inside the anonymous struct or
1696        // union, but which actually declares a type outside of the
1697        // anonymous struct or union. It's okay.
1698      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1699        if (!MemRecord->isAnonymousStructOrUnion() &&
1700            MemRecord->getDeclName()) {
1701          // This is a nested type declaration.
1702          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1703            << (int)Record->isUnion();
1704          Invalid = true;
1705        }
1706      } else {
1707        // We have something that isn't a non-static data
1708        // member. Complain about it.
1709        unsigned DK = diag::err_anonymous_record_bad_member;
1710        if (isa<TypeDecl>(*Mem))
1711          DK = diag::err_anonymous_record_with_type;
1712        else if (isa<FunctionDecl>(*Mem))
1713          DK = diag::err_anonymous_record_with_function;
1714        else if (isa<VarDecl>(*Mem))
1715          DK = diag::err_anonymous_record_with_static;
1716        Diag((*Mem)->getLocation(), DK)
1717            << (int)Record->isUnion();
1718          Invalid = true;
1719      }
1720    }
1721  }
1722
1723  if (!Record->isUnion() && !Owner->isRecord()) {
1724    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1725      << (int)getLangOptions().CPlusPlus;
1726    Invalid = true;
1727  }
1728
1729  // Mock up a declarator.
1730  Declarator Dc(DS, Declarator::TypeNameContext);
1731  TypeSourceInfo *TInfo = 0;
1732  GetTypeForDeclarator(Dc, S, &TInfo);
1733  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1734
1735  // Create a declaration for this anonymous struct/union.
1736  NamedDecl *Anon = 0;
1737  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1738    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1739                             /*IdentifierInfo=*/0,
1740                             Context.getTypeDeclType(Record),
1741                             TInfo,
1742                             /*BitWidth=*/0, /*Mutable=*/false);
1743    Anon->setAccess(AS_public);
1744    if (getLangOptions().CPlusPlus)
1745      FieldCollector->Add(cast<FieldDecl>(Anon));
1746  } else {
1747    VarDecl::StorageClass SC;
1748    switch (DS.getStorageClassSpec()) {
1749    default: assert(0 && "Unknown storage class!");
1750    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1751    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1752    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1753    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1754    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1755    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1756    case DeclSpec::SCS_mutable:
1757      // mutable can only appear on non-static class members, so it's always
1758      // an error here
1759      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1760      Invalid = true;
1761      SC = VarDecl::None;
1762      break;
1763    }
1764
1765    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1766                           /*IdentifierInfo=*/0,
1767                           Context.getTypeDeclType(Record),
1768                           TInfo,
1769                           SC);
1770  }
1771  Anon->setImplicit();
1772
1773  // Add the anonymous struct/union object to the current
1774  // context. We'll be referencing this object when we refer to one of
1775  // its members.
1776  Owner->addDecl(Anon);
1777
1778  // Inject the members of the anonymous struct/union into the owning
1779  // context and into the identifier resolver chain for name lookup
1780  // purposes.
1781  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1782    Invalid = true;
1783
1784  // Mark this as an anonymous struct/union type. Note that we do not
1785  // do this until after we have already checked and injected the
1786  // members of this anonymous struct/union type, because otherwise
1787  // the members could be injected twice: once by DeclContext when it
1788  // builds its lookup table, and once by
1789  // InjectAnonymousStructOrUnionMembers.
1790  Record->setAnonymousStructOrUnion(true);
1791
1792  if (Invalid)
1793    Anon->setInvalidDecl();
1794
1795  return DeclPtrTy::make(Anon);
1796}
1797
1798
1799/// GetNameForDeclarator - Determine the full declaration name for the
1800/// given Declarator.
1801DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1802  return GetNameFromUnqualifiedId(D.getName());
1803}
1804
1805/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1806DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1807  switch (Name.getKind()) {
1808    case UnqualifiedId::IK_Identifier:
1809      return DeclarationName(Name.Identifier);
1810
1811    case UnqualifiedId::IK_OperatorFunctionId:
1812      return Context.DeclarationNames.getCXXOperatorName(
1813                                              Name.OperatorFunctionId.Operator);
1814
1815    case UnqualifiedId::IK_LiteralOperatorId:
1816      return Context.DeclarationNames.getCXXLiteralOperatorName(
1817                                                               Name.Identifier);
1818
1819    case UnqualifiedId::IK_ConversionFunctionId: {
1820      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1821      if (Ty.isNull())
1822        return DeclarationName();
1823
1824      return Context.DeclarationNames.getCXXConversionFunctionName(
1825                                                  Context.getCanonicalType(Ty));
1826    }
1827
1828    case UnqualifiedId::IK_ConstructorName: {
1829      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1830      if (Ty.isNull())
1831        return DeclarationName();
1832
1833      return Context.DeclarationNames.getCXXConstructorName(
1834                                                  Context.getCanonicalType(Ty));
1835    }
1836
1837    case UnqualifiedId::IK_DestructorName: {
1838      QualType Ty = GetTypeFromParser(Name.DestructorName);
1839      if (Ty.isNull())
1840        return DeclarationName();
1841
1842      return Context.DeclarationNames.getCXXDestructorName(
1843                                                           Context.getCanonicalType(Ty));
1844    }
1845
1846    case UnqualifiedId::IK_TemplateId: {
1847      TemplateName TName
1848        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1849      return Context.getNameForTemplate(TName);
1850    }
1851  }
1852
1853  assert(false && "Unknown name kind");
1854  return DeclarationName();
1855}
1856
1857/// isNearlyMatchingFunction - Determine whether the C++ functions
1858/// Declaration and Definition are "nearly" matching. This heuristic
1859/// is used to improve diagnostics in the case where an out-of-line
1860/// function definition doesn't match any declaration within
1861/// the class or namespace.
1862static bool isNearlyMatchingFunction(ASTContext &Context,
1863                                     FunctionDecl *Declaration,
1864                                     FunctionDecl *Definition) {
1865  if (Declaration->param_size() != Definition->param_size())
1866    return false;
1867  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1868    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1869    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1870
1871    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1872                                        DefParamTy.getNonReferenceType()))
1873      return false;
1874  }
1875
1876  return true;
1877}
1878
1879Sema::DeclPtrTy
1880Sema::HandleDeclarator(Scope *S, Declarator &D,
1881                       MultiTemplateParamsArg TemplateParamLists,
1882                       bool IsFunctionDefinition) {
1883  DeclarationName Name = GetNameForDeclarator(D);
1884
1885  // All of these full declarators require an identifier.  If it doesn't have
1886  // one, the ParsedFreeStandingDeclSpec action should be used.
1887  if (!Name) {
1888    if (!D.isInvalidType())  // Reject this if we think it is valid.
1889      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1890           diag::err_declarator_need_ident)
1891        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1892    return DeclPtrTy();
1893  }
1894
1895  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1896  // we find one that is.
1897  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1898         (S->getFlags() & Scope::TemplateParamScope) != 0)
1899    S = S->getParent();
1900
1901  // If this is an out-of-line definition of a member of a class template
1902  // or class template partial specialization, we may need to rebuild the
1903  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1904  // for more information.
1905  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1906  // handle expressions properly.
1907  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1908  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1909      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1910      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1911       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1912       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1913       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1914    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1915      // FIXME: Preserve type source info.
1916      QualType T = GetTypeFromParser(DS.getTypeRep());
1917
1918      DeclContext *SavedContext = CurContext;
1919      CurContext = DC;
1920      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1921      CurContext = SavedContext;
1922
1923      if (T.isNull())
1924        return DeclPtrTy();
1925      DS.UpdateTypeRep(T.getAsOpaquePtr());
1926    }
1927  }
1928
1929  DeclContext *DC;
1930  NamedDecl *New;
1931
1932  TypeSourceInfo *TInfo = 0;
1933  QualType R = GetTypeForDeclarator(D, S, &TInfo);
1934
1935  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1936                        ForRedeclaration);
1937
1938  // See if this is a redefinition of a variable in the same scope.
1939  if (D.getCXXScopeSpec().isInvalid()) {
1940    DC = CurContext;
1941    D.setInvalidType();
1942  } else if (!D.getCXXScopeSpec().isSet()) {
1943    bool IsLinkageLookup = false;
1944
1945    // If the declaration we're planning to build will be a function
1946    // or object with linkage, then look for another declaration with
1947    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1948    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1949      /* Do nothing*/;
1950    else if (R->isFunctionType()) {
1951      if (CurContext->isFunctionOrMethod() ||
1952          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1953        IsLinkageLookup = true;
1954    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1955      IsLinkageLookup = true;
1956    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1957             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1958      IsLinkageLookup = true;
1959
1960    if (IsLinkageLookup)
1961      Previous.clear(LookupRedeclarationWithLinkage);
1962
1963    DC = CurContext;
1964    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1965  } else { // Something like "int foo::x;"
1966    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1967
1968    if (!DC) {
1969      // If we could not compute the declaration context, it's because the
1970      // declaration context is dependent but does not refer to a class,
1971      // class template, or class template partial specialization. Complain
1972      // and return early, to avoid the coming semantic disaster.
1973      Diag(D.getIdentifierLoc(),
1974           diag::err_template_qualified_declarator_no_match)
1975        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1976        << D.getCXXScopeSpec().getRange();
1977      return DeclPtrTy();
1978    }
1979
1980    if (!DC->isDependentContext() &&
1981        RequireCompleteDeclContext(D.getCXXScopeSpec()))
1982      return DeclPtrTy();
1983
1984    LookupQualifiedName(Previous, DC);
1985
1986    // Don't consider using declarations as previous declarations for
1987    // out-of-line members.
1988    RemoveUsingDecls(Previous);
1989
1990    // C++ 7.3.1.2p2:
1991    // Members (including explicit specializations of templates) of a named
1992    // namespace can also be defined outside that namespace by explicit
1993    // qualification of the name being defined, provided that the entity being
1994    // defined was already declared in the namespace and the definition appears
1995    // after the point of declaration in a namespace that encloses the
1996    // declarations namespace.
1997    //
1998    // Note that we only check the context at this point. We don't yet
1999    // have enough information to make sure that PrevDecl is actually
2000    // the declaration we want to match. For example, given:
2001    //
2002    //   class X {
2003    //     void f();
2004    //     void f(float);
2005    //   };
2006    //
2007    //   void X::f(int) { } // ill-formed
2008    //
2009    // In this case, PrevDecl will point to the overload set
2010    // containing the two f's declared in X, but neither of them
2011    // matches.
2012
2013    // First check whether we named the global scope.
2014    if (isa<TranslationUnitDecl>(DC)) {
2015      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2016        << Name << D.getCXXScopeSpec().getRange();
2017    } else {
2018      DeclContext *Cur = CurContext;
2019      while (isa<LinkageSpecDecl>(Cur))
2020        Cur = Cur->getParent();
2021      if (!Cur->Encloses(DC)) {
2022        // The qualifying scope doesn't enclose the original declaration.
2023        // Emit diagnostic based on current scope.
2024        SourceLocation L = D.getIdentifierLoc();
2025        SourceRange R = D.getCXXScopeSpec().getRange();
2026        if (isa<FunctionDecl>(Cur))
2027          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2028        else
2029          Diag(L, diag::err_invalid_declarator_scope)
2030            << Name << cast<NamedDecl>(DC) << R;
2031        D.setInvalidType();
2032      }
2033    }
2034  }
2035
2036  if (Previous.isSingleResult() &&
2037      Previous.getFoundDecl()->isTemplateParameter()) {
2038    // Maybe we will complain about the shadowed template parameter.
2039    if (!D.isInvalidType())
2040      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2041                                          Previous.getFoundDecl()))
2042        D.setInvalidType();
2043
2044    // Just pretend that we didn't see the previous declaration.
2045    Previous.clear();
2046  }
2047
2048  // In C++, the previous declaration we find might be a tag type
2049  // (class or enum). In this case, the new declaration will hide the
2050  // tag type. Note that this does does not apply if we're declaring a
2051  // typedef (C++ [dcl.typedef]p4).
2052  if (Previous.isSingleTagDecl() &&
2053      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2054    Previous.clear();
2055
2056  bool Redeclaration = false;
2057  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2058    if (TemplateParamLists.size()) {
2059      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2060      return DeclPtrTy();
2061    }
2062
2063    New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2064  } else if (R->isFunctionType()) {
2065    New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2066                                  move(TemplateParamLists),
2067                                  IsFunctionDefinition, Redeclaration);
2068  } else {
2069    New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2070                                  move(TemplateParamLists),
2071                                  Redeclaration);
2072  }
2073
2074  if (New == 0)
2075    return DeclPtrTy();
2076
2077  // If this has an identifier and is not an invalid redeclaration or
2078  // function template specialization, add it to the scope stack.
2079  if (Name && !(Redeclaration && New->isInvalidDecl()))
2080    PushOnScopeChains(New, S);
2081
2082  return DeclPtrTy::make(New);
2083}
2084
2085/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2086/// types into constant array types in certain situations which would otherwise
2087/// be errors (for GCC compatibility).
2088static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2089                                                    ASTContext &Context,
2090                                                    bool &SizeIsNegative) {
2091  // This method tries to turn a variable array into a constant
2092  // array even when the size isn't an ICE.  This is necessary
2093  // for compatibility with code that depends on gcc's buggy
2094  // constant expression folding, like struct {char x[(int)(char*)2];}
2095  SizeIsNegative = false;
2096
2097  QualifierCollector Qs;
2098  const Type *Ty = Qs.strip(T);
2099
2100  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2101    QualType Pointee = PTy->getPointeeType();
2102    QualType FixedType =
2103        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2104    if (FixedType.isNull()) return FixedType;
2105    FixedType = Context.getPointerType(FixedType);
2106    return Qs.apply(FixedType);
2107  }
2108
2109  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2110  if (!VLATy)
2111    return QualType();
2112  // FIXME: We should probably handle this case
2113  if (VLATy->getElementType()->isVariablyModifiedType())
2114    return QualType();
2115
2116  Expr::EvalResult EvalResult;
2117  if (!VLATy->getSizeExpr() ||
2118      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2119      !EvalResult.Val.isInt())
2120    return QualType();
2121
2122  llvm::APSInt &Res = EvalResult.Val.getInt();
2123  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2124    // TODO: preserve the size expression in declarator info
2125    return Context.getConstantArrayType(VLATy->getElementType(),
2126                                        Res, ArrayType::Normal, 0);
2127  }
2128
2129  SizeIsNegative = true;
2130  return QualType();
2131}
2132
2133/// \brief Register the given locally-scoped external C declaration so
2134/// that it can be found later for redeclarations
2135void
2136Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2137                                       const LookupResult &Previous,
2138                                       Scope *S) {
2139  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2140         "Decl is not a locally-scoped decl!");
2141  // Note that we have a locally-scoped external with this name.
2142  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2143
2144  if (!Previous.isSingleResult())
2145    return;
2146
2147  NamedDecl *PrevDecl = Previous.getFoundDecl();
2148
2149  // If there was a previous declaration of this variable, it may be
2150  // in our identifier chain. Update the identifier chain with the new
2151  // declaration.
2152  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2153    // The previous declaration was found on the identifer resolver
2154    // chain, so remove it from its scope.
2155    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2156      S = S->getParent();
2157
2158    if (S)
2159      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2160  }
2161}
2162
2163/// \brief Diagnose function specifiers on a declaration of an identifier that
2164/// does not identify a function.
2165void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2166  // FIXME: We should probably indicate the identifier in question to avoid
2167  // confusion for constructs like "inline int a(), b;"
2168  if (D.getDeclSpec().isInlineSpecified())
2169    Diag(D.getDeclSpec().getInlineSpecLoc(),
2170         diag::err_inline_non_function);
2171
2172  if (D.getDeclSpec().isVirtualSpecified())
2173    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2174         diag::err_virtual_non_function);
2175
2176  if (D.getDeclSpec().isExplicitSpecified())
2177    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2178         diag::err_explicit_non_function);
2179}
2180
2181NamedDecl*
2182Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2183                             QualType R,  TypeSourceInfo *TInfo,
2184                             LookupResult &Previous, bool &Redeclaration) {
2185  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2186  if (D.getCXXScopeSpec().isSet()) {
2187    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2188      << D.getCXXScopeSpec().getRange();
2189    D.setInvalidType();
2190    // Pretend we didn't see the scope specifier.
2191    DC = 0;
2192  }
2193
2194  if (getLangOptions().CPlusPlus) {
2195    // Check that there are no default arguments (C++ only).
2196    CheckExtraCXXDefaultArguments(D);
2197  }
2198
2199  DiagnoseFunctionSpecifiers(D);
2200
2201  if (D.getDeclSpec().isThreadSpecified())
2202    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2203
2204  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2205  if (!NewTD) return 0;
2206
2207  // Handle attributes prior to checking for duplicates in MergeVarDecl
2208  ProcessDeclAttributes(S, NewTD, D);
2209
2210  // Merge the decl with the existing one if appropriate. If the decl is
2211  // in an outer scope, it isn't the same thing.
2212  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2213  if (!Previous.empty()) {
2214    Redeclaration = true;
2215    MergeTypeDefDecl(NewTD, Previous);
2216  }
2217
2218  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2219  // then it shall have block scope.
2220  QualType T = NewTD->getUnderlyingType();
2221  if (T->isVariablyModifiedType()) {
2222    CurFunctionNeedsScopeChecking = true;
2223
2224    if (S->getFnParent() == 0) {
2225      bool SizeIsNegative;
2226      QualType FixedTy =
2227          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2228      if (!FixedTy.isNull()) {
2229        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2230        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2231      } else {
2232        if (SizeIsNegative)
2233          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2234        else if (T->isVariableArrayType())
2235          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2236        else
2237          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2238        NewTD->setInvalidDecl();
2239      }
2240    }
2241  }
2242
2243  // If this is the C FILE type, notify the AST context.
2244  if (IdentifierInfo *II = NewTD->getIdentifier())
2245    if (!NewTD->isInvalidDecl() &&
2246        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2247      if (II->isStr("FILE"))
2248        Context.setFILEDecl(NewTD);
2249      else if (II->isStr("jmp_buf"))
2250        Context.setjmp_bufDecl(NewTD);
2251      else if (II->isStr("sigjmp_buf"))
2252        Context.setsigjmp_bufDecl(NewTD);
2253    }
2254
2255  return NewTD;
2256}
2257
2258/// \brief Determines whether the given declaration is an out-of-scope
2259/// previous declaration.
2260///
2261/// This routine should be invoked when name lookup has found a
2262/// previous declaration (PrevDecl) that is not in the scope where a
2263/// new declaration by the same name is being introduced. If the new
2264/// declaration occurs in a local scope, previous declarations with
2265/// linkage may still be considered previous declarations (C99
2266/// 6.2.2p4-5, C++ [basic.link]p6).
2267///
2268/// \param PrevDecl the previous declaration found by name
2269/// lookup
2270///
2271/// \param DC the context in which the new declaration is being
2272/// declared.
2273///
2274/// \returns true if PrevDecl is an out-of-scope previous declaration
2275/// for a new delcaration with the same name.
2276static bool
2277isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2278                                ASTContext &Context) {
2279  if (!PrevDecl)
2280    return 0;
2281
2282  if (!PrevDecl->hasLinkage())
2283    return false;
2284
2285  if (Context.getLangOptions().CPlusPlus) {
2286    // C++ [basic.link]p6:
2287    //   If there is a visible declaration of an entity with linkage
2288    //   having the same name and type, ignoring entities declared
2289    //   outside the innermost enclosing namespace scope, the block
2290    //   scope declaration declares that same entity and receives the
2291    //   linkage of the previous declaration.
2292    DeclContext *OuterContext = DC->getLookupContext();
2293    if (!OuterContext->isFunctionOrMethod())
2294      // This rule only applies to block-scope declarations.
2295      return false;
2296    else {
2297      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2298      if (PrevOuterContext->isRecord())
2299        // We found a member function: ignore it.
2300        return false;
2301      else {
2302        // Find the innermost enclosing namespace for the new and
2303        // previous declarations.
2304        while (!OuterContext->isFileContext())
2305          OuterContext = OuterContext->getParent();
2306        while (!PrevOuterContext->isFileContext())
2307          PrevOuterContext = PrevOuterContext->getParent();
2308
2309        // The previous declaration is in a different namespace, so it
2310        // isn't the same function.
2311        if (OuterContext->getPrimaryContext() !=
2312            PrevOuterContext->getPrimaryContext())
2313          return false;
2314      }
2315    }
2316  }
2317
2318  return true;
2319}
2320
2321NamedDecl*
2322Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2323                              QualType R, TypeSourceInfo *TInfo,
2324                              LookupResult &Previous,
2325                              MultiTemplateParamsArg TemplateParamLists,
2326                              bool &Redeclaration) {
2327  DeclarationName Name = GetNameForDeclarator(D);
2328
2329  // Check that there are no default arguments (C++ only).
2330  if (getLangOptions().CPlusPlus)
2331    CheckExtraCXXDefaultArguments(D);
2332
2333  VarDecl *NewVD;
2334  VarDecl::StorageClass SC;
2335  switch (D.getDeclSpec().getStorageClassSpec()) {
2336  default: assert(0 && "Unknown storage class!");
2337  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
2338  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
2339  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
2340  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
2341  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
2342  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2343  case DeclSpec::SCS_mutable:
2344    // mutable can only appear on non-static class members, so it's always
2345    // an error here
2346    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2347    D.setInvalidType();
2348    SC = VarDecl::None;
2349    break;
2350  }
2351
2352  IdentifierInfo *II = Name.getAsIdentifierInfo();
2353  if (!II) {
2354    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2355      << Name.getAsString();
2356    return 0;
2357  }
2358
2359  DiagnoseFunctionSpecifiers(D);
2360
2361  if (!DC->isRecord() && S->getFnParent() == 0) {
2362    // C99 6.9p2: The storage-class specifiers auto and register shall not
2363    // appear in the declaration specifiers in an external declaration.
2364    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2365
2366      // If this is a register variable with an asm label specified, then this
2367      // is a GNU extension.
2368      if (SC == VarDecl::Register && D.getAsmLabel())
2369        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2370      else
2371        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2372      D.setInvalidType();
2373    }
2374  }
2375  if (DC->isRecord() && !CurContext->isRecord()) {
2376    // This is an out-of-line definition of a static data member.
2377    if (SC == VarDecl::Static) {
2378      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2379           diag::err_static_out_of_line)
2380        << CodeModificationHint::CreateRemoval(
2381                                      D.getDeclSpec().getStorageClassSpecLoc());
2382    } else if (SC == VarDecl::None)
2383      SC = VarDecl::Static;
2384  }
2385  if (SC == VarDecl::Static) {
2386    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2387      if (RD->isLocalClass())
2388        Diag(D.getIdentifierLoc(),
2389             diag::err_static_data_member_not_allowed_in_local_class)
2390          << Name << RD->getDeclName();
2391    }
2392  }
2393
2394  // Match up the template parameter lists with the scope specifier, then
2395  // determine whether we have a template or a template specialization.
2396  bool isExplicitSpecialization = false;
2397  if (TemplateParameterList *TemplateParams
2398        = MatchTemplateParametersToScopeSpecifier(
2399                                  D.getDeclSpec().getSourceRange().getBegin(),
2400                                                  D.getCXXScopeSpec(),
2401                        (TemplateParameterList**)TemplateParamLists.get(),
2402                                                   TemplateParamLists.size(),
2403                                                  isExplicitSpecialization)) {
2404    if (TemplateParams->size() > 0) {
2405      // There is no such thing as a variable template.
2406      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2407        << II
2408        << SourceRange(TemplateParams->getTemplateLoc(),
2409                       TemplateParams->getRAngleLoc());
2410      return 0;
2411    } else {
2412      // There is an extraneous 'template<>' for this variable. Complain
2413      // about it, but allow the declaration of the variable.
2414      Diag(TemplateParams->getTemplateLoc(),
2415           diag::err_template_variable_noparams)
2416        << II
2417        << SourceRange(TemplateParams->getTemplateLoc(),
2418                       TemplateParams->getRAngleLoc());
2419
2420      isExplicitSpecialization = true;
2421    }
2422  }
2423
2424  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2425                          II, R, TInfo, SC);
2426
2427  if (D.isInvalidType())
2428    NewVD->setInvalidDecl();
2429
2430  if (D.getDeclSpec().isThreadSpecified()) {
2431    if (NewVD->hasLocalStorage())
2432      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2433    else if (!Context.Target.isTLSSupported())
2434      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2435    else
2436      NewVD->setThreadSpecified(true);
2437  }
2438
2439  // Set the lexical context. If the declarator has a C++ scope specifier, the
2440  // lexical context will be different from the semantic context.
2441  NewVD->setLexicalDeclContext(CurContext);
2442
2443  // Handle attributes prior to checking for duplicates in MergeVarDecl
2444  ProcessDeclAttributes(S, NewVD, D);
2445
2446  // Handle GNU asm-label extension (encoded as an attribute).
2447  if (Expr *E = (Expr*) D.getAsmLabel()) {
2448    // The parser guarantees this is a string.
2449    StringLiteral *SE = cast<StringLiteral>(E);
2450    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2451  }
2452
2453  // Don't consider existing declarations that are in a different
2454  // scope and are out-of-semantic-context declarations (if the new
2455  // declaration has linkage).
2456  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2457
2458  // Merge the decl with the existing one if appropriate.
2459  if (!Previous.empty()) {
2460    if (Previous.isSingleResult() &&
2461        isa<FieldDecl>(Previous.getFoundDecl()) &&
2462        D.getCXXScopeSpec().isSet()) {
2463      // The user tried to define a non-static data member
2464      // out-of-line (C++ [dcl.meaning]p1).
2465      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2466        << D.getCXXScopeSpec().getRange();
2467      Previous.clear();
2468      NewVD->setInvalidDecl();
2469    }
2470  } else if (D.getCXXScopeSpec().isSet()) {
2471    // No previous declaration in the qualifying scope.
2472    Diag(D.getIdentifierLoc(), diag::err_no_member)
2473      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2474      << D.getCXXScopeSpec().getRange();
2475    NewVD->setInvalidDecl();
2476  }
2477
2478  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2479
2480  // This is an explicit specialization of a static data member. Check it.
2481  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2482      CheckMemberSpecialization(NewVD, Previous))
2483    NewVD->setInvalidDecl();
2484
2485  // attributes declared post-definition are currently ignored
2486  if (Previous.isSingleResult()) {
2487    const VarDecl *Def = 0;
2488    VarDecl *PrevDecl = dyn_cast<VarDecl>(Previous.getFoundDecl());
2489    if (PrevDecl && PrevDecl->getDefinition(Def) && D.hasAttributes()) {
2490      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2491      Diag(Def->getLocation(), diag::note_previous_definition);
2492    }
2493  }
2494
2495  // If this is a locally-scoped extern C variable, update the map of
2496  // such variables.
2497  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2498      !NewVD->isInvalidDecl())
2499    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2500
2501  return NewVD;
2502}
2503
2504/// \brief Perform semantic checking on a newly-created variable
2505/// declaration.
2506///
2507/// This routine performs all of the type-checking required for a
2508/// variable declaration once it has been built. It is used both to
2509/// check variables after they have been parsed and their declarators
2510/// have been translated into a declaration, and to check variables
2511/// that have been instantiated from a template.
2512///
2513/// Sets NewVD->isInvalidDecl() if an error was encountered.
2514void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2515                                    LookupResult &Previous,
2516                                    bool &Redeclaration) {
2517  // If the decl is already known invalid, don't check it.
2518  if (NewVD->isInvalidDecl())
2519    return;
2520
2521  QualType T = NewVD->getType();
2522
2523  if (T->isObjCInterfaceType()) {
2524    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2525    return NewVD->setInvalidDecl();
2526  }
2527
2528  // Emit an error if an address space was applied to decl with local storage.
2529  // This includes arrays of objects with address space qualifiers, but not
2530  // automatic variables that point to other address spaces.
2531  // ISO/IEC TR 18037 S5.1.2
2532  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2533    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2534    return NewVD->setInvalidDecl();
2535  }
2536
2537  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2538      && !NewVD->hasAttr<BlocksAttr>())
2539    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2540
2541  bool isVM = T->isVariablyModifiedType();
2542  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2543      NewVD->hasAttr<BlocksAttr>())
2544    CurFunctionNeedsScopeChecking = true;
2545
2546  if ((isVM && NewVD->hasLinkage()) ||
2547      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2548    bool SizeIsNegative;
2549    QualType FixedTy =
2550        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2551
2552    if (FixedTy.isNull() && T->isVariableArrayType()) {
2553      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2554      // FIXME: This won't give the correct result for
2555      // int a[10][n];
2556      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2557
2558      if (NewVD->isFileVarDecl())
2559        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2560        << SizeRange;
2561      else if (NewVD->getStorageClass() == VarDecl::Static)
2562        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2563        << SizeRange;
2564      else
2565        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2566        << SizeRange;
2567      return NewVD->setInvalidDecl();
2568    }
2569
2570    if (FixedTy.isNull()) {
2571      if (NewVD->isFileVarDecl())
2572        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2573      else
2574        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2575      return NewVD->setInvalidDecl();
2576    }
2577
2578    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2579    NewVD->setType(FixedTy);
2580  }
2581
2582  if (Previous.empty() && NewVD->isExternC()) {
2583    // Since we did not find anything by this name and we're declaring
2584    // an extern "C" variable, look for a non-visible extern "C"
2585    // declaration with the same name.
2586    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2587      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2588    if (Pos != LocallyScopedExternalDecls.end())
2589      Previous.addDecl(Pos->second);
2590  }
2591
2592  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2593    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2594      << T;
2595    return NewVD->setInvalidDecl();
2596  }
2597
2598  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2599    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2600    return NewVD->setInvalidDecl();
2601  }
2602
2603  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2604    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2605    return NewVD->setInvalidDecl();
2606  }
2607
2608  if (!Previous.empty()) {
2609    Redeclaration = true;
2610    MergeVarDecl(NewVD, Previous);
2611  }
2612}
2613
2614/// \brief Data used with FindOverriddenMethod
2615struct FindOverriddenMethodData {
2616  Sema *S;
2617  CXXMethodDecl *Method;
2618};
2619
2620/// \brief Member lookup function that determines whether a given C++
2621/// method overrides a method in a base class, to be used with
2622/// CXXRecordDecl::lookupInBases().
2623static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2624                                 CXXBasePath &Path,
2625                                 void *UserData) {
2626  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2627
2628  FindOverriddenMethodData *Data
2629    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2630
2631  DeclarationName Name = Data->Method->getDeclName();
2632
2633  // FIXME: Do we care about other names here too?
2634  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2635    // We really want to find the base class constructor here.
2636    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2637    CanQualType CT = Data->S->Context.getCanonicalType(T);
2638
2639    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2640  }
2641
2642  for (Path.Decls = BaseRecord->lookup(Name);
2643       Path.Decls.first != Path.Decls.second;
2644       ++Path.Decls.first) {
2645    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2646      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2647        return true;
2648    }
2649  }
2650
2651  return false;
2652}
2653
2654/// AddOverriddenMethods - See if a method overrides any in the base classes,
2655/// and if so, check that it's a valid override and remember it.
2656void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2657  // Look for virtual methods in base classes that this method might override.
2658  CXXBasePaths Paths;
2659  FindOverriddenMethodData Data;
2660  Data.Method = MD;
2661  Data.S = this;
2662  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2663    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2664         E = Paths.found_decls_end(); I != E; ++I) {
2665      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2666        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2667            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2668            !CheckOverridingFunctionAttributes(MD, OldMD))
2669          MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2670      }
2671    }
2672  }
2673}
2674
2675NamedDecl*
2676Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2677                              QualType R, TypeSourceInfo *TInfo,
2678                              LookupResult &Previous,
2679                              MultiTemplateParamsArg TemplateParamLists,
2680                              bool IsFunctionDefinition, bool &Redeclaration) {
2681  assert(R.getTypePtr()->isFunctionType());
2682
2683  DeclarationName Name = GetNameForDeclarator(D);
2684  FunctionDecl::StorageClass SC = FunctionDecl::None;
2685  switch (D.getDeclSpec().getStorageClassSpec()) {
2686  default: assert(0 && "Unknown storage class!");
2687  case DeclSpec::SCS_auto:
2688  case DeclSpec::SCS_register:
2689  case DeclSpec::SCS_mutable:
2690    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2691         diag::err_typecheck_sclass_func);
2692    D.setInvalidType();
2693    break;
2694  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2695  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2696  case DeclSpec::SCS_static: {
2697    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2698      // C99 6.7.1p5:
2699      //   The declaration of an identifier for a function that has
2700      //   block scope shall have no explicit storage-class specifier
2701      //   other than extern
2702      // See also (C++ [dcl.stc]p4).
2703      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2704           diag::err_static_block_func);
2705      SC = FunctionDecl::None;
2706    } else
2707      SC = FunctionDecl::Static;
2708    break;
2709  }
2710  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2711  }
2712
2713  if (D.getDeclSpec().isThreadSpecified())
2714    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2715
2716  bool isFriend = D.getDeclSpec().isFriendSpecified();
2717  bool isInline = D.getDeclSpec().isInlineSpecified();
2718  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2719  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2720
2721  // Check that the return type is not an abstract class type.
2722  // For record types, this is done by the AbstractClassUsageDiagnoser once
2723  // the class has been completely parsed.
2724  if (!DC->isRecord() &&
2725      RequireNonAbstractType(D.getIdentifierLoc(),
2726                             R->getAs<FunctionType>()->getResultType(),
2727                             diag::err_abstract_type_in_decl,
2728                             AbstractReturnType))
2729    D.setInvalidType();
2730
2731  // Do not allow returning a objc interface by-value.
2732  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2733    Diag(D.getIdentifierLoc(),
2734         diag::err_object_cannot_be_passed_returned_by_value) << 0
2735      << R->getAs<FunctionType>()->getResultType();
2736    D.setInvalidType();
2737  }
2738
2739  bool isVirtualOkay = false;
2740  FunctionDecl *NewFD;
2741
2742  if (isFriend) {
2743    // C++ [class.friend]p5
2744    //   A function can be defined in a friend declaration of a
2745    //   class . . . . Such a function is implicitly inline.
2746    isInline |= IsFunctionDefinition;
2747  }
2748
2749  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2750    // This is a C++ constructor declaration.
2751    assert(DC->isRecord() &&
2752           "Constructors can only be declared in a member context");
2753
2754    R = CheckConstructorDeclarator(D, R, SC);
2755
2756    // Create the new declaration
2757    NewFD = CXXConstructorDecl::Create(Context,
2758                                       cast<CXXRecordDecl>(DC),
2759                                       D.getIdentifierLoc(), Name, R, TInfo,
2760                                       isExplicit, isInline,
2761                                       /*isImplicitlyDeclared=*/false);
2762  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2763    // This is a C++ destructor declaration.
2764    if (DC->isRecord()) {
2765      R = CheckDestructorDeclarator(D, SC);
2766
2767      NewFD = CXXDestructorDecl::Create(Context,
2768                                        cast<CXXRecordDecl>(DC),
2769                                        D.getIdentifierLoc(), Name, R,
2770                                        isInline,
2771                                        /*isImplicitlyDeclared=*/false);
2772
2773      isVirtualOkay = true;
2774    } else {
2775      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2776
2777      // Create a FunctionDecl to satisfy the function definition parsing
2778      // code path.
2779      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2780                                   Name, R, TInfo, SC, isInline,
2781                                   /*hasPrototype=*/true);
2782      D.setInvalidType();
2783    }
2784  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2785    if (!DC->isRecord()) {
2786      Diag(D.getIdentifierLoc(),
2787           diag::err_conv_function_not_member);
2788      return 0;
2789    }
2790
2791    CheckConversionDeclarator(D, R, SC);
2792    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2793                                      D.getIdentifierLoc(), Name, R, TInfo,
2794                                      isInline, isExplicit);
2795
2796    isVirtualOkay = true;
2797  } else if (DC->isRecord()) {
2798    // If the of the function is the same as the name of the record, then this
2799    // must be an invalid constructor that has a return type.
2800    // (The parser checks for a return type and makes the declarator a
2801    // constructor if it has no return type).
2802    // must have an invalid constructor that has a return type
2803    if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2804      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2805        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2806        << SourceRange(D.getIdentifierLoc());
2807      return 0;
2808    }
2809
2810    bool isStatic = SC == FunctionDecl::Static;
2811
2812    // [class.free]p1:
2813    // Any allocation function for a class T is a static member
2814    // (even if not explicitly declared static).
2815    if (Name.getCXXOverloadedOperator() == OO_New ||
2816        Name.getCXXOverloadedOperator() == OO_Array_New)
2817      isStatic = true;
2818
2819    // [class.free]p6 Any deallocation function for a class X is a static member
2820    // (even if not explicitly declared static).
2821    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2822        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2823      isStatic = true;
2824
2825    // This is a C++ method declaration.
2826    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2827                                  D.getIdentifierLoc(), Name, R, TInfo,
2828                                  isStatic, isInline);
2829
2830    isVirtualOkay = !isStatic;
2831  } else {
2832    // Determine whether the function was written with a
2833    // prototype. This true when:
2834    //   - we're in C++ (where every function has a prototype),
2835    //   - there is a prototype in the declarator, or
2836    //   - the type R of the function is some kind of typedef or other reference
2837    //     to a type name (which eventually refers to a function type).
2838    bool HasPrototype =
2839       getLangOptions().CPlusPlus ||
2840       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2841       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2842
2843    NewFD = FunctionDecl::Create(Context, DC,
2844                                 D.getIdentifierLoc(),
2845                                 Name, R, TInfo, SC, isInline, HasPrototype);
2846  }
2847
2848  if (D.isInvalidType())
2849    NewFD->setInvalidDecl();
2850
2851  // Set the lexical context. If the declarator has a C++
2852  // scope specifier, or is the object of a friend declaration, the
2853  // lexical context will be different from the semantic context.
2854  NewFD->setLexicalDeclContext(CurContext);
2855
2856  // Match up the template parameter lists with the scope specifier, then
2857  // determine whether we have a template or a template specialization.
2858  FunctionTemplateDecl *FunctionTemplate = 0;
2859  bool isExplicitSpecialization = false;
2860  bool isFunctionTemplateSpecialization = false;
2861  if (TemplateParameterList *TemplateParams
2862        = MatchTemplateParametersToScopeSpecifier(
2863                                  D.getDeclSpec().getSourceRange().getBegin(),
2864                                  D.getCXXScopeSpec(),
2865                           (TemplateParameterList**)TemplateParamLists.get(),
2866                                                  TemplateParamLists.size(),
2867                                                  isExplicitSpecialization)) {
2868    if (TemplateParams->size() > 0) {
2869      // This is a function template
2870
2871      // Check that we can declare a template here.
2872      if (CheckTemplateDeclScope(S, TemplateParams))
2873        return 0;
2874
2875      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2876                                                      NewFD->getLocation(),
2877                                                      Name, TemplateParams,
2878                                                      NewFD);
2879      FunctionTemplate->setLexicalDeclContext(CurContext);
2880      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2881    } else {
2882      // This is a function template specialization.
2883      isFunctionTemplateSpecialization = true;
2884    }
2885
2886    // FIXME: Free this memory properly.
2887    TemplateParamLists.release();
2888  }
2889
2890  // C++ [dcl.fct.spec]p5:
2891  //   The virtual specifier shall only be used in declarations of
2892  //   nonstatic class member functions that appear within a
2893  //   member-specification of a class declaration; see 10.3.
2894  //
2895  if (isVirtual && !NewFD->isInvalidDecl()) {
2896    if (!isVirtualOkay) {
2897       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2898           diag::err_virtual_non_function);
2899    } else if (!CurContext->isRecord()) {
2900      // 'virtual' was specified outside of the class.
2901      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2902        << CodeModificationHint::CreateRemoval(
2903                                           D.getDeclSpec().getVirtualSpecLoc());
2904    } else {
2905      // Okay: Add virtual to the method.
2906      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2907      CurClass->setMethodAsVirtual(NewFD);
2908    }
2909  }
2910
2911  // Filter out previous declarations that don't match the scope.
2912  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2913
2914  if (isFriend) {
2915    // DC is the namespace in which the function is being declared.
2916    assert((DC->isFileContext() || !Previous.empty()) &&
2917           "previously-undeclared friend function being created "
2918           "in a non-namespace context");
2919
2920    if (FunctionTemplate) {
2921      FunctionTemplate->setObjectOfFriendDecl(
2922                                   /* PreviouslyDeclared= */ !Previous.empty());
2923      FunctionTemplate->setAccess(AS_public);
2924    }
2925    else
2926      NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2927
2928    NewFD->setAccess(AS_public);
2929  }
2930
2931  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2932      !CurContext->isRecord()) {
2933    // C++ [class.static]p1:
2934    //   A data or function member of a class may be declared static
2935    //   in a class definition, in which case it is a static member of
2936    //   the class.
2937
2938    // Complain about the 'static' specifier if it's on an out-of-line
2939    // member function definition.
2940    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2941         diag::err_static_out_of_line)
2942      << CodeModificationHint::CreateRemoval(
2943                                      D.getDeclSpec().getStorageClassSpecLoc());
2944  }
2945
2946  // Handle GNU asm-label extension (encoded as an attribute).
2947  if (Expr *E = (Expr*) D.getAsmLabel()) {
2948    // The parser guarantees this is a string.
2949    StringLiteral *SE = cast<StringLiteral>(E);
2950    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2951  }
2952
2953  // Copy the parameter declarations from the declarator D to the function
2954  // declaration NewFD, if they are available.  First scavenge them into Params.
2955  llvm::SmallVector<ParmVarDecl*, 16> Params;
2956  if (D.getNumTypeObjects() > 0) {
2957    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2958
2959    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2960    // function that takes no arguments, not a function that takes a
2961    // single void argument.
2962    // We let through "const void" here because Sema::GetTypeForDeclarator
2963    // already checks for that case.
2964    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2965        FTI.ArgInfo[0].Param &&
2966        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2967      // Empty arg list, don't push any params.
2968      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2969
2970      // In C++, the empty parameter-type-list must be spelled "void"; a
2971      // typedef of void is not permitted.
2972      if (getLangOptions().CPlusPlus &&
2973          Param->getType().getUnqualifiedType() != Context.VoidTy)
2974        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2975      // FIXME: Leaks decl?
2976    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2977      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2978        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2979        assert(Param->getDeclContext() != NewFD && "Was set before ?");
2980        Param->setDeclContext(NewFD);
2981        Params.push_back(Param);
2982      }
2983    }
2984
2985  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2986    // When we're declaring a function with a typedef, typeof, etc as in the
2987    // following example, we'll need to synthesize (unnamed)
2988    // parameters for use in the declaration.
2989    //
2990    // @code
2991    // typedef void fn(int);
2992    // fn f;
2993    // @endcode
2994
2995    // Synthesize a parameter for each argument type.
2996    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2997         AE = FT->arg_type_end(); AI != AE; ++AI) {
2998      ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2999                                               SourceLocation(), 0,
3000                                               *AI, /*TInfo=*/0,
3001                                               VarDecl::None, 0);
3002      Param->setImplicit();
3003      Params.push_back(Param);
3004    }
3005  } else {
3006    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3007           "Should not need args for typedef of non-prototype fn");
3008  }
3009  // Finally, we know we have the right number of parameters, install them.
3010  NewFD->setParams(Context, Params.data(), Params.size());
3011
3012  // If the declarator is a template-id, translate the parser's template
3013  // argument list into our AST format.
3014  bool HasExplicitTemplateArgs = false;
3015  TemplateArgumentListInfo TemplateArgs;
3016  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3017    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3018    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3019    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3020    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3021                                       TemplateId->getTemplateArgs(),
3022                                       TemplateId->NumArgs);
3023    translateTemplateArguments(TemplateArgsPtr,
3024                               TemplateArgs);
3025    TemplateArgsPtr.release();
3026
3027    HasExplicitTemplateArgs = true;
3028
3029    if (FunctionTemplate) {
3030      // FIXME: Diagnose function template with explicit template
3031      // arguments.
3032      HasExplicitTemplateArgs = false;
3033    } else if (!isFunctionTemplateSpecialization &&
3034               !D.getDeclSpec().isFriendSpecified()) {
3035      // We have encountered something that the user meant to be a
3036      // specialization (because it has explicitly-specified template
3037      // arguments) but that was not introduced with a "template<>" (or had
3038      // too few of them).
3039      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3040        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3041        << CodeModificationHint::CreateInsertion(
3042                                   D.getDeclSpec().getSourceRange().getBegin(),
3043                                                 "template<> ");
3044      isFunctionTemplateSpecialization = true;
3045    }
3046  }
3047
3048  if (isFunctionTemplateSpecialization) {
3049      if (CheckFunctionTemplateSpecialization(NewFD,
3050                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3051                                              Previous))
3052        NewFD->setInvalidDecl();
3053  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3054             CheckMemberSpecialization(NewFD, Previous))
3055    NewFD->setInvalidDecl();
3056
3057  // Perform semantic checking on the function declaration.
3058  bool OverloadableAttrRequired = false; // FIXME: HACK!
3059  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3060                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3061
3062  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3063          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3064         "previous declaration set still overloaded");
3065
3066  // If we have a function template, check the template parameter
3067  // list. This will check and merge default template arguments.
3068  if (FunctionTemplate) {
3069    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3070    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3071                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3072             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3073                                                : TPC_FunctionTemplate);
3074  }
3075
3076  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3077    // An out-of-line member function declaration must also be a
3078    // definition (C++ [dcl.meaning]p1).
3079    // Note that this is not the case for explicit specializations of
3080    // function templates or member functions of class templates, per
3081    // C++ [temp.expl.spec]p2.
3082    if (!IsFunctionDefinition && !isFriend &&
3083        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3084      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3085        << D.getCXXScopeSpec().getRange();
3086      NewFD->setInvalidDecl();
3087    } else if (!Redeclaration) {
3088      // The user tried to provide an out-of-line definition for a
3089      // function that is a member of a class or namespace, but there
3090      // was no such member function declared (C++ [class.mfct]p2,
3091      // C++ [namespace.memdef]p2). For example:
3092      //
3093      // class X {
3094      //   void f() const;
3095      // };
3096      //
3097      // void X::f() { } // ill-formed
3098      //
3099      // Complain about this problem, and attempt to suggest close
3100      // matches (e.g., those that differ only in cv-qualifiers and
3101      // whether the parameter types are references).
3102      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3103        << Name << DC << D.getCXXScopeSpec().getRange();
3104      NewFD->setInvalidDecl();
3105
3106      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3107                        ForRedeclaration);
3108      LookupQualifiedName(Prev, DC);
3109      assert(!Prev.isAmbiguous() &&
3110             "Cannot have an ambiguity in previous-declaration lookup");
3111      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3112           Func != FuncEnd; ++Func) {
3113        if (isa<FunctionDecl>(*Func) &&
3114            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3115          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3116      }
3117    }
3118  }
3119
3120  // Handle attributes. We need to have merged decls when handling attributes
3121  // (for example to check for conflicts, etc).
3122  // FIXME: This needs to happen before we merge declarations. Then,
3123  // let attribute merging cope with attribute conflicts.
3124  ProcessDeclAttributes(S, NewFD, D);
3125
3126  // attributes declared post-definition are currently ignored
3127  if (Redeclaration && Previous.isSingleResult()) {
3128    const FunctionDecl *Def;
3129    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3130    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3131      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3132      Diag(Def->getLocation(), diag::note_previous_definition);
3133    }
3134  }
3135
3136  AddKnownFunctionAttributes(NewFD);
3137
3138  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3139    // If a function name is overloadable in C, then every function
3140    // with that name must be marked "overloadable".
3141    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3142      << Redeclaration << NewFD;
3143    if (!Previous.empty())
3144      Diag(Previous.getRepresentativeDecl()->getLocation(),
3145           diag::note_attribute_overloadable_prev_overload);
3146    NewFD->addAttr(::new (Context) OverloadableAttr());
3147  }
3148
3149  // If this is a locally-scoped extern C function, update the
3150  // map of such names.
3151  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3152      && !NewFD->isInvalidDecl())
3153    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3154
3155  // Set this FunctionDecl's range up to the right paren.
3156  NewFD->setLocEnd(D.getSourceRange().getEnd());
3157
3158  if (FunctionTemplate && NewFD->isInvalidDecl())
3159    FunctionTemplate->setInvalidDecl();
3160
3161  if (FunctionTemplate)
3162    return FunctionTemplate;
3163
3164  return NewFD;
3165}
3166
3167/// \brief Perform semantic checking of a new function declaration.
3168///
3169/// Performs semantic analysis of the new function declaration
3170/// NewFD. This routine performs all semantic checking that does not
3171/// require the actual declarator involved in the declaration, and is
3172/// used both for the declaration of functions as they are parsed
3173/// (called via ActOnDeclarator) and for the declaration of functions
3174/// that have been instantiated via C++ template instantiation (called
3175/// via InstantiateDecl).
3176///
3177/// \param IsExplicitSpecialiation whether this new function declaration is
3178/// an explicit specialization of the previous declaration.
3179///
3180/// This sets NewFD->isInvalidDecl() to true if there was an error.
3181void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3182                                    LookupResult &Previous,
3183                                    bool IsExplicitSpecialization,
3184                                    bool &Redeclaration,
3185                                    bool &OverloadableAttrRequired) {
3186  // If NewFD is already known erroneous, don't do any of this checking.
3187  if (NewFD->isInvalidDecl())
3188    return;
3189
3190  if (NewFD->getResultType()->isVariablyModifiedType()) {
3191    // Functions returning a variably modified type violate C99 6.7.5.2p2
3192    // because all functions have linkage.
3193    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3194    return NewFD->setInvalidDecl();
3195  }
3196
3197  if (NewFD->isMain())
3198    CheckMain(NewFD);
3199
3200  // Check for a previous declaration of this name.
3201  if (Previous.empty() && NewFD->isExternC()) {
3202    // Since we did not find anything by this name and we're declaring
3203    // an extern "C" function, look for a non-visible extern "C"
3204    // declaration with the same name.
3205    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3206      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3207    if (Pos != LocallyScopedExternalDecls.end())
3208      Previous.addDecl(Pos->second);
3209  }
3210
3211  // Merge or overload the declaration with an existing declaration of
3212  // the same name, if appropriate.
3213  if (!Previous.empty()) {
3214    // Determine whether NewFD is an overload of PrevDecl or
3215    // a declaration that requires merging. If it's an overload,
3216    // there's no more work to do here; we'll just add the new
3217    // function to the scope.
3218
3219    NamedDecl *OldDecl = 0;
3220    if (!AllowOverloadingOfFunction(Previous, Context)) {
3221      Redeclaration = true;
3222      OldDecl = Previous.getFoundDecl();
3223    } else {
3224      if (!getLangOptions().CPlusPlus) {
3225        OverloadableAttrRequired = true;
3226
3227        // Functions marked "overloadable" must have a prototype (that
3228        // we can't get through declaration merging).
3229        if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3230          Diag(NewFD->getLocation(),
3231               diag::err_attribute_overloadable_no_prototype)
3232            << NewFD;
3233          Redeclaration = true;
3234
3235          // Turn this into a variadic function with no parameters.
3236          QualType R = Context.getFunctionType(
3237                     NewFD->getType()->getAs<FunctionType>()->getResultType(),
3238                     0, 0, true, 0);
3239          NewFD->setType(R);
3240          return NewFD->setInvalidDecl();
3241        }
3242      }
3243
3244      switch (CheckOverload(NewFD, Previous, OldDecl)) {
3245      case Ovl_Match:
3246        Redeclaration = true;
3247        if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3248          HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3249          Redeclaration = false;
3250        }
3251        break;
3252
3253      case Ovl_NonFunction:
3254        Redeclaration = true;
3255        break;
3256
3257      case Ovl_Overload:
3258        Redeclaration = false;
3259        break;
3260      }
3261    }
3262
3263    if (Redeclaration) {
3264      // NewFD and OldDecl represent declarations that need to be
3265      // merged.
3266      if (MergeFunctionDecl(NewFD, OldDecl))
3267        return NewFD->setInvalidDecl();
3268
3269      Previous.clear();
3270      Previous.addDecl(OldDecl);
3271
3272      if (FunctionTemplateDecl *OldTemplateDecl
3273                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3274        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3275        FunctionTemplateDecl *NewTemplateDecl
3276          = NewFD->getDescribedFunctionTemplate();
3277        assert(NewTemplateDecl && "Template/non-template mismatch");
3278        if (CXXMethodDecl *Method
3279              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3280          Method->setAccess(OldTemplateDecl->getAccess());
3281          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3282        }
3283
3284        // If this is an explicit specialization of a member that is a function
3285        // template, mark it as a member specialization.
3286        if (IsExplicitSpecialization &&
3287            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3288          NewTemplateDecl->setMemberSpecialization();
3289          assert(OldTemplateDecl->isMemberSpecialization());
3290        }
3291      } else {
3292        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3293          NewFD->setAccess(OldDecl->getAccess());
3294        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3295      }
3296    }
3297  }
3298
3299  // Semantic checking for this function declaration (in isolation).
3300  if (getLangOptions().CPlusPlus) {
3301    // C++-specific checks.
3302    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3303      CheckConstructor(Constructor);
3304    } else if (CXXDestructorDecl *Destructor =
3305                dyn_cast<CXXDestructorDecl>(NewFD)) {
3306      CXXRecordDecl *Record = Destructor->getParent();
3307      QualType ClassType = Context.getTypeDeclType(Record);
3308
3309      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3310      // type is dependent? Both gcc and edg can handle that.
3311      if (!ClassType->isDependentType()) {
3312        DeclarationName Name
3313          = Context.DeclarationNames.getCXXDestructorName(
3314                                        Context.getCanonicalType(ClassType));
3315        if (NewFD->getDeclName() != Name) {
3316          Diag(NewFD->getLocation(), diag::err_destructor_name);
3317          return NewFD->setInvalidDecl();
3318        }
3319      }
3320
3321      Record->setUserDeclaredDestructor(true);
3322      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3323      // user-defined destructor.
3324      Record->setPOD(false);
3325
3326      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3327      // declared destructor.
3328      // FIXME: C++0x: don't do this for "= default" destructors
3329      Record->setHasTrivialDestructor(false);
3330    } else if (CXXConversionDecl *Conversion
3331               = dyn_cast<CXXConversionDecl>(NewFD)) {
3332      ActOnConversionDeclarator(Conversion);
3333    }
3334
3335    // Find any virtual functions that this function overrides.
3336    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3337      if (!Method->isFunctionTemplateSpecialization() &&
3338          !Method->getDescribedFunctionTemplate())
3339        AddOverriddenMethods(Method->getParent(), Method);
3340    }
3341
3342    // Additional checks for the destructor; make sure we do this after we
3343    // figure out whether the destructor is virtual.
3344    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3345      if (!Destructor->getParent()->isDependentType())
3346        CheckDestructor(Destructor);
3347
3348    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3349    if (NewFD->isOverloadedOperator() &&
3350        CheckOverloadedOperatorDeclaration(NewFD))
3351      return NewFD->setInvalidDecl();
3352
3353    // In C++, check default arguments now that we have merged decls. Unless
3354    // the lexical context is the class, because in this case this is done
3355    // during delayed parsing anyway.
3356    if (!CurContext->isRecord())
3357      CheckCXXDefaultArguments(NewFD);
3358  }
3359}
3360
3361void Sema::CheckMain(FunctionDecl* FD) {
3362  // C++ [basic.start.main]p3:  A program that declares main to be inline
3363  //   or static is ill-formed.
3364  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3365  //   shall not appear in a declaration of main.
3366  // static main is not an error under C99, but we should warn about it.
3367  bool isInline = FD->isInlineSpecified();
3368  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3369  if (isInline || isStatic) {
3370    unsigned diagID = diag::warn_unusual_main_decl;
3371    if (isInline || getLangOptions().CPlusPlus)
3372      diagID = diag::err_unusual_main_decl;
3373
3374    int which = isStatic + (isInline << 1) - 1;
3375    Diag(FD->getLocation(), diagID) << which;
3376  }
3377
3378  QualType T = FD->getType();
3379  assert(T->isFunctionType() && "function decl is not of function type");
3380  const FunctionType* FT = T->getAs<FunctionType>();
3381
3382  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3383    // TODO: add a replacement fixit to turn the return type into 'int'.
3384    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3385    FD->setInvalidDecl(true);
3386  }
3387
3388  // Treat protoless main() as nullary.
3389  if (isa<FunctionNoProtoType>(FT)) return;
3390
3391  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3392  unsigned nparams = FTP->getNumArgs();
3393  assert(FD->getNumParams() == nparams);
3394
3395  if (nparams > 3) {
3396    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3397    FD->setInvalidDecl(true);
3398    nparams = 3;
3399  }
3400
3401  // FIXME: a lot of the following diagnostics would be improved
3402  // if we had some location information about types.
3403
3404  QualType CharPP =
3405    Context.getPointerType(Context.getPointerType(Context.CharTy));
3406  QualType Expected[] = { Context.IntTy, CharPP, CharPP };
3407
3408  for (unsigned i = 0; i < nparams; ++i) {
3409    QualType AT = FTP->getArgType(i);
3410
3411    bool mismatch = true;
3412
3413    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3414      mismatch = false;
3415    else if (Expected[i] == CharPP) {
3416      // As an extension, the following forms are okay:
3417      //   char const **
3418      //   char const * const *
3419      //   char * const *
3420
3421      QualifierCollector qs;
3422      const PointerType* PT;
3423      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3424          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3425          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3426        qs.removeConst();
3427        mismatch = !qs.empty();
3428      }
3429    }
3430
3431    if (mismatch) {
3432      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3433      // TODO: suggest replacing given type with expected type
3434      FD->setInvalidDecl(true);
3435    }
3436  }
3437
3438  if (nparams == 1 && !FD->isInvalidDecl()) {
3439    Diag(FD->getLocation(), diag::warn_main_one_arg);
3440  }
3441}
3442
3443bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3444  // FIXME: Need strict checking.  In C89, we need to check for
3445  // any assignment, increment, decrement, function-calls, or
3446  // commas outside of a sizeof.  In C99, it's the same list,
3447  // except that the aforementioned are allowed in unevaluated
3448  // expressions.  Everything else falls under the
3449  // "may accept other forms of constant expressions" exception.
3450  // (We never end up here for C++, so the constant expression
3451  // rules there don't matter.)
3452  if (Init->isConstantInitializer(Context))
3453    return false;
3454  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3455    << Init->getSourceRange();
3456  return true;
3457}
3458
3459void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3460  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3461}
3462
3463/// AddInitializerToDecl - Adds the initializer Init to the
3464/// declaration dcl. If DirectInit is true, this is C++ direct
3465/// initialization rather than copy initialization.
3466void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3467  Decl *RealDecl = dcl.getAs<Decl>();
3468  // If there is no declaration, there was an error parsing it.  Just ignore
3469  // the initializer.
3470  if (RealDecl == 0)
3471    return;
3472
3473  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3474    // With declarators parsed the way they are, the parser cannot
3475    // distinguish between a normal initializer and a pure-specifier.
3476    // Thus this grotesque test.
3477    IntegerLiteral *IL;
3478    Expr *Init = static_cast<Expr *>(init.get());
3479    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3480        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3481      CheckPureMethod(Method, Init->getSourceRange());
3482    else {
3483      Diag(Method->getLocation(), diag::err_member_function_initialization)
3484        << Method->getDeclName() << Init->getSourceRange();
3485      Method->setInvalidDecl();
3486    }
3487    return;
3488  }
3489
3490  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3491  if (!VDecl) {
3492    if (getLangOptions().CPlusPlus &&
3493        RealDecl->getLexicalDeclContext()->isRecord() &&
3494        isa<NamedDecl>(RealDecl))
3495      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3496        << cast<NamedDecl>(RealDecl)->getDeclName();
3497    else
3498      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3499    RealDecl->setInvalidDecl();
3500    return;
3501  }
3502
3503  // A definition must end up with a complete type, which means it must be
3504  // complete with the restriction that an array type might be completed by the
3505  // initializer; note that later code assumes this restriction.
3506  QualType BaseDeclType = VDecl->getType();
3507  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3508    BaseDeclType = Array->getElementType();
3509  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3510                          diag::err_typecheck_decl_incomplete_type)) {
3511    RealDecl->setInvalidDecl();
3512    return;
3513  }
3514
3515  // The variable can not have an abstract class type.
3516  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3517                             diag::err_abstract_type_in_decl,
3518                             AbstractVariableType))
3519    VDecl->setInvalidDecl();
3520
3521  const VarDecl *Def = 0;
3522  if (VDecl->getDefinition(Def)) {
3523    Diag(VDecl->getLocation(), diag::err_redefinition)
3524      << VDecl->getDeclName();
3525    Diag(Def->getLocation(), diag::note_previous_definition);
3526    VDecl->setInvalidDecl();
3527    return;
3528  }
3529
3530  // Take ownership of the expression, now that we're sure we have somewhere
3531  // to put it.
3532  Expr *Init = init.takeAs<Expr>();
3533  assert(Init && "missing initializer");
3534
3535  // Capture the variable that is being initialized and the style of
3536  // initialization.
3537  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3538
3539  // FIXME: Poor source location information.
3540  InitializationKind Kind
3541    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3542                                                   Init->getLocStart(),
3543                                                   Init->getLocEnd())
3544                : InitializationKind::CreateCopy(VDecl->getLocation(),
3545                                                 Init->getLocStart());
3546
3547  // Get the decls type and save a reference for later, since
3548  // CheckInitializerTypes may change it.
3549  QualType DclT = VDecl->getType(), SavT = DclT;
3550  if (VDecl->isBlockVarDecl()) {
3551    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3552      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3553      VDecl->setInvalidDecl();
3554    } else if (!VDecl->isInvalidDecl()) {
3555      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3556      if (InitSeq) {
3557        OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3558                                          MultiExprArg(*this, (void**)&Init, 1),
3559                                                  &DclT);
3560        if (Result.isInvalid()) {
3561          VDecl->setInvalidDecl();
3562          return;
3563        }
3564
3565        Init = Result.takeAs<Expr>();
3566      } else {
3567        InitSeq.Diagnose(*this, Entity, Kind, &Init, 1);
3568        VDecl->setInvalidDecl();
3569        return;
3570      }
3571
3572      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3573      // Don't check invalid declarations to avoid emitting useless diagnostics.
3574      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3575        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3576          CheckForConstantInitializer(Init, DclT);
3577      }
3578    }
3579  } else if (VDecl->isStaticDataMember() &&
3580             VDecl->getLexicalDeclContext()->isRecord()) {
3581    // This is an in-class initialization for a static data member, e.g.,
3582    //
3583    // struct S {
3584    //   static const int value = 17;
3585    // };
3586
3587    // Attach the initializer
3588    VDecl->setInit(Context, Init);
3589
3590    // C++ [class.mem]p4:
3591    //   A member-declarator can contain a constant-initializer only
3592    //   if it declares a static member (9.4) of const integral or
3593    //   const enumeration type, see 9.4.2.
3594    QualType T = VDecl->getType();
3595    if (!T->isDependentType() &&
3596        (!Context.getCanonicalType(T).isConstQualified() ||
3597         !T->isIntegralType())) {
3598      Diag(VDecl->getLocation(), diag::err_member_initialization)
3599        << VDecl->getDeclName() << Init->getSourceRange();
3600      VDecl->setInvalidDecl();
3601    } else {
3602      // C++ [class.static.data]p4:
3603      //   If a static data member is of const integral or const
3604      //   enumeration type, its declaration in the class definition
3605      //   can specify a constant-initializer which shall be an
3606      //   integral constant expression (5.19).
3607      if (!Init->isTypeDependent() &&
3608          !Init->getType()->isIntegralType()) {
3609        // We have a non-dependent, non-integral or enumeration type.
3610        Diag(Init->getSourceRange().getBegin(),
3611             diag::err_in_class_initializer_non_integral_type)
3612          << Init->getType() << Init->getSourceRange();
3613        VDecl->setInvalidDecl();
3614      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3615        // Check whether the expression is a constant expression.
3616        llvm::APSInt Value;
3617        SourceLocation Loc;
3618        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3619          Diag(Loc, diag::err_in_class_initializer_non_constant)
3620            << Init->getSourceRange();
3621          VDecl->setInvalidDecl();
3622        } else if (!VDecl->getType()->isDependentType())
3623          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3624      }
3625    }
3626  } else if (VDecl->isFileVarDecl()) {
3627    if (VDecl->getStorageClass() == VarDecl::Extern)
3628      Diag(VDecl->getLocation(), diag::warn_extern_init);
3629    if (!VDecl->isInvalidDecl())
3630      if (CheckInitializerTypes(Init, DclT, Entity, Kind))
3631        VDecl->setInvalidDecl();
3632
3633    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3634    // Don't check invalid declarations to avoid emitting useless diagnostics.
3635    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3636      // C99 6.7.8p4. All file scoped initializers need to be constant.
3637      CheckForConstantInitializer(Init, DclT);
3638    }
3639  }
3640  // If the type changed, it means we had an incomplete type that was
3641  // completed by the initializer. For example:
3642  //   int ary[] = { 1, 3, 5 };
3643  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3644  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3645    VDecl->setType(DclT);
3646    Init->setType(DclT);
3647  }
3648
3649  Init = MaybeCreateCXXExprWithTemporaries(Init);
3650  // Attach the initializer to the decl.
3651  VDecl->setInit(Context, Init);
3652
3653  // If the previous declaration of VDecl was a tentative definition,
3654  // remove it from the set of tentative definitions.
3655  if (VDecl->getPreviousDeclaration() &&
3656      VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3657    bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3658    assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
3659  }
3660
3661  return;
3662}
3663
3664void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3665                                  bool TypeContainsUndeducedAuto) {
3666  Decl *RealDecl = dcl.getAs<Decl>();
3667
3668  // If there is no declaration, there was an error parsing it. Just ignore it.
3669  if (RealDecl == 0)
3670    return;
3671
3672  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3673    QualType Type = Var->getType();
3674
3675    // Record tentative definitions.
3676    if (Var->isTentativeDefinition(Context)) {
3677      std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
3678        InsertPair =
3679           TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
3680
3681      // Keep the latest definition in the map.  If we see 'int i; int i;' we
3682      // want the second one in the map.
3683      InsertPair.first->second = Var;
3684
3685      // However, for the list, we don't care about the order, just make sure
3686      // that there are no dupes for a given declaration name.
3687      if (InsertPair.second)
3688        TentativeDefinitionList.push_back(Var->getDeclName());
3689    }
3690
3691    // C++ [dcl.init.ref]p3:
3692    //   The initializer can be omitted for a reference only in a
3693    //   parameter declaration (8.3.5), in the declaration of a
3694    //   function return type, in the declaration of a class member
3695    //   within its class declaration (9.2), and where the extern
3696    //   specifier is explicitly used.
3697    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3698      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3699        << Var->getDeclName()
3700        << SourceRange(Var->getLocation(), Var->getLocation());
3701      Var->setInvalidDecl();
3702      return;
3703    }
3704
3705    // C++0x [dcl.spec.auto]p3
3706    if (TypeContainsUndeducedAuto) {
3707      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3708        << Var->getDeclName() << Type;
3709      Var->setInvalidDecl();
3710      return;
3711    }
3712
3713    // An array without size is an incomplete type, and there are no special
3714    // rules in C++ to make such a definition acceptable.
3715    if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3716        !Var->hasExternalStorage()) {
3717      Diag(Var->getLocation(),
3718           diag::err_typecheck_incomplete_array_needs_initializer);
3719      Var->setInvalidDecl();
3720      return;
3721    }
3722
3723    // C++ [temp.expl.spec]p15:
3724    //   An explicit specialization of a static data member of a template is a
3725    //   definition if the declaration includes an initializer; otherwise, it
3726    //   is a declaration.
3727    if (Var->isStaticDataMember() &&
3728        Var->getInstantiatedFromStaticDataMember() &&
3729        Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3730      return;
3731
3732    // C++ [dcl.init]p9:
3733    //   If no initializer is specified for an object, and the object
3734    //   is of (possibly cv-qualified) non-POD class type (or array
3735    //   thereof), the object shall be default-initialized; if the
3736    //   object is of const-qualified type, the underlying class type
3737    //   shall have a user-declared default constructor.
3738    //
3739    // FIXME: Diagnose the "user-declared default constructor" bit.
3740    if (getLangOptions().CPlusPlus) {
3741      QualType InitType = Type;
3742      if (const ArrayType *Array = Context.getAsArrayType(Type))
3743        InitType = Context.getBaseElementType(Array);
3744      if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
3745          InitType->isRecordType() && !InitType->isDependentType()) {
3746        if (!RequireCompleteType(Var->getLocation(), InitType,
3747                                 diag::err_invalid_incomplete_type_use)) {
3748          ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3749
3750          CXXConstructorDecl *Constructor
3751            = PerformInitializationByConstructor(InitType,
3752                                                 MultiExprArg(*this, 0, 0),
3753                                                 Var->getLocation(),
3754                                               SourceRange(Var->getLocation(),
3755                                                           Var->getLocation()),
3756                                                 Var->getDeclName(),
3757                         InitializationKind::CreateDefault(Var->getLocation()),
3758                                                 ConstructorArgs);
3759
3760          // FIXME: Location info for the variable initialization?
3761          if (!Constructor)
3762            Var->setInvalidDecl();
3763          else {
3764            // FIXME: Cope with initialization of arrays
3765            if (!Constructor->isTrivial() &&
3766                InitializeVarWithConstructor(Var, Constructor,
3767                                             move_arg(ConstructorArgs)))
3768              Var->setInvalidDecl();
3769
3770            FinalizeVarWithDestructor(Var, InitType);
3771          }
3772        } else {
3773          Var->setInvalidDecl();
3774        }
3775      }
3776
3777      // The variable can not have an abstract class type.
3778      if (RequireNonAbstractType(Var->getLocation(), Type,
3779                                 diag::err_abstract_type_in_decl,
3780                                 AbstractVariableType))
3781        Var->setInvalidDecl();
3782    }
3783
3784#if 0
3785    // FIXME: Temporarily disabled because we are not properly parsing
3786    // linkage specifications on declarations, e.g.,
3787    //
3788    //   extern "C" const CGPoint CGPointerZero;
3789    //
3790    // C++ [dcl.init]p9:
3791    //
3792    //     If no initializer is specified for an object, and the
3793    //     object is of (possibly cv-qualified) non-POD class type (or
3794    //     array thereof), the object shall be default-initialized; if
3795    //     the object is of const-qualified type, the underlying class
3796    //     type shall have a user-declared default
3797    //     constructor. Otherwise, if no initializer is specified for
3798    //     an object, the object and its subobjects, if any, have an
3799    //     indeterminate initial value; if the object or any of its
3800    //     subobjects are of const-qualified type, the program is
3801    //     ill-formed.
3802    //
3803    // This isn't technically an error in C, so we don't diagnose it.
3804    //
3805    // FIXME: Actually perform the POD/user-defined default
3806    // constructor check.
3807    if (getLangOptions().CPlusPlus &&
3808        Context.getCanonicalType(Type).isConstQualified() &&
3809        !Var->hasExternalStorage())
3810      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
3811        << Var->getName()
3812        << SourceRange(Var->getLocation(), Var->getLocation());
3813#endif
3814  }
3815}
3816
3817Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3818                                                   DeclPtrTy *Group,
3819                                                   unsigned NumDecls) {
3820  llvm::SmallVector<Decl*, 8> Decls;
3821
3822  if (DS.isTypeSpecOwned())
3823    Decls.push_back((Decl*)DS.getTypeRep());
3824
3825  for (unsigned i = 0; i != NumDecls; ++i)
3826    if (Decl *D = Group[i].getAs<Decl>())
3827      Decls.push_back(D);
3828
3829  // Perform semantic analysis that depends on having fully processed both
3830  // the declarator and initializer.
3831  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3832    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3833    if (!IDecl)
3834      continue;
3835    QualType T = IDecl->getType();
3836
3837    // Block scope. C99 6.7p7: If an identifier for an object is declared with
3838    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3839    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3840      if (T->isDependentType()) {
3841        // If T is dependent, we should not require a complete type.
3842        // (RequireCompleteType shouldn't be called with dependent types.)
3843        // But we still can at least check if we've got an array of unspecified
3844        // size without an initializer.
3845        if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3846            !IDecl->getInit()) {
3847          Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3848            << T;
3849          IDecl->setInvalidDecl();
3850        }
3851      } else if (!IDecl->isInvalidDecl()) {
3852        // If T is an incomplete array type with an initializer list that is
3853        // dependent on something, its size has not been fixed. We could attempt
3854        // to fix the size for such arrays, but we would still have to check
3855        // here for initializers containing a C++0x vararg expansion, e.g.
3856        // template <typename... Args> void f(Args... args) {
3857        //   int vals[] = { args };
3858        // }
3859        const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
3860        Expr *Init = IDecl->getInit();
3861        if (IAT && Init &&
3862            (Init->isTypeDependent() || Init->isValueDependent())) {
3863          // Check that the member type of the array is complete, at least.
3864          if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3865                                  diag::err_typecheck_decl_incomplete_type))
3866            IDecl->setInvalidDecl();
3867        } else if (RequireCompleteType(IDecl->getLocation(), T,
3868                                      diag::err_typecheck_decl_incomplete_type))
3869          IDecl->setInvalidDecl();
3870      }
3871    }
3872    // File scope. C99 6.9.2p2: A declaration of an identifier for an
3873    // object that has file scope without an initializer, and without a
3874    // storage-class specifier or with the storage-class specifier "static",
3875    // constitutes a tentative definition. Note: A tentative definition with
3876    // external linkage is valid (C99 6.2.2p5).
3877    if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3878      if (const IncompleteArrayType *ArrayT
3879          = Context.getAsIncompleteArrayType(T)) {
3880        if (RequireCompleteType(IDecl->getLocation(),
3881                                ArrayT->getElementType(),
3882                                diag::err_illegal_decl_array_incomplete_type))
3883          IDecl->setInvalidDecl();
3884      } else if (IDecl->getStorageClass() == VarDecl::Static) {
3885        // C99 6.9.2p3: If the declaration of an identifier for an object is
3886        // a tentative definition and has internal linkage (C99 6.2.2p3), the
3887        // declared type shall not be an incomplete type.
3888        // NOTE: code such as the following
3889        //     static struct s;
3890        //     struct s { int a; };
3891        // is accepted by gcc. Hence here we issue a warning instead of
3892        // an error and we do not invalidate the static declaration.
3893        // NOTE: to avoid multiple warnings, only check the first declaration.
3894        if (IDecl->getPreviousDeclaration() == 0)
3895          RequireCompleteType(IDecl->getLocation(), T,
3896                              diag::ext_typecheck_decl_incomplete_type);
3897      }
3898    }
3899  }
3900  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3901                                                   Decls.data(), Decls.size()));
3902}
3903
3904
3905/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3906/// to introduce parameters into function prototype scope.
3907Sema::DeclPtrTy
3908Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3909  const DeclSpec &DS = D.getDeclSpec();
3910
3911  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3912  VarDecl::StorageClass StorageClass = VarDecl::None;
3913  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3914    StorageClass = VarDecl::Register;
3915  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3916    Diag(DS.getStorageClassSpecLoc(),
3917         diag::err_invalid_storage_class_in_func_decl);
3918    D.getMutableDeclSpec().ClearStorageClassSpecs();
3919  }
3920
3921  if (D.getDeclSpec().isThreadSpecified())
3922    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3923
3924  DiagnoseFunctionSpecifiers(D);
3925
3926  // Check that there are no default arguments inside the type of this
3927  // parameter (C++ only).
3928  if (getLangOptions().CPlusPlus)
3929    CheckExtraCXXDefaultArguments(D);
3930
3931  TypeSourceInfo *TInfo = 0;
3932  TagDecl *OwnedDecl = 0;
3933  QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
3934
3935  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3936    // C++ [dcl.fct]p6:
3937    //   Types shall not be defined in return or parameter types.
3938    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3939      << Context.getTypeDeclType(OwnedDecl);
3940  }
3941
3942  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3943  // Can this happen for params?  We already checked that they don't conflict
3944  // among each other.  Here they can only shadow globals, which is ok.
3945  IdentifierInfo *II = D.getIdentifier();
3946  if (II) {
3947    if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3948      if (PrevDecl->isTemplateParameter()) {
3949        // Maybe we will complain about the shadowed template parameter.
3950        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3951        // Just pretend that we didn't see the previous declaration.
3952        PrevDecl = 0;
3953      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3954        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3955
3956        // Recover by removing the name
3957        II = 0;
3958        D.SetIdentifier(0, D.getIdentifierLoc());
3959      }
3960    }
3961  }
3962
3963  // Parameters can not be abstract class types.
3964  // For record types, this is done by the AbstractClassUsageDiagnoser once
3965  // the class has been completely parsed.
3966  if (!CurContext->isRecord() &&
3967      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3968                             diag::err_abstract_type_in_decl,
3969                             AbstractParamType))
3970    D.setInvalidType(true);
3971
3972  QualType T = adjustParameterType(parmDeclType);
3973
3974  ParmVarDecl *New
3975    = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
3976                          T, TInfo, StorageClass, 0);
3977
3978  if (D.isInvalidType())
3979    New->setInvalidDecl();
3980
3981  // Parameter declarators cannot be interface types. All ObjC objects are
3982  // passed by reference.
3983  if (T->isObjCInterfaceType()) {
3984    Diag(D.getIdentifierLoc(),
3985         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3986    New->setInvalidDecl();
3987  }
3988
3989  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3990  if (D.getCXXScopeSpec().isSet()) {
3991    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3992      << D.getCXXScopeSpec().getRange();
3993    New->setInvalidDecl();
3994  }
3995
3996  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3997  // duration shall not be qualified by an address-space qualifier."
3998  // Since all parameters have automatic store duration, they can not have
3999  // an address space.
4000  if (T.getAddressSpace() != 0) {
4001    Diag(D.getIdentifierLoc(),
4002         diag::err_arg_with_address_space);
4003    New->setInvalidDecl();
4004  }
4005
4006
4007  // Add the parameter declaration into this scope.
4008  S->AddDecl(DeclPtrTy::make(New));
4009  if (II)
4010    IdResolver.AddDecl(New);
4011
4012  ProcessDeclAttributes(S, New, D);
4013
4014  if (New->hasAttr<BlocksAttr>()) {
4015    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4016  }
4017  return DeclPtrTy::make(New);
4018}
4019
4020void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4021                                           SourceLocation LocAfterDecls) {
4022  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4023         "Not a function declarator!");
4024  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4025
4026  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4027  // for a K&R function.
4028  if (!FTI.hasPrototype) {
4029    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4030      --i;
4031      if (FTI.ArgInfo[i].Param == 0) {
4032        llvm::SmallString<256> Code;
4033        llvm::raw_svector_ostream(Code) << "  int "
4034                                        << FTI.ArgInfo[i].Ident->getName()
4035                                        << ";\n";
4036        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4037          << FTI.ArgInfo[i].Ident
4038          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
4039
4040        // Implicitly declare the argument as type 'int' for lack of a better
4041        // type.
4042        DeclSpec DS;
4043        const char* PrevSpec; // unused
4044        unsigned DiagID; // unused
4045        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4046                           PrevSpec, DiagID);
4047        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4048        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4049        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4050      }
4051    }
4052  }
4053}
4054
4055Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4056                                              Declarator &D) {
4057  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4058  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4059         "Not a function declarator!");
4060  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4061
4062  if (FTI.hasPrototype) {
4063    // FIXME: Diagnose arguments without names in C.
4064  }
4065
4066  Scope *ParentScope = FnBodyScope->getParent();
4067
4068  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4069                                  MultiTemplateParamsArg(*this),
4070                                  /*IsFunctionDefinition=*/true);
4071  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4072}
4073
4074static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4075  // Don't warn about invalid declarations.
4076  if (FD->isInvalidDecl())
4077    return false;
4078
4079  // Or declarations that aren't global.
4080  if (!FD->isGlobal())
4081    return false;
4082
4083  // Don't warn about C++ member functions.
4084  if (isa<CXXMethodDecl>(FD))
4085    return false;
4086
4087  // Don't warn about 'main'.
4088  if (FD->isMain())
4089    return false;
4090
4091  // Don't warn about inline functions.
4092  if (FD->isInlineSpecified())
4093    return false;
4094
4095  // Don't warn about function templates.
4096  if (FD->getDescribedFunctionTemplate())
4097    return false;
4098
4099  // Don't warn about function template specializations.
4100  if (FD->isFunctionTemplateSpecialization())
4101    return false;
4102
4103  bool MissingPrototype = true;
4104  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4105       Prev; Prev = Prev->getPreviousDeclaration()) {
4106    // Ignore any declarations that occur in function or method
4107    // scope, because they aren't visible from the header.
4108    if (Prev->getDeclContext()->isFunctionOrMethod())
4109      continue;
4110
4111    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4112    break;
4113  }
4114
4115  return MissingPrototype;
4116}
4117
4118Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4119  // Clear the last template instantiation error context.
4120  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4121
4122  if (!D)
4123    return D;
4124  FunctionDecl *FD = 0;
4125
4126  if (FunctionTemplateDecl *FunTmpl
4127        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4128    FD = FunTmpl->getTemplatedDecl();
4129  else
4130    FD = cast<FunctionDecl>(D.getAs<Decl>());
4131
4132  CurFunctionNeedsScopeChecking = false;
4133
4134  // See if this is a redefinition.
4135  const FunctionDecl *Definition;
4136  if (FD->getBody(Definition)) {
4137    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4138    Diag(Definition->getLocation(), diag::note_previous_definition);
4139  }
4140
4141  // Builtin functions cannot be defined.
4142  if (unsigned BuiltinID = FD->getBuiltinID()) {
4143    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4144      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4145      FD->setInvalidDecl();
4146    }
4147  }
4148
4149  // The return type of a function definition must be complete
4150  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4151  QualType ResultType = FD->getResultType();
4152  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4153      !FD->isInvalidDecl() &&
4154      RequireCompleteType(FD->getLocation(), ResultType,
4155                          diag::err_func_def_incomplete_result))
4156    FD->setInvalidDecl();
4157
4158  // GNU warning -Wmissing-prototypes:
4159  //   Warn if a global function is defined without a previous
4160  //   prototype declaration. This warning is issued even if the
4161  //   definition itself provides a prototype. The aim is to detect
4162  //   global functions that fail to be declared in header files.
4163  if (ShouldWarnAboutMissingPrototype(FD))
4164    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4165
4166  if (FnBodyScope)
4167    PushDeclContext(FnBodyScope, FD);
4168
4169  // Check the validity of our function parameters
4170  CheckParmsForFunctionDef(FD);
4171
4172  // Introduce our parameters into the function scope
4173  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4174    ParmVarDecl *Param = FD->getParamDecl(p);
4175    Param->setOwningFunction(FD);
4176
4177    // If this has an identifier, add it to the scope stack.
4178    if (Param->getIdentifier() && FnBodyScope)
4179      PushOnScopeChains(Param, FnBodyScope);
4180  }
4181
4182  // Checking attributes of current function definition
4183  // dllimport attribute.
4184  if (FD->getAttr<DLLImportAttr>() &&
4185      (!FD->getAttr<DLLExportAttr>())) {
4186    // dllimport attribute cannot be applied to definition.
4187    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4188      Diag(FD->getLocation(),
4189           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4190        << "dllimport";
4191      FD->setInvalidDecl();
4192      return DeclPtrTy::make(FD);
4193    } else {
4194      // If a symbol previously declared dllimport is later defined, the
4195      // attribute is ignored in subsequent references, and a warning is
4196      // emitted.
4197      Diag(FD->getLocation(),
4198           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4199        << FD->getNameAsCString() << "dllimport";
4200    }
4201  }
4202  return DeclPtrTy::make(FD);
4203}
4204
4205Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4206  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4207}
4208
4209Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4210                                              bool IsInstantiation) {
4211  Decl *dcl = D.getAs<Decl>();
4212  Stmt *Body = BodyArg.takeAs<Stmt>();
4213
4214  FunctionDecl *FD = 0;
4215  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4216  if (FunTmpl)
4217    FD = FunTmpl->getTemplatedDecl();
4218  else
4219    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4220
4221  if (FD) {
4222    FD->setBody(Body);
4223    if (FD->isMain())
4224      // C and C++ allow for main to automagically return 0.
4225      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4226      FD->setHasImplicitReturnZero(true);
4227    else
4228      CheckFallThroughForFunctionDef(FD, Body);
4229
4230    if (!FD->isInvalidDecl())
4231      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4232
4233    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4234      MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4235
4236    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4237  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4238    assert(MD == getCurMethodDecl() && "Method parsing confused");
4239    MD->setBody(Body);
4240    CheckFallThroughForFunctionDef(MD, Body);
4241    MD->setEndLoc(Body->getLocEnd());
4242
4243    if (!MD->isInvalidDecl())
4244      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4245  } else {
4246    Body->Destroy(Context);
4247    return DeclPtrTy();
4248  }
4249  if (!IsInstantiation)
4250    PopDeclContext();
4251
4252  // Verify and clean out per-function state.
4253
4254  assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4255
4256  // Check goto/label use.
4257  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4258       I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4259    LabelStmt *L = I->second;
4260
4261    // Verify that we have no forward references left.  If so, there was a goto
4262    // or address of a label taken, but no definition of it.  Label fwd
4263    // definitions are indicated with a null substmt.
4264    if (L->getSubStmt() != 0)
4265      continue;
4266
4267    // Emit error.
4268    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4269
4270    // At this point, we have gotos that use the bogus label.  Stitch it into
4271    // the function body so that they aren't leaked and that the AST is well
4272    // formed.
4273    if (Body == 0) {
4274      // The whole function wasn't parsed correctly, just delete this.
4275      L->Destroy(Context);
4276      continue;
4277    }
4278
4279    // Otherwise, the body is valid: we want to stitch the label decl into the
4280    // function somewhere so that it is properly owned and so that the goto
4281    // has a valid target.  Do this by creating a new compound stmt with the
4282    // label in it.
4283
4284    // Give the label a sub-statement.
4285    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4286
4287    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4288                               cast<CXXTryStmt>(Body)->getTryBlock() :
4289                               cast<CompoundStmt>(Body);
4290    std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4291    Elements.push_back(L);
4292    Compound->setStmts(Context, &Elements[0], Elements.size());
4293  }
4294  FunctionLabelMap.clear();
4295
4296  if (!Body) return D;
4297
4298  // Verify that that gotos and switch cases don't jump into scopes illegally.
4299  if (CurFunctionNeedsScopeChecking)
4300    DiagnoseInvalidJumps(Body);
4301
4302  // C++ constructors that have function-try-blocks can't have return
4303  // statements in the handlers of that block. (C++ [except.handle]p14)
4304  // Verify this.
4305  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4306    DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4307
4308  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4309    MarkBaseAndMemberDestructorsReferenced(Destructor);
4310
4311  // If any errors have occurred, clear out any temporaries that may have
4312  // been leftover. This ensures that these temporaries won't be picked up for
4313  // deletion in some later function.
4314  if (PP.getDiagnostics().hasErrorOccurred())
4315    ExprTemporaries.clear();
4316
4317  assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4318  return D;
4319}
4320
4321/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4322/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4323NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4324                                          IdentifierInfo &II, Scope *S) {
4325  // Before we produce a declaration for an implicitly defined
4326  // function, see whether there was a locally-scoped declaration of
4327  // this name as a function or variable. If so, use that
4328  // (non-visible) declaration, and complain about it.
4329  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4330    = LocallyScopedExternalDecls.find(&II);
4331  if (Pos != LocallyScopedExternalDecls.end()) {
4332    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4333    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4334    return Pos->second;
4335  }
4336
4337  // Extension in C99.  Legal in C90, but warn about it.
4338  if (II.getName().startswith("__builtin_"))
4339    Diag(Loc, diag::warn_builtin_unknown) << &II;
4340  else if (getLangOptions().C99)
4341    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4342  else
4343    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4344
4345  // Set a Declarator for the implicit definition: int foo();
4346  const char *Dummy;
4347  DeclSpec DS;
4348  unsigned DiagID;
4349  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4350  Error = Error; // Silence warning.
4351  assert(!Error && "Error setting up implicit decl!");
4352  Declarator D(DS, Declarator::BlockContext);
4353  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4354                                             0, 0, false, SourceLocation(),
4355                                             false, 0,0,0, Loc, Loc, D),
4356                SourceLocation());
4357  D.SetIdentifier(&II, Loc);
4358
4359  // Insert this function into translation-unit scope.
4360
4361  DeclContext *PrevDC = CurContext;
4362  CurContext = Context.getTranslationUnitDecl();
4363
4364  FunctionDecl *FD =
4365 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4366  FD->setImplicit();
4367
4368  CurContext = PrevDC;
4369
4370  AddKnownFunctionAttributes(FD);
4371
4372  return FD;
4373}
4374
4375/// \brief Adds any function attributes that we know a priori based on
4376/// the declaration of this function.
4377///
4378/// These attributes can apply both to implicitly-declared builtins
4379/// (like __builtin___printf_chk) or to library-declared functions
4380/// like NSLog or printf.
4381void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4382  if (FD->isInvalidDecl())
4383    return;
4384
4385  // If this is a built-in function, map its builtin attributes to
4386  // actual attributes.
4387  if (unsigned BuiltinID = FD->getBuiltinID()) {
4388    // Handle printf-formatting attributes.
4389    unsigned FormatIdx;
4390    bool HasVAListArg;
4391    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4392      if (!FD->getAttr<FormatAttr>())
4393        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4394                                             HasVAListArg ? 0 : FormatIdx + 2));
4395    }
4396
4397    // Mark const if we don't care about errno and that is the only
4398    // thing preventing the function from being const. This allows
4399    // IRgen to use LLVM intrinsics for such functions.
4400    if (!getLangOptions().MathErrno &&
4401        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4402      if (!FD->getAttr<ConstAttr>())
4403        FD->addAttr(::new (Context) ConstAttr());
4404    }
4405
4406    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4407      FD->addAttr(::new (Context) NoReturnAttr());
4408  }
4409
4410  IdentifierInfo *Name = FD->getIdentifier();
4411  if (!Name)
4412    return;
4413  if ((!getLangOptions().CPlusPlus &&
4414       FD->getDeclContext()->isTranslationUnit()) ||
4415      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4416       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4417       LinkageSpecDecl::lang_c)) {
4418    // Okay: this could be a libc/libm/Objective-C function we know
4419    // about.
4420  } else
4421    return;
4422
4423  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4424    // FIXME: NSLog and NSLogv should be target specific
4425    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4426      // FIXME: We known better than our headers.
4427      const_cast<FormatAttr *>(Format)->setType("printf");
4428    } else
4429      FD->addAttr(::new (Context) FormatAttr("printf", 1,
4430                                             Name->isStr("NSLogv") ? 0 : 2));
4431  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4432    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4433    // target-specific builtins, perhaps?
4434    if (!FD->getAttr<FormatAttr>())
4435      FD->addAttr(::new (Context) FormatAttr("printf", 2,
4436                                             Name->isStr("vasprintf") ? 0 : 3));
4437  }
4438}
4439
4440TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4441                                    TypeSourceInfo *TInfo) {
4442  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4443  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4444
4445  if (!TInfo) {
4446    assert(D.isInvalidType() && "no declarator info for valid type");
4447    TInfo = Context.getTrivialTypeSourceInfo(T);
4448  }
4449
4450  // Scope manipulation handled by caller.
4451  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4452                                           D.getIdentifierLoc(),
4453                                           D.getIdentifier(),
4454                                           TInfo);
4455
4456  if (const TagType *TT = T->getAs<TagType>()) {
4457    TagDecl *TD = TT->getDecl();
4458
4459    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4460    // keep track of the TypedefDecl.
4461    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4462      TD->setTypedefForAnonDecl(NewTD);
4463  }
4464
4465  if (D.isInvalidType())
4466    NewTD->setInvalidDecl();
4467  return NewTD;
4468}
4469
4470
4471/// \brief Determine whether a tag with a given kind is acceptable
4472/// as a redeclaration of the given tag declaration.
4473///
4474/// \returns true if the new tag kind is acceptable, false otherwise.
4475bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4476                                        TagDecl::TagKind NewTag,
4477                                        SourceLocation NewTagLoc,
4478                                        const IdentifierInfo &Name) {
4479  // C++ [dcl.type.elab]p3:
4480  //   The class-key or enum keyword present in the
4481  //   elaborated-type-specifier shall agree in kind with the
4482  //   declaration to which the name in theelaborated-type-specifier
4483  //   refers. This rule also applies to the form of
4484  //   elaborated-type-specifier that declares a class-name or
4485  //   friend class since it can be construed as referring to the
4486  //   definition of the class. Thus, in any
4487  //   elaborated-type-specifier, the enum keyword shall be used to
4488  //   refer to an enumeration (7.2), the union class-keyshall be
4489  //   used to refer to a union (clause 9), and either the class or
4490  //   struct class-key shall be used to refer to a class (clause 9)
4491  //   declared using the class or struct class-key.
4492  TagDecl::TagKind OldTag = Previous->getTagKind();
4493  if (OldTag == NewTag)
4494    return true;
4495
4496  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4497      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4498    // Warn about the struct/class tag mismatch.
4499    bool isTemplate = false;
4500    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4501      isTemplate = Record->getDescribedClassTemplate();
4502
4503    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4504      << (NewTag == TagDecl::TK_class)
4505      << isTemplate << &Name
4506      << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4507                              OldTag == TagDecl::TK_class? "class" : "struct");
4508    Diag(Previous->getLocation(), diag::note_previous_use);
4509    return true;
4510  }
4511  return false;
4512}
4513
4514/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4515/// former case, Name will be non-null.  In the later case, Name will be null.
4516/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4517/// reference/declaration/definition of a tag.
4518Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4519                               SourceLocation KWLoc, const CXXScopeSpec &SS,
4520                               IdentifierInfo *Name, SourceLocation NameLoc,
4521                               AttributeList *Attr, AccessSpecifier AS,
4522                               MultiTemplateParamsArg TemplateParameterLists,
4523                               bool &OwnedDecl, bool &IsDependent) {
4524  // If this is not a definition, it must have a name.
4525  assert((Name != 0 || TUK == TUK_Definition) &&
4526         "Nameless record must be a definition!");
4527
4528  OwnedDecl = false;
4529  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4530
4531  // FIXME: Check explicit specializations more carefully.
4532  bool isExplicitSpecialization = false;
4533  if (TUK != TUK_Reference) {
4534    if (TemplateParameterList *TemplateParams
4535          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4536                        (TemplateParameterList**)TemplateParameterLists.get(),
4537                                              TemplateParameterLists.size(),
4538                                                    isExplicitSpecialization)) {
4539      if (TemplateParams->size() > 0) {
4540        // This is a declaration or definition of a class template (which may
4541        // be a member of another template).
4542        OwnedDecl = false;
4543        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4544                                               SS, Name, NameLoc, Attr,
4545                                               TemplateParams,
4546                                               AS);
4547        TemplateParameterLists.release();
4548        return Result.get();
4549      } else {
4550        // The "template<>" header is extraneous.
4551        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4552          << ElaboratedType::getNameForTagKind(Kind) << Name;
4553        isExplicitSpecialization = true;
4554      }
4555    }
4556
4557    TemplateParameterLists.release();
4558  }
4559
4560  DeclContext *SearchDC = CurContext;
4561  DeclContext *DC = CurContext;
4562  bool isStdBadAlloc = false;
4563  bool Invalid = false;
4564
4565  RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4566                                                   : NotForRedeclaration);
4567
4568  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4569
4570  if (Name && SS.isNotEmpty()) {
4571    // We have a nested-name tag ('struct foo::bar').
4572
4573    // Check for invalid 'foo::'.
4574    if (SS.isInvalid()) {
4575      Name = 0;
4576      goto CreateNewDecl;
4577    }
4578
4579    // If this is a friend or a reference to a class in a dependent
4580    // context, don't try to make a decl for it.
4581    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4582      DC = computeDeclContext(SS, false);
4583      if (!DC) {
4584        IsDependent = true;
4585        return DeclPtrTy();
4586      }
4587    }
4588
4589    if (RequireCompleteDeclContext(SS))
4590      return DeclPtrTy::make((Decl *)0);
4591
4592    DC = computeDeclContext(SS, true);
4593    SearchDC = DC;
4594    // Look-up name inside 'foo::'.
4595    LookupQualifiedName(Previous, DC);
4596
4597    if (Previous.isAmbiguous())
4598      return DeclPtrTy();
4599
4600    // A tag 'foo::bar' must already exist.
4601    if (Previous.empty()) {
4602      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4603      Name = 0;
4604      Invalid = true;
4605      goto CreateNewDecl;
4606    }
4607  } else if (Name) {
4608    // If this is a named struct, check to see if there was a previous forward
4609    // declaration or definition.
4610    // FIXME: We're looking into outer scopes here, even when we
4611    // shouldn't be. Doing so can result in ambiguities that we
4612    // shouldn't be diagnosing.
4613    LookupName(Previous, S);
4614
4615    // Note:  there used to be some attempt at recovery here.
4616    if (Previous.isAmbiguous())
4617      return DeclPtrTy();
4618
4619    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4620      // FIXME: This makes sure that we ignore the contexts associated
4621      // with C structs, unions, and enums when looking for a matching
4622      // tag declaration or definition. See the similar lookup tweak
4623      // in Sema::LookupName; is there a better way to deal with this?
4624      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4625        SearchDC = SearchDC->getParent();
4626    }
4627  }
4628
4629  if (Previous.isSingleResult() &&
4630      Previous.getFoundDecl()->isTemplateParameter()) {
4631    // Maybe we will complain about the shadowed template parameter.
4632    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4633    // Just pretend that we didn't see the previous declaration.
4634    Previous.clear();
4635  }
4636
4637  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4638      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4639    // This is a declaration of or a reference to "std::bad_alloc".
4640    isStdBadAlloc = true;
4641
4642    if (Previous.empty() && StdBadAlloc) {
4643      // std::bad_alloc has been implicitly declared (but made invisible to
4644      // name lookup). Fill in this implicit declaration as the previous
4645      // declaration, so that the declarations get chained appropriately.
4646      Previous.addDecl(StdBadAlloc);
4647    }
4648  }
4649
4650  if (!Previous.empty()) {
4651    assert(Previous.isSingleResult());
4652    NamedDecl *PrevDecl = Previous.getFoundDecl();
4653    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4654      // If this is a use of a previous tag, or if the tag is already declared
4655      // in the same scope (so that the definition/declaration completes or
4656      // rementions the tag), reuse the decl.
4657      if (TUK == TUK_Reference || TUK == TUK_Friend ||
4658          isDeclInScope(PrevDecl, SearchDC, S)) {
4659        // Make sure that this wasn't declared as an enum and now used as a
4660        // struct or something similar.
4661        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4662          bool SafeToContinue
4663            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4664               Kind != TagDecl::TK_enum);
4665          if (SafeToContinue)
4666            Diag(KWLoc, diag::err_use_with_wrong_tag)
4667              << Name
4668              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4669                                                  PrevTagDecl->getKindName());
4670          else
4671            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4672          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4673
4674          if (SafeToContinue)
4675            Kind = PrevTagDecl->getTagKind();
4676          else {
4677            // Recover by making this an anonymous redefinition.
4678            Name = 0;
4679            Previous.clear();
4680            Invalid = true;
4681          }
4682        }
4683
4684        if (!Invalid) {
4685          // If this is a use, just return the declaration we found.
4686
4687          // FIXME: In the future, return a variant or some other clue
4688          // for the consumer of this Decl to know it doesn't own it.
4689          // For our current ASTs this shouldn't be a problem, but will
4690          // need to be changed with DeclGroups.
4691          if (TUK == TUK_Reference || TUK == TUK_Friend)
4692            return DeclPtrTy::make(PrevTagDecl);
4693
4694          // Diagnose attempts to redefine a tag.
4695          if (TUK == TUK_Definition) {
4696            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4697              // If we're defining a specialization and the previous definition
4698              // is from an implicit instantiation, don't emit an error
4699              // here; we'll catch this in the general case below.
4700              if (!isExplicitSpecialization ||
4701                  !isa<CXXRecordDecl>(Def) ||
4702                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4703                                               == TSK_ExplicitSpecialization) {
4704                Diag(NameLoc, diag::err_redefinition) << Name;
4705                Diag(Def->getLocation(), diag::note_previous_definition);
4706                // If this is a redefinition, recover by making this
4707                // struct be anonymous, which will make any later
4708                // references get the previous definition.
4709                Name = 0;
4710                Previous.clear();
4711                Invalid = true;
4712              }
4713            } else {
4714              // If the type is currently being defined, complain
4715              // about a nested redefinition.
4716              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4717              if (Tag->isBeingDefined()) {
4718                Diag(NameLoc, diag::err_nested_redefinition) << Name;
4719                Diag(PrevTagDecl->getLocation(),
4720                     diag::note_previous_definition);
4721                Name = 0;
4722                Previous.clear();
4723                Invalid = true;
4724              }
4725            }
4726
4727            // Okay, this is definition of a previously declared or referenced
4728            // tag PrevDecl. We're going to create a new Decl for it.
4729          }
4730        }
4731        // If we get here we have (another) forward declaration or we
4732        // have a definition.  Just create a new decl.
4733
4734      } else {
4735        // If we get here, this is a definition of a new tag type in a nested
4736        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4737        // new decl/type.  We set PrevDecl to NULL so that the entities
4738        // have distinct types.
4739        Previous.clear();
4740      }
4741      // If we get here, we're going to create a new Decl. If PrevDecl
4742      // is non-NULL, it's a definition of the tag declared by
4743      // PrevDecl. If it's NULL, we have a new definition.
4744    } else {
4745      // PrevDecl is a namespace, template, or anything else
4746      // that lives in the IDNS_Tag identifier namespace.
4747      if (isDeclInScope(PrevDecl, SearchDC, S)) {
4748        // The tag name clashes with a namespace name, issue an error and
4749        // recover by making this tag be anonymous.
4750        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4751        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4752        Name = 0;
4753        Previous.clear();
4754        Invalid = true;
4755      } else {
4756        // The existing declaration isn't relevant to us; we're in a
4757        // new scope, so clear out the previous declaration.
4758        Previous.clear();
4759      }
4760    }
4761  } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
4762    // C++ [basic.scope.pdecl]p5:
4763    //   -- for an elaborated-type-specifier of the form
4764    //
4765    //          class-key identifier
4766    //
4767    //      if the elaborated-type-specifier is used in the
4768    //      decl-specifier-seq or parameter-declaration-clause of a
4769    //      function defined in namespace scope, the identifier is
4770    //      declared as a class-name in the namespace that contains
4771    //      the declaration; otherwise, except as a friend
4772    //      declaration, the identifier is declared in the smallest
4773    //      non-class, non-function-prototype scope that contains the
4774    //      declaration.
4775    //
4776    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4777    // C structs and unions.
4778    //
4779    // It is an error in C++ to declare (rather than define) an enum
4780    // type, including via an elaborated type specifier.  We'll
4781    // diagnose that later; for now, declare the enum in the same
4782    // scope as we would have picked for any other tag type.
4783    //
4784    // GNU C also supports this behavior as part of its incomplete
4785    // enum types extension, while GNU C++ does not.
4786    //
4787    // Find the context where we'll be declaring the tag.
4788    // FIXME: We would like to maintain the current DeclContext as the
4789    // lexical context,
4790    while (SearchDC->isRecord())
4791      SearchDC = SearchDC->getParent();
4792
4793    // Find the scope where we'll be declaring the tag.
4794    while (S->isClassScope() ||
4795           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4796           ((S->getFlags() & Scope::DeclScope) == 0) ||
4797           (S->getEntity() &&
4798            ((DeclContext *)S->getEntity())->isTransparentContext()))
4799      S = S->getParent();
4800
4801  } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4802    // C++ [namespace.memdef]p3:
4803    //   If a friend declaration in a non-local class first declares a
4804    //   class or function, the friend class or function is a member of
4805    //   the innermost enclosing namespace.
4806    while (!SearchDC->isFileContext())
4807      SearchDC = SearchDC->getParent();
4808
4809    // The entity of a decl scope is a DeclContext; see PushDeclContext.
4810    while (S->getEntity() != SearchDC)
4811      S = S->getParent();
4812  }
4813
4814CreateNewDecl:
4815
4816  TagDecl *PrevDecl = 0;
4817  if (Previous.isSingleResult())
4818    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4819
4820  // If there is an identifier, use the location of the identifier as the
4821  // location of the decl, otherwise use the location of the struct/union
4822  // keyword.
4823  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4824
4825  // Otherwise, create a new declaration. If there is a previous
4826  // declaration of the same entity, the two will be linked via
4827  // PrevDecl.
4828  TagDecl *New;
4829
4830  if (Kind == TagDecl::TK_enum) {
4831    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4832    // enum X { A, B, C } D;    D should chain to X.
4833    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4834                           cast_or_null<EnumDecl>(PrevDecl));
4835    // If this is an undefined enum, warn.
4836    if (TUK != TUK_Definition && !Invalid)  {
4837      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4838                                              : diag::ext_forward_ref_enum;
4839      Diag(Loc, DK);
4840    }
4841  } else {
4842    // struct/union/class
4843
4844    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4845    // struct X { int A; } D;    D should chain to X.
4846    if (getLangOptions().CPlusPlus) {
4847      // FIXME: Look for a way to use RecordDecl for simple structs.
4848      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4849                                  cast_or_null<CXXRecordDecl>(PrevDecl));
4850
4851      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4852        StdBadAlloc = cast<CXXRecordDecl>(New);
4853    } else
4854      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4855                               cast_or_null<RecordDecl>(PrevDecl));
4856  }
4857
4858  if (Kind != TagDecl::TK_enum) {
4859    // Handle #pragma pack: if the #pragma pack stack has non-default
4860    // alignment, make up a packed attribute for this decl. These
4861    // attributes are checked when the ASTContext lays out the
4862    // structure.
4863    //
4864    // It is important for implementing the correct semantics that this
4865    // happen here (in act on tag decl). The #pragma pack stack is
4866    // maintained as a result of parser callbacks which can occur at
4867    // many points during the parsing of a struct declaration (because
4868    // the #pragma tokens are effectively skipped over during the
4869    // parsing of the struct).
4870    if (unsigned Alignment = getPragmaPackAlignment())
4871      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4872  }
4873
4874  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4875    // C++ [dcl.typedef]p3:
4876    //   [...] Similarly, in a given scope, a class or enumeration
4877    //   shall not be declared with the same name as a typedef-name
4878    //   that is declared in that scope and refers to a type other
4879    //   than the class or enumeration itself.
4880    LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4881                        ForRedeclaration);
4882    LookupName(Lookup, S);
4883    TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
4884    NamedDecl *PrevTypedefNamed = PrevTypedef;
4885    if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4886        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4887          Context.getCanonicalType(Context.getTypeDeclType(New))) {
4888      Diag(Loc, diag::err_tag_definition_of_typedef)
4889        << Context.getTypeDeclType(New)
4890        << PrevTypedef->getUnderlyingType();
4891      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4892      Invalid = true;
4893    }
4894  }
4895
4896  // If this is a specialization of a member class (of a class template),
4897  // check the specialization.
4898  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4899    Invalid = true;
4900
4901  if (Invalid)
4902    New->setInvalidDecl();
4903
4904  if (Attr)
4905    ProcessDeclAttributeList(S, New, Attr);
4906
4907  // If we're declaring or defining a tag in function prototype scope
4908  // in C, note that this type can only be used within the function.
4909  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4910    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4911
4912  // Set the lexical context. If the tag has a C++ scope specifier, the
4913  // lexical context will be different from the semantic context.
4914  New->setLexicalDeclContext(CurContext);
4915
4916  // Mark this as a friend decl if applicable.
4917  if (TUK == TUK_Friend)
4918    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4919
4920  // Set the access specifier.
4921  if (!Invalid && TUK != TUK_Friend)
4922    SetMemberAccessSpecifier(New, PrevDecl, AS);
4923
4924  if (TUK == TUK_Definition)
4925    New->startDefinition();
4926
4927  // If this has an identifier, add it to the scope stack.
4928  if (TUK == TUK_Friend) {
4929    // We might be replacing an existing declaration in the lookup tables;
4930    // if so, borrow its access specifier.
4931    if (PrevDecl)
4932      New->setAccess(PrevDecl->getAccess());
4933
4934    // Friend tag decls are visible in fairly strange ways.
4935    if (!CurContext->isDependentContext()) {
4936      DeclContext *DC = New->getDeclContext()->getLookupContext();
4937      DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4938      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4939        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4940    }
4941  } else if (Name) {
4942    S = getNonFieldDeclScope(S);
4943    PushOnScopeChains(New, S);
4944  } else {
4945    CurContext->addDecl(New);
4946  }
4947
4948  // If this is the C FILE type, notify the AST context.
4949  if (IdentifierInfo *II = New->getIdentifier())
4950    if (!New->isInvalidDecl() &&
4951        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4952        II->isStr("FILE"))
4953      Context.setFILEDecl(New);
4954
4955  OwnedDecl = true;
4956  return DeclPtrTy::make(New);
4957}
4958
4959void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4960  AdjustDeclIfTemplate(TagD);
4961  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4962
4963  // Enter the tag context.
4964  PushDeclContext(S, Tag);
4965
4966  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
4967    FieldCollector->StartClass();
4968
4969    if (Record->getIdentifier()) {
4970      // C++ [class]p2:
4971      //   [...] The class-name is also inserted into the scope of the
4972      //   class itself; this is known as the injected-class-name. For
4973      //   purposes of access checking, the injected-class-name is treated
4974      //   as if it were a public member name.
4975      CXXRecordDecl *InjectedClassName
4976        = CXXRecordDecl::Create(Context, Record->getTagKind(),
4977                                CurContext, Record->getLocation(),
4978                                Record->getIdentifier(),
4979                                Record->getTagKeywordLoc(),
4980                                Record);
4981      InjectedClassName->setImplicit();
4982      InjectedClassName->setAccess(AS_public);
4983      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4984        InjectedClassName->setDescribedClassTemplate(Template);
4985      PushOnScopeChains(InjectedClassName, S);
4986      assert(InjectedClassName->isInjectedClassName() &&
4987             "Broken injected-class-name");
4988    }
4989  }
4990}
4991
4992void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4993                                    SourceLocation RBraceLoc) {
4994  AdjustDeclIfTemplate(TagD);
4995  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4996  Tag->setRBraceLoc(RBraceLoc);
4997
4998  if (isa<CXXRecordDecl>(Tag))
4999    FieldCollector->FinishClass();
5000
5001  // Exit this scope of this tag's definition.
5002  PopDeclContext();
5003
5004  // Notify the consumer that we've defined a tag.
5005  Consumer.HandleTagDeclDefinition(Tag);
5006}
5007
5008// Note that FieldName may be null for anonymous bitfields.
5009bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5010                          QualType FieldTy, const Expr *BitWidth,
5011                          bool *ZeroWidth) {
5012  // Default to true; that shouldn't confuse checks for emptiness
5013  if (ZeroWidth)
5014    *ZeroWidth = true;
5015
5016  // C99 6.7.2.1p4 - verify the field type.
5017  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5018  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5019    // Handle incomplete types with specific error.
5020    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5021      return true;
5022    if (FieldName)
5023      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5024        << FieldName << FieldTy << BitWidth->getSourceRange();
5025    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5026      << FieldTy << BitWidth->getSourceRange();
5027  }
5028
5029  // If the bit-width is type- or value-dependent, don't try to check
5030  // it now.
5031  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5032    return false;
5033
5034  llvm::APSInt Value;
5035  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5036    return true;
5037
5038  if (Value != 0 && ZeroWidth)
5039    *ZeroWidth = false;
5040
5041  // Zero-width bitfield is ok for anonymous field.
5042  if (Value == 0 && FieldName)
5043    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5044
5045  if (Value.isSigned() && Value.isNegative()) {
5046    if (FieldName)
5047      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5048               << FieldName << Value.toString(10);
5049    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5050      << Value.toString(10);
5051  }
5052
5053  if (!FieldTy->isDependentType()) {
5054    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5055    if (Value.getZExtValue() > TypeSize) {
5056      if (FieldName)
5057        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5058          << FieldName << (unsigned)TypeSize;
5059      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5060        << (unsigned)TypeSize;
5061    }
5062  }
5063
5064  return false;
5065}
5066
5067/// ActOnField - Each field of a struct/union/class is passed into this in order
5068/// to create a FieldDecl object for it.
5069Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5070                                 SourceLocation DeclStart,
5071                                 Declarator &D, ExprTy *BitfieldWidth) {
5072  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5073                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5074                               AS_public);
5075  return DeclPtrTy::make(Res);
5076}
5077
5078/// HandleField - Analyze a field of a C struct or a C++ data member.
5079///
5080FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5081                             SourceLocation DeclStart,
5082                             Declarator &D, Expr *BitWidth,
5083                             AccessSpecifier AS) {
5084  IdentifierInfo *II = D.getIdentifier();
5085  SourceLocation Loc = DeclStart;
5086  if (II) Loc = D.getIdentifierLoc();
5087
5088  TypeSourceInfo *TInfo = 0;
5089  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5090  if (getLangOptions().CPlusPlus)
5091    CheckExtraCXXDefaultArguments(D);
5092
5093  DiagnoseFunctionSpecifiers(D);
5094
5095  if (D.getDeclSpec().isThreadSpecified())
5096    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5097
5098  NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5099                                         ForRedeclaration);
5100
5101  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5102    // Maybe we will complain about the shadowed template parameter.
5103    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5104    // Just pretend that we didn't see the previous declaration.
5105    PrevDecl = 0;
5106  }
5107
5108  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5109    PrevDecl = 0;
5110
5111  bool Mutable
5112    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5113  SourceLocation TSSL = D.getSourceRange().getBegin();
5114  FieldDecl *NewFD
5115    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5116                     AS, PrevDecl, &D);
5117  if (NewFD->isInvalidDecl() && PrevDecl) {
5118    // Don't introduce NewFD into scope; there's already something
5119    // with the same name in the same scope.
5120  } else if (II) {
5121    PushOnScopeChains(NewFD, S);
5122  } else
5123    Record->addDecl(NewFD);
5124
5125  return NewFD;
5126}
5127
5128/// \brief Build a new FieldDecl and check its well-formedness.
5129///
5130/// This routine builds a new FieldDecl given the fields name, type,
5131/// record, etc. \p PrevDecl should refer to any previous declaration
5132/// with the same name and in the same scope as the field to be
5133/// created.
5134///
5135/// \returns a new FieldDecl.
5136///
5137/// \todo The Declarator argument is a hack. It will be removed once
5138FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5139                                TypeSourceInfo *TInfo,
5140                                RecordDecl *Record, SourceLocation Loc,
5141                                bool Mutable, Expr *BitWidth,
5142                                SourceLocation TSSL,
5143                                AccessSpecifier AS, NamedDecl *PrevDecl,
5144                                Declarator *D) {
5145  IdentifierInfo *II = Name.getAsIdentifierInfo();
5146  bool InvalidDecl = false;
5147  if (D) InvalidDecl = D->isInvalidType();
5148
5149  // If we receive a broken type, recover by assuming 'int' and
5150  // marking this declaration as invalid.
5151  if (T.isNull()) {
5152    InvalidDecl = true;
5153    T = Context.IntTy;
5154  }
5155
5156  QualType EltTy = Context.getBaseElementType(T);
5157  if (!EltTy->isDependentType() &&
5158      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5159    InvalidDecl = true;
5160
5161  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5162  // than a variably modified type.
5163  if (!InvalidDecl && T->isVariablyModifiedType()) {
5164    bool SizeIsNegative;
5165    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5166                                                           SizeIsNegative);
5167    if (!FixedTy.isNull()) {
5168      Diag(Loc, diag::warn_illegal_constant_array_size);
5169      T = FixedTy;
5170    } else {
5171      if (SizeIsNegative)
5172        Diag(Loc, diag::err_typecheck_negative_array_size);
5173      else
5174        Diag(Loc, diag::err_typecheck_field_variable_size);
5175      InvalidDecl = true;
5176    }
5177  }
5178
5179  // Fields can not have abstract class types
5180  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5181                                             diag::err_abstract_type_in_decl,
5182                                             AbstractFieldType))
5183    InvalidDecl = true;
5184
5185  bool ZeroWidth = false;
5186  // If this is declared as a bit-field, check the bit-field.
5187  if (!InvalidDecl && BitWidth &&
5188      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5189    InvalidDecl = true;
5190    DeleteExpr(BitWidth);
5191    BitWidth = 0;
5192    ZeroWidth = false;
5193  }
5194
5195  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5196                                       BitWidth, Mutable);
5197  if (InvalidDecl)
5198    NewFD->setInvalidDecl();
5199
5200  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5201    Diag(Loc, diag::err_duplicate_member) << II;
5202    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5203    NewFD->setInvalidDecl();
5204  }
5205
5206  if (getLangOptions().CPlusPlus) {
5207    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5208
5209    if (!T->isPODType())
5210      CXXRecord->setPOD(false);
5211    if (!ZeroWidth)
5212      CXXRecord->setEmpty(false);
5213
5214    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5215      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5216
5217      if (!RDecl->hasTrivialConstructor())
5218        CXXRecord->setHasTrivialConstructor(false);
5219      if (!RDecl->hasTrivialCopyConstructor())
5220        CXXRecord->setHasTrivialCopyConstructor(false);
5221      if (!RDecl->hasTrivialCopyAssignment())
5222        CXXRecord->setHasTrivialCopyAssignment(false);
5223      if (!RDecl->hasTrivialDestructor())
5224        CXXRecord->setHasTrivialDestructor(false);
5225
5226      // C++ 9.5p1: An object of a class with a non-trivial
5227      // constructor, a non-trivial copy constructor, a non-trivial
5228      // destructor, or a non-trivial copy assignment operator
5229      // cannot be a member of a union, nor can an array of such
5230      // objects.
5231      // TODO: C++0x alters this restriction significantly.
5232      if (Record->isUnion()) {
5233        // We check for copy constructors before constructors
5234        // because otherwise we'll never get complaints about
5235        // copy constructors.
5236
5237        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5238
5239        CXXSpecialMember member;
5240        if (!RDecl->hasTrivialCopyConstructor())
5241          member = CXXCopyConstructor;
5242        else if (!RDecl->hasTrivialConstructor())
5243          member = CXXDefaultConstructor;
5244        else if (!RDecl->hasTrivialCopyAssignment())
5245          member = CXXCopyAssignment;
5246        else if (!RDecl->hasTrivialDestructor())
5247          member = CXXDestructor;
5248        else
5249          member = invalid;
5250
5251        if (member != invalid) {
5252          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5253          DiagnoseNontrivial(RT, member);
5254          NewFD->setInvalidDecl();
5255        }
5256      }
5257    }
5258  }
5259
5260  // FIXME: We need to pass in the attributes given an AST
5261  // representation, not a parser representation.
5262  if (D)
5263    // FIXME: What to pass instead of TUScope?
5264    ProcessDeclAttributes(TUScope, NewFD, *D);
5265
5266  if (T.isObjCGCWeak())
5267    Diag(Loc, diag::warn_attribute_weak_on_field);
5268
5269  NewFD->setAccess(AS);
5270
5271  // C++ [dcl.init.aggr]p1:
5272  //   An aggregate is an array or a class (clause 9) with [...] no
5273  //   private or protected non-static data members (clause 11).
5274  // A POD must be an aggregate.
5275  if (getLangOptions().CPlusPlus &&
5276      (AS == AS_private || AS == AS_protected)) {
5277    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5278    CXXRecord->setAggregate(false);
5279    CXXRecord->setPOD(false);
5280  }
5281
5282  return NewFD;
5283}
5284
5285/// DiagnoseNontrivial - Given that a class has a non-trivial
5286/// special member, figure out why.
5287void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5288  QualType QT(T, 0U);
5289  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5290
5291  // Check whether the member was user-declared.
5292  switch (member) {
5293  case CXXDefaultConstructor:
5294    if (RD->hasUserDeclaredConstructor()) {
5295      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5296      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5297        const FunctionDecl *body = 0;
5298        ci->getBody(body);
5299        if (!body ||
5300            !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5301          SourceLocation CtorLoc = ci->getLocation();
5302          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5303          return;
5304        }
5305      }
5306
5307      assert(0 && "found no user-declared constructors");
5308      return;
5309    }
5310    break;
5311
5312  case CXXCopyConstructor:
5313    if (RD->hasUserDeclaredCopyConstructor()) {
5314      SourceLocation CtorLoc =
5315        RD->getCopyConstructor(Context, 0)->getLocation();
5316      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5317      return;
5318    }
5319    break;
5320
5321  case CXXCopyAssignment:
5322    if (RD->hasUserDeclaredCopyAssignment()) {
5323      // FIXME: this should use the location of the copy
5324      // assignment, not the type.
5325      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5326      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5327      return;
5328    }
5329    break;
5330
5331  case CXXDestructor:
5332    if (RD->hasUserDeclaredDestructor()) {
5333      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5334      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5335      return;
5336    }
5337    break;
5338  }
5339
5340  typedef CXXRecordDecl::base_class_iterator base_iter;
5341
5342  // Virtual bases and members inhibit trivial copying/construction,
5343  // but not trivial destruction.
5344  if (member != CXXDestructor) {
5345    // Check for virtual bases.  vbases includes indirect virtual bases,
5346    // so we just iterate through the direct bases.
5347    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5348      if (bi->isVirtual()) {
5349        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5350        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5351        return;
5352      }
5353
5354    // Check for virtual methods.
5355    typedef CXXRecordDecl::method_iterator meth_iter;
5356    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5357         ++mi) {
5358      if (mi->isVirtual()) {
5359        SourceLocation MLoc = mi->getSourceRange().getBegin();
5360        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5361        return;
5362      }
5363    }
5364  }
5365
5366  bool (CXXRecordDecl::*hasTrivial)() const;
5367  switch (member) {
5368  case CXXDefaultConstructor:
5369    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5370  case CXXCopyConstructor:
5371    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5372  case CXXCopyAssignment:
5373    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5374  case CXXDestructor:
5375    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5376  default:
5377    assert(0 && "unexpected special member"); return;
5378  }
5379
5380  // Check for nontrivial bases (and recurse).
5381  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5382    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5383    assert(BaseRT && "Don't know how to handle dependent bases");
5384    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5385    if (!(BaseRecTy->*hasTrivial)()) {
5386      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5387      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5388      DiagnoseNontrivial(BaseRT, member);
5389      return;
5390    }
5391  }
5392
5393  // Check for nontrivial members (and recurse).
5394  typedef RecordDecl::field_iterator field_iter;
5395  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5396       ++fi) {
5397    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5398    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5399      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5400
5401      if (!(EltRD->*hasTrivial)()) {
5402        SourceLocation FLoc = (*fi)->getLocation();
5403        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5404        DiagnoseNontrivial(EltRT, member);
5405        return;
5406      }
5407    }
5408  }
5409
5410  assert(0 && "found no explanation for non-trivial member");
5411}
5412
5413/// TranslateIvarVisibility - Translate visibility from a token ID to an
5414///  AST enum value.
5415static ObjCIvarDecl::AccessControl
5416TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5417  switch (ivarVisibility) {
5418  default: assert(0 && "Unknown visitibility kind");
5419  case tok::objc_private: return ObjCIvarDecl::Private;
5420  case tok::objc_public: return ObjCIvarDecl::Public;
5421  case tok::objc_protected: return ObjCIvarDecl::Protected;
5422  case tok::objc_package: return ObjCIvarDecl::Package;
5423  }
5424}
5425
5426/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5427/// in order to create an IvarDecl object for it.
5428Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5429                                SourceLocation DeclStart,
5430                                DeclPtrTy IntfDecl,
5431                                Declarator &D, ExprTy *BitfieldWidth,
5432                                tok::ObjCKeywordKind Visibility) {
5433
5434  IdentifierInfo *II = D.getIdentifier();
5435  Expr *BitWidth = (Expr*)BitfieldWidth;
5436  SourceLocation Loc = DeclStart;
5437  if (II) Loc = D.getIdentifierLoc();
5438
5439  // FIXME: Unnamed fields can be handled in various different ways, for
5440  // example, unnamed unions inject all members into the struct namespace!
5441
5442  TypeSourceInfo *TInfo = 0;
5443  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5444
5445  if (BitWidth) {
5446    // 6.7.2.1p3, 6.7.2.1p4
5447    if (VerifyBitField(Loc, II, T, BitWidth)) {
5448      D.setInvalidType();
5449      DeleteExpr(BitWidth);
5450      BitWidth = 0;
5451    }
5452  } else {
5453    // Not a bitfield.
5454
5455    // validate II.
5456
5457  }
5458
5459  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5460  // than a variably modified type.
5461  if (T->isVariablyModifiedType()) {
5462    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5463    D.setInvalidType();
5464  }
5465
5466  // Get the visibility (access control) for this ivar.
5467  ObjCIvarDecl::AccessControl ac =
5468    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5469                                        : ObjCIvarDecl::None;
5470  // Must set ivar's DeclContext to its enclosing interface.
5471  Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5472  DeclContext *EnclosingContext;
5473  if (ObjCImplementationDecl *IMPDecl =
5474      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5475    // Case of ivar declared in an implementation. Context is that of its class.
5476    ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5477    assert(IDecl && "No class- ActOnIvar");
5478    EnclosingContext = cast_or_null<DeclContext>(IDecl);
5479  } else
5480    EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5481  assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5482
5483  // Construct the decl.
5484  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5485                                             EnclosingContext, Loc, II, T,
5486                                             TInfo, ac, (Expr *)BitfieldWidth);
5487
5488  if (II) {
5489    NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5490                                           ForRedeclaration);
5491    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5492        && !isa<TagDecl>(PrevDecl)) {
5493      Diag(Loc, diag::err_duplicate_member) << II;
5494      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5495      NewID->setInvalidDecl();
5496    }
5497  }
5498
5499  // Process attributes attached to the ivar.
5500  ProcessDeclAttributes(S, NewID, D);
5501
5502  if (D.isInvalidType())
5503    NewID->setInvalidDecl();
5504
5505  if (II) {
5506    // FIXME: When interfaces are DeclContexts, we'll need to add
5507    // these to the interface.
5508    S->AddDecl(DeclPtrTy::make(NewID));
5509    IdResolver.AddDecl(NewID);
5510  }
5511
5512  return DeclPtrTy::make(NewID);
5513}
5514
5515void Sema::ActOnFields(Scope* S,
5516                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5517                       DeclPtrTy *Fields, unsigned NumFields,
5518                       SourceLocation LBrac, SourceLocation RBrac,
5519                       AttributeList *Attr) {
5520  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5521  assert(EnclosingDecl && "missing record or interface decl");
5522
5523  // If the decl this is being inserted into is invalid, then it may be a
5524  // redeclaration or some other bogus case.  Don't try to add fields to it.
5525  if (EnclosingDecl->isInvalidDecl()) {
5526    // FIXME: Deallocate fields?
5527    return;
5528  }
5529
5530
5531  // Verify that all the fields are okay.
5532  unsigned NumNamedMembers = 0;
5533  llvm::SmallVector<FieldDecl*, 32> RecFields;
5534
5535  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5536  for (unsigned i = 0; i != NumFields; ++i) {
5537    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5538
5539    // Get the type for the field.
5540    Type *FDTy = FD->getType().getTypePtr();
5541
5542    if (!FD->isAnonymousStructOrUnion()) {
5543      // Remember all fields written by the user.
5544      RecFields.push_back(FD);
5545    }
5546
5547    // If the field is already invalid for some reason, don't emit more
5548    // diagnostics about it.
5549    if (FD->isInvalidDecl()) {
5550      EnclosingDecl->setInvalidDecl();
5551      continue;
5552    }
5553
5554    // C99 6.7.2.1p2:
5555    //   A structure or union shall not contain a member with
5556    //   incomplete or function type (hence, a structure shall not
5557    //   contain an instance of itself, but may contain a pointer to
5558    //   an instance of itself), except that the last member of a
5559    //   structure with more than one named member may have incomplete
5560    //   array type; such a structure (and any union containing,
5561    //   possibly recursively, a member that is such a structure)
5562    //   shall not be a member of a structure or an element of an
5563    //   array.
5564    if (FDTy->isFunctionType()) {
5565      // Field declared as a function.
5566      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5567        << FD->getDeclName();
5568      FD->setInvalidDecl();
5569      EnclosingDecl->setInvalidDecl();
5570      continue;
5571    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5572               Record && Record->isStruct()) {
5573      // Flexible array member.
5574      if (NumNamedMembers < 1) {
5575        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5576          << FD->getDeclName();
5577        FD->setInvalidDecl();
5578        EnclosingDecl->setInvalidDecl();
5579        continue;
5580      }
5581      // Okay, we have a legal flexible array member at the end of the struct.
5582      if (Record)
5583        Record->setHasFlexibleArrayMember(true);
5584    } else if (!FDTy->isDependentType() &&
5585               RequireCompleteType(FD->getLocation(), FD->getType(),
5586                                   diag::err_field_incomplete)) {
5587      // Incomplete type
5588      FD->setInvalidDecl();
5589      EnclosingDecl->setInvalidDecl();
5590      continue;
5591    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5592      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5593        // If this is a member of a union, then entire union becomes "flexible".
5594        if (Record && Record->isUnion()) {
5595          Record->setHasFlexibleArrayMember(true);
5596        } else {
5597          // If this is a struct/class and this is not the last element, reject
5598          // it.  Note that GCC supports variable sized arrays in the middle of
5599          // structures.
5600          if (i != NumFields-1)
5601            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5602              << FD->getDeclName() << FD->getType();
5603          else {
5604            // We support flexible arrays at the end of structs in
5605            // other structs as an extension.
5606            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5607              << FD->getDeclName();
5608            if (Record)
5609              Record->setHasFlexibleArrayMember(true);
5610          }
5611        }
5612      }
5613      if (Record && FDTTy->getDecl()->hasObjectMember())
5614        Record->setHasObjectMember(true);
5615    } else if (FDTy->isObjCInterfaceType()) {
5616      /// A field cannot be an Objective-c object
5617      Diag(FD->getLocation(), diag::err_statically_allocated_object);
5618      FD->setInvalidDecl();
5619      EnclosingDecl->setInvalidDecl();
5620      continue;
5621    } else if (getLangOptions().ObjC1 &&
5622               getLangOptions().getGCMode() != LangOptions::NonGC &&
5623               Record &&
5624               (FD->getType()->isObjCObjectPointerType() ||
5625                FD->getType().isObjCGCStrong()))
5626      Record->setHasObjectMember(true);
5627    // Keep track of the number of named members.
5628    if (FD->getIdentifier())
5629      ++NumNamedMembers;
5630  }
5631
5632  // Okay, we successfully defined 'Record'.
5633  if (Record) {
5634    Record->completeDefinition(Context);
5635  } else {
5636    ObjCIvarDecl **ClsFields =
5637      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5638    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5639      ID->setIVarList(ClsFields, RecFields.size(), Context);
5640      ID->setLocEnd(RBrac);
5641      // Add ivar's to class's DeclContext.
5642      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5643        ClsFields[i]->setLexicalDeclContext(ID);
5644        ID->addDecl(ClsFields[i]);
5645      }
5646      // Must enforce the rule that ivars in the base classes may not be
5647      // duplicates.
5648      if (ID->getSuperClass()) {
5649        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5650             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5651          ObjCIvarDecl* Ivar = (*IVI);
5652
5653          if (IdentifierInfo *II = Ivar->getIdentifier()) {
5654            ObjCIvarDecl* prevIvar =
5655              ID->getSuperClass()->lookupInstanceVariable(II);
5656            if (prevIvar) {
5657              Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5658              Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5659            }
5660          }
5661        }
5662      }
5663    } else if (ObjCImplementationDecl *IMPDecl =
5664                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5665      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5666      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5667        // Ivar declared in @implementation never belongs to the implementation.
5668        // Only it is in implementation's lexical context.
5669        ClsFields[I]->setLexicalDeclContext(IMPDecl);
5670      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5671    }
5672  }
5673
5674  if (Attr)
5675    ProcessDeclAttributeList(S, Record, Attr);
5676}
5677
5678EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5679                                          EnumConstantDecl *LastEnumConst,
5680                                          SourceLocation IdLoc,
5681                                          IdentifierInfo *Id,
5682                                          ExprArg val) {
5683  Expr *Val = (Expr *)val.get();
5684
5685  llvm::APSInt EnumVal(32);
5686  QualType EltTy;
5687  if (Val) {
5688    if (Enum->isDependentType())
5689      EltTy = Context.DependentTy;
5690    else {
5691      // Make sure to promote the operand type to int.
5692      UsualUnaryConversions(Val);
5693      if (Val != val.get()) {
5694        val.release();
5695        val = Val;
5696      }
5697
5698      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5699      SourceLocation ExpLoc;
5700      if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
5701        Val = 0;
5702      } else {
5703        EltTy = Val->getType();
5704      }
5705    }
5706  }
5707
5708  if (!Val) {
5709    if (Enum->isDependentType())
5710      EltTy = Context.DependentTy;
5711    else if (LastEnumConst) {
5712      // Assign the last value + 1.
5713      EnumVal = LastEnumConst->getInitVal();
5714      ++EnumVal;
5715
5716      // Check for overflow on increment.
5717      if (EnumVal < LastEnumConst->getInitVal())
5718        Diag(IdLoc, diag::warn_enum_value_overflow);
5719
5720      EltTy = LastEnumConst->getType();
5721    } else {
5722      // First value, set to zero.
5723      EltTy = Context.IntTy;
5724      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5725      EnumVal.setIsSigned(true);
5726    }
5727  }
5728
5729  assert(!EltTy.isNull() && "Enum constant with NULL type");
5730
5731  val.release();
5732  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5733                                  Val, EnumVal);
5734}
5735
5736
5737Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5738                                        DeclPtrTy lastEnumConst,
5739                                        SourceLocation IdLoc,
5740                                        IdentifierInfo *Id,
5741                                        SourceLocation EqualLoc, ExprTy *val) {
5742  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5743  EnumConstantDecl *LastEnumConst =
5744    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5745  Expr *Val = static_cast<Expr*>(val);
5746
5747  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5748  // we find one that is.
5749  S = getNonFieldDeclScope(S);
5750
5751  // Verify that there isn't already something declared with this name in this
5752  // scope.
5753  NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
5754  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5755    // Maybe we will complain about the shadowed template parameter.
5756    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5757    // Just pretend that we didn't see the previous declaration.
5758    PrevDecl = 0;
5759  }
5760
5761  if (PrevDecl) {
5762    // When in C++, we may get a TagDecl with the same name; in this case the
5763    // enum constant will 'hide' the tag.
5764    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5765           "Received TagDecl when not in C++!");
5766    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5767      if (isa<EnumConstantDecl>(PrevDecl))
5768        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5769      else
5770        Diag(IdLoc, diag::err_redefinition) << Id;
5771      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5772      if (Val) Val->Destroy(Context);
5773      return DeclPtrTy();
5774    }
5775  }
5776
5777  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5778                                            IdLoc, Id, Owned(Val));
5779
5780  // Register this decl in the current scope stack.
5781  if (New)
5782    PushOnScopeChains(New, S);
5783
5784  return DeclPtrTy::make(New);
5785}
5786
5787void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5788                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5789                         DeclPtrTy *Elements, unsigned NumElements,
5790                         Scope *S, AttributeList *Attr) {
5791  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5792  QualType EnumType = Context.getTypeDeclType(Enum);
5793
5794  if (Attr)
5795    ProcessDeclAttributeList(S, Enum, Attr);
5796
5797  if (Enum->isDependentType()) {
5798    for (unsigned i = 0; i != NumElements; ++i) {
5799      EnumConstantDecl *ECD =
5800        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5801      if (!ECD) continue;
5802
5803      ECD->setType(EnumType);
5804    }
5805
5806    Enum->completeDefinition(Context, Context.DependentTy, Context.DependentTy);
5807    return;
5808  }
5809
5810  // TODO: If the result value doesn't fit in an int, it must be a long or long
5811  // long value.  ISO C does not support this, but GCC does as an extension,
5812  // emit a warning.
5813  unsigned IntWidth = Context.Target.getIntWidth();
5814  unsigned CharWidth = Context.Target.getCharWidth();
5815  unsigned ShortWidth = Context.Target.getShortWidth();
5816
5817  // Verify that all the values are okay, compute the size of the values, and
5818  // reverse the list.
5819  unsigned NumNegativeBits = 0;
5820  unsigned NumPositiveBits = 0;
5821
5822  // Keep track of whether all elements have type int.
5823  bool AllElementsInt = true;
5824
5825  for (unsigned i = 0; i != NumElements; ++i) {
5826    EnumConstantDecl *ECD =
5827      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5828    if (!ECD) continue;  // Already issued a diagnostic.
5829
5830    // If the enum value doesn't fit in an int, emit an extension warning.
5831    const llvm::APSInt &InitVal = ECD->getInitVal();
5832    assert(InitVal.getBitWidth() >= IntWidth &&
5833           "Should have promoted value to int");
5834    if (!getLangOptions().CPlusPlus && InitVal.getBitWidth() > IntWidth) {
5835      llvm::APSInt V(InitVal);
5836      V.trunc(IntWidth);
5837      V.extend(InitVal.getBitWidth());
5838      if (V != InitVal)
5839        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5840          << InitVal.toString(10);
5841    }
5842
5843    // Keep track of the size of positive and negative values.
5844    if (InitVal.isUnsigned() || InitVal.isNonNegative())
5845      NumPositiveBits = std::max(NumPositiveBits,
5846                                 (unsigned)InitVal.getActiveBits());
5847    else
5848      NumNegativeBits = std::max(NumNegativeBits,
5849                                 (unsigned)InitVal.getMinSignedBits());
5850
5851    // Keep track of whether every enum element has type int (very commmon).
5852    if (AllElementsInt)
5853      AllElementsInt = ECD->getType() == Context.IntTy;
5854  }
5855
5856  // Figure out the type that should be used for this enum.
5857  // FIXME: Support -fshort-enums.
5858  QualType BestType;
5859  unsigned BestWidth;
5860
5861  // C++0x N3000 [conv.prom]p3:
5862  //   An rvalue of an unscoped enumeration type whose underlying
5863  //   type is not fixed can be converted to an rvalue of the first
5864  //   of the following types that can represent all the values of
5865  //   the enumeration: int, unsigned int, long int, unsigned long
5866  //   int, long long int, or unsigned long long int.
5867  // C99 6.4.4.3p2:
5868  //   An identifier declared as an enumeration constant has type int.
5869  // The C99 rule is modified by a gcc extension
5870  QualType BestPromotionType;
5871
5872  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5873
5874  if (NumNegativeBits) {
5875    // If there is a negative value, figure out the smallest integer type (of
5876    // int/long/longlong) that fits.
5877    // If it's packed, check also if it fits a char or a short.
5878    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5879      BestType = Context.SignedCharTy;
5880      BestWidth = CharWidth;
5881    } else if (Packed && NumNegativeBits <= ShortWidth &&
5882               NumPositiveBits < ShortWidth) {
5883      BestType = Context.ShortTy;
5884      BestWidth = ShortWidth;
5885    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5886      BestType = Context.IntTy;
5887      BestWidth = IntWidth;
5888    } else {
5889      BestWidth = Context.Target.getLongWidth();
5890
5891      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5892        BestType = Context.LongTy;
5893      } else {
5894        BestWidth = Context.Target.getLongLongWidth();
5895
5896        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5897          Diag(Enum->getLocation(), diag::warn_enum_too_large);
5898        BestType = Context.LongLongTy;
5899      }
5900    }
5901    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
5902  } else {
5903    // If there is no negative value, figure out which of uint, ulong, ulonglong
5904    // fits.
5905    // If it's packed, check also if it fits a char or a short.
5906    if (Packed && NumPositiveBits <= CharWidth) {
5907      BestType = Context.UnsignedCharTy;
5908      BestPromotionType = Context.IntTy;
5909      BestWidth = CharWidth;
5910    } else if (Packed && NumPositiveBits <= ShortWidth) {
5911      BestType = Context.UnsignedShortTy;
5912      BestPromotionType = Context.IntTy;
5913      BestWidth = ShortWidth;
5914    } else if (NumPositiveBits <= IntWidth) {
5915      BestType = Context.UnsignedIntTy;
5916      BestWidth = IntWidth;
5917      BestPromotionType = (NumPositiveBits == BestWidth
5918                           ? Context.UnsignedIntTy : Context.IntTy);
5919    } else if (NumPositiveBits <=
5920               (BestWidth = Context.Target.getLongWidth())) {
5921      BestType = Context.UnsignedLongTy;
5922      BestPromotionType = (NumPositiveBits == BestWidth
5923                           ? Context.UnsignedLongTy : Context.LongTy);
5924    } else {
5925      BestWidth = Context.Target.getLongLongWidth();
5926      assert(NumPositiveBits <= BestWidth &&
5927             "How could an initializer get larger than ULL?");
5928      BestType = Context.UnsignedLongLongTy;
5929      BestPromotionType = (NumPositiveBits == BestWidth
5930                           ? Context.UnsignedLongLongTy : Context.LongLongTy);
5931    }
5932  }
5933
5934  // If we're in C and the promotion type is larger than an int, just
5935  // use the underlying type, which is generally the unsigned integer
5936  // type of the same rank as the promotion type.  This is how the gcc
5937  // extension works.
5938  if (!getLangOptions().CPlusPlus && BestPromotionType != Context.IntTy)
5939    BestPromotionType = BestType;
5940
5941  // Loop over all of the enumerator constants, changing their types to match
5942  // the type of the enum if needed.
5943  for (unsigned i = 0; i != NumElements; ++i) {
5944    EnumConstantDecl *ECD =
5945      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5946    if (!ECD) continue;  // Already issued a diagnostic.
5947
5948    // Standard C says the enumerators have int type, but we allow, as an
5949    // extension, the enumerators to be larger than int size.  If each
5950    // enumerator value fits in an int, type it as an int, otherwise type it the
5951    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
5952    // that X has type 'int', not 'unsigned'.
5953    if (!getLangOptions().CPlusPlus && ECD->getType() == Context.IntTy)
5954      continue;
5955
5956    // Determine whether the value fits into an int.
5957    llvm::APSInt InitVal = ECD->getInitVal();
5958    bool FitsInInt;
5959    if (InitVal.isUnsigned() || !InitVal.isNegative())
5960      FitsInInt = InitVal.getActiveBits() < IntWidth;
5961    else
5962      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
5963
5964    // If it fits into an integer type, force it.  Otherwise force it to match
5965    // the enum decl type.
5966    QualType NewTy;
5967    unsigned NewWidth;
5968    bool NewSign;
5969    if (FitsInInt && !getLangOptions().CPlusPlus) {
5970      NewTy = Context.IntTy;
5971      NewWidth = IntWidth;
5972      NewSign = true;
5973    } else if (ECD->getType() == BestType) {
5974      // Already the right type!
5975      if (getLangOptions().CPlusPlus)
5976        // C++ [dcl.enum]p4: Following the closing brace of an
5977        // enum-specifier, each enumerator has the type of its
5978        // enumeration.
5979        ECD->setType(EnumType);
5980      continue;
5981    } else {
5982      NewTy = BestType;
5983      NewWidth = BestWidth;
5984      NewSign = BestType->isSignedIntegerType();
5985    }
5986
5987    // Adjust the APSInt value.
5988    InitVal.extOrTrunc(NewWidth);
5989    InitVal.setIsSigned(NewSign);
5990    ECD->setInitVal(InitVal);
5991
5992    // Adjust the Expr initializer and type.
5993    if (ECD->getInitExpr())
5994      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
5995                                                      CastExpr::CK_IntegralCast,
5996                                                      ECD->getInitExpr(),
5997                                                      /*isLvalue=*/false));
5998    if (getLangOptions().CPlusPlus)
5999      // C++ [dcl.enum]p4: Following the closing brace of an
6000      // enum-specifier, each enumerator has the type of its
6001      // enumeration.
6002      ECD->setType(EnumType);
6003    else
6004      ECD->setType(NewTy);
6005  }
6006
6007  Enum->completeDefinition(Context, BestType, BestPromotionType);
6008}
6009
6010Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6011                                            ExprArg expr) {
6012  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6013
6014  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6015                                                   Loc, AsmString);
6016  CurContext->addDecl(New);
6017  return DeclPtrTy::make(New);
6018}
6019
6020void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6021                             SourceLocation PragmaLoc,
6022                             SourceLocation NameLoc) {
6023  Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
6024
6025  if (PrevDecl) {
6026    PrevDecl->addAttr(::new (Context) WeakAttr());
6027  } else {
6028    (void)WeakUndeclaredIdentifiers.insert(
6029      std::pair<IdentifierInfo*,WeakInfo>
6030        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6031  }
6032}
6033
6034void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6035                                IdentifierInfo* AliasName,
6036                                SourceLocation PragmaLoc,
6037                                SourceLocation NameLoc,
6038                                SourceLocation AliasNameLoc) {
6039  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
6040  WeakInfo W = WeakInfo(Name, NameLoc);
6041
6042  if (PrevDecl) {
6043    if (!PrevDecl->hasAttr<AliasAttr>())
6044      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6045        DeclApplyPragmaWeak(TUScope, ND, W);
6046  } else {
6047    (void)WeakUndeclaredIdentifiers.insert(
6048      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6049  }
6050}
6051