SemaDecl.cpp revision 9a9cc8103401942527b43a51504fe7c985052d21
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 "clang/AST/APValue.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/STLExtras.h"
29#include <algorithm>
30#include <functional>
31using namespace clang;
32
33/// getDeclName - Return a pretty name for the specified decl if possible, or
34/// an empty string if not.  This is used for pretty crash reporting.
35std::string Sema::getDeclName(DeclPtrTy d) {
36  Decl *D = d.getAs<Decl>();
37  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
38    return DN->getQualifiedNameAsString();
39  return "";
40}
41
42Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
43  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
44}
45
46/// \brief If the identifier refers to a type name within this scope,
47/// return the declaration of that type.
48///
49/// This routine performs ordinary name lookup of the identifier II
50/// within the given scope, with optional C++ scope specifier SS, to
51/// determine whether the name refers to a type. If so, returns an
52/// opaque pointer (actually a QualType) corresponding to that
53/// type. Otherwise, returns NULL.
54///
55/// If name lookup results in an ambiguity, this routine will complain
56/// and then return NULL.
57Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
58                                Scope *S, const CXXScopeSpec *SS) {
59  // C++ [temp.res]p3:
60  //   A qualified-id that refers to a type and in which the
61  //   nested-name-specifier depends on a template-parameter (14.6.2)
62  //   shall be prefixed by the keyword typename to indicate that the
63  //   qualified-id denotes a type, forming an
64  //   elaborated-type-specifier (7.1.5.3).
65  //
66  // We therefore do not perform any name lookup up SS is a dependent
67  // scope name. FIXME: we will need to perform a special kind of
68  // lookup if the scope specifier names a member of the current
69  // instantiation.
70  if (SS && isDependentScopeSpecifier(*SS))
71    return 0;
72
73  NamedDecl *IIDecl = 0;
74  LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
75                                         false, false);
76  switch (Result.getKind()) {
77  case LookupResult::NotFound:
78  case LookupResult::FoundOverloaded:
79    return 0;
80
81  case LookupResult::AmbiguousBaseSubobjectTypes:
82  case LookupResult::AmbiguousBaseSubobjects:
83  case LookupResult::AmbiguousReference: {
84    // Look to see if we have a type anywhere in the list of results.
85    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
86         Res != ResEnd; ++Res) {
87      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
88        if (!IIDecl ||
89            (*Res)->getLocation().getRawEncoding() <
90              IIDecl->getLocation().getRawEncoding())
91          IIDecl = *Res;
92      }
93    }
94
95    if (!IIDecl) {
96      // None of the entities we found is a type, so there is no way
97      // to even assume that the result is a type. In this case, don't
98      // complain about the ambiguity. The parser will either try to
99      // perform this lookup again (e.g., as an object name), which
100      // will produce the ambiguity, or will complain that it expected
101      // a type name.
102      Result.Destroy();
103      return 0;
104    }
105
106    // We found a type within the ambiguous lookup; diagnose the
107    // ambiguity and then return that type. This might be the right
108    // answer, or it might not be, but it suppresses any attempt to
109    // perform the name lookup again.
110    DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
111    break;
112  }
113
114  case LookupResult::Found:
115    IIDecl = Result.getAsDecl();
116    break;
117  }
118
119  if (IIDecl) {
120    QualType T;
121
122    if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
123      // Check whether we can use this type
124      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
125
126      T = Context.getTypeDeclType(TD);
127    } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
128      // Check whether we can use this interface.
129      (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
130
131      T = Context.getObjCInterfaceType(IDecl);
132    } else
133      return 0;
134
135    if (SS)
136      T = getQualifiedNameType(*SS, T);
137
138    return T.getAsOpaquePtr();
139  }
140
141  return 0;
142}
143
144/// isTagName() - This method is called *for error recovery purposes only*
145/// to determine if the specified name is a valid tag name ("struct foo").  If
146/// so, this returns the TST for the tag corresponding to it (TST_enum,
147/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
148/// where the user forgot to specify the tag.
149DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
150  // Do a tag name lookup in this scope.
151  LookupResult R = LookupName(S, &II, LookupTagName, false, false);
152  if (R.getKind() == LookupResult::Found)
153    if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
154      switch (TD->getTagKind()) {
155      case TagDecl::TK_struct: return DeclSpec::TST_struct;
156      case TagDecl::TK_union:  return DeclSpec::TST_union;
157      case TagDecl::TK_class:  return DeclSpec::TST_class;
158      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
159      }
160    }
161
162  return DeclSpec::TST_unspecified;
163}
164
165
166
167DeclContext *Sema::getContainingDC(DeclContext *DC) {
168  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
169    // A C++ out-of-line method will return to the file declaration context.
170    if (MD->isOutOfLineDefinition())
171      return MD->getLexicalDeclContext();
172
173    // A C++ inline method is parsed *after* the topmost class it was declared
174    // in is fully parsed (it's "complete").
175    // The parsing of a C++ inline method happens at the declaration context of
176    // the topmost (non-nested) class it is lexically declared in.
177    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
178    DC = MD->getParent();
179    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
180      DC = RD;
181
182    // Return the declaration context of the topmost class the inline method is
183    // declared in.
184    return DC;
185  }
186
187  if (isa<ObjCMethodDecl>(DC))
188    return Context.getTranslationUnitDecl();
189
190  return DC->getLexicalParent();
191}
192
193void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
194  assert(getContainingDC(DC) == CurContext &&
195      "The next DeclContext should be lexically contained in the current one.");
196  CurContext = DC;
197  S->setEntity(DC);
198}
199
200void Sema::PopDeclContext() {
201  assert(CurContext && "DeclContext imbalance!");
202
203  CurContext = getContainingDC(CurContext);
204}
205
206/// \brief Determine whether we allow overloading of the function
207/// PrevDecl with another declaration.
208///
209/// This routine determines whether overloading is possible, not
210/// whether some new function is actually an overload. It will return
211/// true in C++ (where we can always provide overloads) or, as an
212/// extension, in C when the previous function is already an
213/// overloaded function declaration or has the "overloadable"
214/// attribute.
215static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
216  if (Context.getLangOptions().CPlusPlus)
217    return true;
218
219  if (isa<OverloadedFunctionDecl>(PrevDecl))
220    return true;
221
222  return PrevDecl->getAttr<OverloadableAttr>() != 0;
223}
224
225/// Add this decl to the scope shadowed decl chains.
226void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
227  // Move up the scope chain until we find the nearest enclosing
228  // non-transparent context. The declaration will be introduced into this
229  // scope.
230  while (S->getEntity() &&
231         ((DeclContext *)S->getEntity())->isTransparentContext())
232    S = S->getParent();
233
234  S->AddDecl(DeclPtrTy::make(D));
235
236  // Add scoped declarations into their context, so that they can be
237  // found later. Declarations without a context won't be inserted
238  // into any context.
239  CurContext->addDecl(Context, D);
240
241  // C++ [basic.scope]p4:
242  //   -- exactly one declaration shall declare a class name or
243  //   enumeration name that is not a typedef name and the other
244  //   declarations shall all refer to the same object or
245  //   enumerator, or all refer to functions and function templates;
246  //   in this case the class name or enumeration name is hidden.
247  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
248    // We are pushing the name of a tag (enum or class).
249    if (CurContext->getLookupContext()
250          == TD->getDeclContext()->getLookupContext()) {
251      // We're pushing the tag into the current context, which might
252      // require some reshuffling in the identifier resolver.
253      IdentifierResolver::iterator
254        I = IdResolver.begin(TD->getDeclName()),
255        IEnd = IdResolver.end();
256      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
257        NamedDecl *PrevDecl = *I;
258        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
259             PrevDecl = *I, ++I) {
260          if (TD->declarationReplaces(*I)) {
261            // This is a redeclaration. Remove it from the chain and
262            // break out, so that we'll add in the shadowed
263            // declaration.
264            S->RemoveDecl(DeclPtrTy::make(*I));
265            if (PrevDecl == *I) {
266              IdResolver.RemoveDecl(*I);
267              IdResolver.AddDecl(TD);
268              return;
269            } else {
270              IdResolver.RemoveDecl(*I);
271              break;
272            }
273          }
274        }
275
276        // There is already a declaration with the same name in the same
277        // scope, which is not a tag declaration. It must be found
278        // before we find the new declaration, so insert the new
279        // declaration at the end of the chain.
280        IdResolver.AddShadowedDecl(TD, PrevDecl);
281
282        return;
283      }
284    }
285  } else if (isa<FunctionDecl>(D) &&
286             AllowOverloadingOfFunction(D, Context)) {
287    // We are pushing the name of a function, which might be an
288    // overloaded name.
289    FunctionDecl *FD = cast<FunctionDecl>(D);
290    IdentifierResolver::iterator Redecl
291      = std::find_if(IdResolver.begin(FD->getDeclName()),
292                     IdResolver.end(),
293                     std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
294                                  FD));
295    if (Redecl != IdResolver.end() &&
296        S->isDeclScope(DeclPtrTy::make(*Redecl))) {
297      // There is already a declaration of a function on our
298      // IdResolver chain. Replace it with this declaration.
299      S->RemoveDecl(DeclPtrTy::make(*Redecl));
300      IdResolver.RemoveDecl(*Redecl);
301    }
302  }
303
304  IdResolver.AddDecl(D);
305}
306
307void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
308  if (S->decl_empty()) return;
309  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
310	 "Scope shouldn't contain decls!");
311
312  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
313       I != E; ++I) {
314    Decl *TmpD = (*I).getAs<Decl>();
315    assert(TmpD && "This decl didn't get pushed??");
316
317    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
318    NamedDecl *D = cast<NamedDecl>(TmpD);
319
320    if (!D->getDeclName()) continue;
321
322    // Remove this name from our lexical scope.
323    IdResolver.RemoveDecl(D);
324  }
325}
326
327/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
328/// return 0 if one not found.
329ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
330  // The third "scope" argument is 0 since we aren't enabling lazy built-in
331  // creation from this context.
332  NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
333
334  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
335}
336
337/// getNonFieldDeclScope - Retrieves the innermost scope, starting
338/// from S, where a non-field would be declared. This routine copes
339/// with the difference between C and C++ scoping rules in structs and
340/// unions. For example, the following code is well-formed in C but
341/// ill-formed in C++:
342/// @code
343/// struct S6 {
344///   enum { BAR } e;
345/// };
346///
347/// void test_S6() {
348///   struct S6 a;
349///   a.e = BAR;
350/// }
351/// @endcode
352/// For the declaration of BAR, this routine will return a different
353/// scope. The scope S will be the scope of the unnamed enumeration
354/// within S6. In C++, this routine will return the scope associated
355/// with S6, because the enumeration's scope is a transparent
356/// context but structures can contain non-field names. In C, this
357/// routine will return the translation unit scope, since the
358/// enumeration's scope is a transparent context and structures cannot
359/// contain non-field names.
360Scope *Sema::getNonFieldDeclScope(Scope *S) {
361  while (((S->getFlags() & Scope::DeclScope) == 0) ||
362         (S->getEntity() &&
363          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
364         (S->isClassScope() && !getLangOptions().CPlusPlus))
365    S = S->getParent();
366  return S;
367}
368
369void Sema::InitBuiltinVaListType() {
370  if (!Context.getBuiltinVaListType().isNull())
371    return;
372
373  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
374  NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
375  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
376  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
377}
378
379/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
380/// file scope.  lazily create a decl for it. ForRedeclaration is true
381/// if we're creating this built-in in anticipation of redeclaring the
382/// built-in.
383NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
384                                     Scope *S, bool ForRedeclaration,
385                                     SourceLocation Loc) {
386  Builtin::ID BID = (Builtin::ID)bid;
387
388  if (Context.BuiltinInfo.hasVAListUse(BID))
389    InitBuiltinVaListType();
390
391  Builtin::Context::GetBuiltinTypeError Error;
392  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
393  switch (Error) {
394  case Builtin::Context::GE_None:
395    // Okay
396    break;
397
398  case Builtin::Context::GE_Missing_FILE:
399    if (ForRedeclaration)
400      Diag(Loc, diag::err_implicit_decl_requires_stdio)
401        << Context.BuiltinInfo.GetName(BID);
402    return 0;
403  }
404
405  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
406    Diag(Loc, diag::ext_implicit_lib_function_decl)
407      << Context.BuiltinInfo.GetName(BID)
408      << R;
409    if (Context.BuiltinInfo.getHeaderName(BID) &&
410        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
411          != Diagnostic::Ignored)
412      Diag(Loc, diag::note_please_include_header)
413        << Context.BuiltinInfo.getHeaderName(BID)
414        << Context.BuiltinInfo.GetName(BID);
415  }
416
417  FunctionDecl *New = FunctionDecl::Create(Context,
418                                           Context.getTranslationUnitDecl(),
419                                           Loc, II, R,
420                                           FunctionDecl::Extern, false,
421                                           /*hasPrototype=*/true);
422  New->setImplicit();
423
424  // Create Decl objects for each parameter, adding them to the
425  // FunctionDecl.
426  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
427    llvm::SmallVector<ParmVarDecl*, 16> Params;
428    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
429      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
430                                           FT->getArgType(i), VarDecl::None, 0));
431    New->setParams(Context, &Params[0], Params.size());
432  }
433
434  AddKnownFunctionAttributes(New);
435
436  // TUScope is the translation-unit scope to insert this function into.
437  // FIXME: This is hideous. We need to teach PushOnScopeChains to
438  // relate Scopes to DeclContexts, and probably eliminate CurContext
439  // entirely, but we're not there yet.
440  DeclContext *SavedContext = CurContext;
441  CurContext = Context.getTranslationUnitDecl();
442  PushOnScopeChains(New, TUScope);
443  CurContext = SavedContext;
444  return New;
445}
446
447/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
448/// everything from the standard library is defined.
449NamespaceDecl *Sema::GetStdNamespace() {
450  if (!StdNamespace) {
451    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
452    DeclContext *Global = Context.getTranslationUnitDecl();
453    Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
454    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
455  }
456  return StdNamespace;
457}
458
459/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
460/// same name and scope as a previous declaration 'Old'.  Figure out
461/// how to resolve this situation, merging decls or emitting
462/// diagnostics as appropriate. Returns true if there was an error,
463/// false otherwise.
464///
465bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
466  bool objc_types = false;
467  // Allow multiple definitions for ObjC built-in typedefs.
468  // FIXME: Verify the underlying types are equivalent!
469  if (getLangOptions().ObjC1) {
470    const IdentifierInfo *TypeID = New->getIdentifier();
471    switch (TypeID->getLength()) {
472    default: break;
473    case 2:
474      if (!TypeID->isStr("id"))
475        break;
476      Context.setObjCIdType(New);
477      objc_types = true;
478      break;
479    case 5:
480      if (!TypeID->isStr("Class"))
481        break;
482      Context.setObjCClassType(New);
483      objc_types = true;
484      return false;
485    case 3:
486      if (!TypeID->isStr("SEL"))
487        break;
488      Context.setObjCSelType(New);
489      objc_types = true;
490      return false;
491    case 8:
492      if (!TypeID->isStr("Protocol"))
493        break;
494      Context.setObjCProtoType(New->getUnderlyingType());
495      objc_types = true;
496      return false;
497    }
498    // Fall through - the typedef name was not a builtin type.
499  }
500  // Verify the old decl was also a type.
501  TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
502  if (!Old) {
503    Diag(New->getLocation(), diag::err_redefinition_different_kind)
504      << New->getDeclName();
505    if (!objc_types)
506      Diag(OldD->getLocation(), diag::note_previous_definition);
507    return true;
508  }
509
510  // Determine the "old" type we'll use for checking and diagnostics.
511  QualType OldType;
512  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
513    OldType = OldTypedef->getUnderlyingType();
514  else
515    OldType = Context.getTypeDeclType(Old);
516
517  // If the typedef types are not identical, reject them in all languages and
518  // with any extensions enabled.
519
520  if (OldType != New->getUnderlyingType() &&
521      Context.getCanonicalType(OldType) !=
522      Context.getCanonicalType(New->getUnderlyingType())) {
523    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
524      << New->getUnderlyingType() << OldType;
525    if (!objc_types)
526      Diag(Old->getLocation(), diag::note_previous_definition);
527    return true;
528  }
529  if (objc_types) return false;
530  if (getLangOptions().Microsoft) return false;
531
532  // C++ [dcl.typedef]p2:
533  //   In a given non-class scope, a typedef specifier can be used to
534  //   redefine the name of any type declared in that scope to refer
535  //   to the type to which it already refers.
536  if (getLangOptions().CPlusPlus) {
537    if (!isa<CXXRecordDecl>(CurContext))
538      return false;
539    Diag(New->getLocation(), diag::err_redefinition)
540      << New->getDeclName();
541    Diag(Old->getLocation(), diag::note_previous_definition);
542    return true;
543  }
544
545  // If we have a redefinition of a typedef in C, emit a warning.  This warning
546  // is normally mapped to an error, but can be controlled with
547  // -Wtypedef-redefinition.
548  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
549    << New->getDeclName();
550  Diag(Old->getLocation(), diag::note_previous_definition);
551  return false;
552}
553
554/// DeclhasAttr - returns true if decl Declaration already has the target
555/// attribute.
556static bool DeclHasAttr(const Decl *decl, const Attr *target) {
557  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
558    if (attr->getKind() == target->getKind())
559      return true;
560
561  return false;
562}
563
564/// MergeAttributes - append attributes from the Old decl to the New one.
565static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
566  Attr *attr = const_cast<Attr*>(Old->getAttrs());
567
568  while (attr) {
569    Attr *tmp = attr;
570    attr = attr->getNext();
571
572    if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
573      tmp->setInherited(true);
574      New->addAttr(tmp);
575    } else {
576      tmp->setNext(0);
577      tmp->Destroy(C);
578    }
579  }
580
581  Old->invalidateAttrs();
582}
583
584/// Used in MergeFunctionDecl to keep track of function parameters in
585/// C.
586struct GNUCompatibleParamWarning {
587  ParmVarDecl *OldParm;
588  ParmVarDecl *NewParm;
589  QualType PromotedType;
590};
591
592/// MergeFunctionDecl - We just parsed a function 'New' from
593/// declarator D which has the same name and scope as a previous
594/// declaration 'Old'.  Figure out how to resolve this situation,
595/// merging decls or emitting diagnostics as appropriate.
596///
597/// In C++, New and Old must be declarations that are not
598/// overloaded. Use IsOverload to determine whether New and Old are
599/// overloaded, and to select the Old declaration that New should be
600/// merged with.
601///
602/// Returns true if there was an error, false otherwise.
603bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
604  assert(!isa<OverloadedFunctionDecl>(OldD) &&
605         "Cannot merge with an overloaded function declaration");
606
607  // Verify the old decl was also a function.
608  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
609  if (!Old) {
610    Diag(New->getLocation(), diag::err_redefinition_different_kind)
611      << New->getDeclName();
612    Diag(OldD->getLocation(), diag::note_previous_definition);
613    return true;
614  }
615
616  // Determine whether the previous declaration was a definition,
617  // implicit declaration, or a declaration.
618  diag::kind PrevDiag;
619  if (Old->isThisDeclarationADefinition())
620    PrevDiag = diag::note_previous_definition;
621  else if (Old->isImplicit())
622    PrevDiag = diag::note_previous_implicit_declaration;
623  else
624    PrevDiag = diag::note_previous_declaration;
625
626  QualType OldQType = Context.getCanonicalType(Old->getType());
627  QualType NewQType = Context.getCanonicalType(New->getType());
628
629  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
630      New->getStorageClass() == FunctionDecl::Static &&
631      Old->getStorageClass() != FunctionDecl::Static) {
632    Diag(New->getLocation(), diag::err_static_non_static)
633      << New;
634    Diag(Old->getLocation(), PrevDiag);
635    return true;
636  }
637
638  if (getLangOptions().CPlusPlus) {
639    // (C++98 13.1p2):
640    //   Certain function declarations cannot be overloaded:
641    //     -- Function declarations that differ only in the return type
642    //        cannot be overloaded.
643    QualType OldReturnType
644      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
645    QualType NewReturnType
646      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
647    if (OldReturnType != NewReturnType) {
648      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
649      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
650      return true;
651    }
652
653    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
654    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
655    if (OldMethod && NewMethod &&
656        OldMethod->getLexicalDeclContext() ==
657          NewMethod->getLexicalDeclContext()) {
658      //    -- Member function declarations with the same name and the
659      //       same parameter types cannot be overloaded if any of them
660      //       is a static member function declaration.
661      if (OldMethod->isStatic() || NewMethod->isStatic()) {
662        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
663        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
664        return true;
665      }
666
667      // C++ [class.mem]p1:
668      //   [...] A member shall not be declared twice in the
669      //   member-specification, except that a nested class or member
670      //   class template can be declared and then later defined.
671      unsigned NewDiag;
672      if (isa<CXXConstructorDecl>(OldMethod))
673        NewDiag = diag::err_constructor_redeclared;
674      else if (isa<CXXDestructorDecl>(NewMethod))
675        NewDiag = diag::err_destructor_redeclared;
676      else if (isa<CXXConversionDecl>(NewMethod))
677        NewDiag = diag::err_conv_function_redeclared;
678      else
679        NewDiag = diag::err_member_redeclared;
680
681      Diag(New->getLocation(), NewDiag);
682      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
683    }
684
685    // (C++98 8.3.5p3):
686    //   All declarations for a function shall agree exactly in both the
687    //   return type and the parameter-type-list.
688    if (OldQType == NewQType)
689      return MergeCompatibleFunctionDecls(New, Old);
690
691    // Fall through for conflicting redeclarations and redefinitions.
692  }
693
694  // C: Function types need to be compatible, not identical. This handles
695  // duplicate function decls like "void f(int); void f(enum X);" properly.
696  if (!getLangOptions().CPlusPlus &&
697      Context.typesAreCompatible(OldQType, NewQType)) {
698    const FunctionType *OldFuncType = OldQType->getAsFunctionType();
699    const FunctionType *NewFuncType = NewQType->getAsFunctionType();
700    const FunctionProtoType *OldProto = 0;
701    if (isa<FunctionNoProtoType>(NewFuncType) &&
702        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
703      // The old declaration provided a function prototype, but the
704      // new declaration does not. Merge in the prototype.
705      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
706                                                 OldProto->arg_type_end());
707      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
708                                         &ParamTypes[0], ParamTypes.size(),
709                                         OldProto->isVariadic(),
710                                         OldProto->getTypeQuals());
711      New->setType(NewQType);
712      New->setInheritedPrototype();
713
714      // Synthesize a parameter for each argument type.
715      llvm::SmallVector<ParmVarDecl*, 16> Params;
716      for (FunctionProtoType::arg_type_iterator
717             ParamType = OldProto->arg_type_begin(),
718             ParamEnd = OldProto->arg_type_end();
719           ParamType != ParamEnd; ++ParamType) {
720        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
721                                                 SourceLocation(), 0,
722                                                 *ParamType, VarDecl::None,
723                                                 0);
724        Param->setImplicit();
725        Params.push_back(Param);
726      }
727
728      New->setParams(Context, &Params[0], Params.size());
729    }
730
731    return MergeCompatibleFunctionDecls(New, Old);
732  }
733
734  // GNU C permits a K&R definition to follow a prototype declaration
735  // if the declared types of the parameters in the K&R definition
736  // match the types in the prototype declaration, even when the
737  // promoted types of the parameters from the K&R definition differ
738  // from the types in the prototype. GCC then keeps the types from
739  // the prototype.
740  if (!getLangOptions().CPlusPlus &&
741      !getLangOptions().NoExtensions &&
742      Old->hasPrototype() && !New->hasPrototype() &&
743      New->getType()->getAsFunctionProtoType() &&
744      Old->getNumParams() == New->getNumParams()) {
745    llvm::SmallVector<QualType, 16> ArgTypes;
746    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
747    const FunctionProtoType *OldProto
748      = Old->getType()->getAsFunctionProtoType();
749    const FunctionProtoType *NewProto
750      = New->getType()->getAsFunctionProtoType();
751
752    // Determine whether this is the GNU C extension.
753    bool GNUCompatible =
754      Context.typesAreCompatible(OldProto->getResultType(),
755                                 NewProto->getResultType()) &&
756      (OldProto->isVariadic() == NewProto->isVariadic());
757    for (unsigned Idx = 0, End = Old->getNumParams();
758         GNUCompatible && Idx != End; ++Idx) {
759      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
760      ParmVarDecl *NewParm = New->getParamDecl(Idx);
761      if (Context.typesAreCompatible(OldParm->getType(),
762                                     NewProto->getArgType(Idx))) {
763        ArgTypes.push_back(NewParm->getType());
764      } else if (Context.typesAreCompatible(OldParm->getType(),
765                                            NewParm->getType())) {
766        GNUCompatibleParamWarning Warn
767          = { OldParm, NewParm, NewProto->getArgType(Idx) };
768        Warnings.push_back(Warn);
769        ArgTypes.push_back(NewParm->getType());
770      } else
771        GNUCompatible = false;
772    }
773
774    if (GNUCompatible) {
775      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
776        Diag(Warnings[Warn].NewParm->getLocation(),
777             diag::ext_param_promoted_not_compatible_with_prototype)
778          << Warnings[Warn].PromotedType
779          << Warnings[Warn].OldParm->getType();
780        Diag(Warnings[Warn].OldParm->getLocation(),
781             diag::note_previous_declaration);
782      }
783
784      New->setType(Context.getFunctionType(NewProto->getResultType(),
785                                           &ArgTypes[0], ArgTypes.size(),
786                                           NewProto->isVariadic(),
787                                           NewProto->getTypeQuals()));
788      return MergeCompatibleFunctionDecls(New, Old);
789    }
790
791    // Fall through to diagnose conflicting types.
792  }
793
794  // A function that has already been declared has been redeclared or defined
795  // with a different type- show appropriate diagnostic
796  if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
797    // The user has declared a builtin function with an incompatible
798    // signature.
799    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
800      // The function the user is redeclaring is a library-defined
801      // function like 'malloc' or 'printf'. Warn about the
802      // redeclaration, then pretend that we don't know about this
803      // library built-in.
804      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
805      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
806        << Old << Old->getType();
807      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
808      Old->setInvalidDecl();
809      return false;
810    }
811
812    PrevDiag = diag::note_previous_builtin_declaration;
813  }
814
815  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
816  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
817  return true;
818}
819
820/// \brief Completes the merge of two function declarations that are
821/// known to be compatible.
822///
823/// This routine handles the merging of attributes and other
824/// properties of function declarations form the old declaration to
825/// the new declaration, once we know that New is in fact a
826/// redeclaration of Old.
827///
828/// \returns false
829bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
830  // Merge the attributes
831  MergeAttributes(New, Old, Context);
832
833  // Merge the storage class.
834  New->setStorageClass(Old->getStorageClass());
835
836  // FIXME: need to implement inline semantics
837
838  // Merge "pure" flag.
839  if (Old->isPure())
840    New->setPure();
841
842  // Merge the "deleted" flag.
843  if (Old->isDeleted())
844    New->setDeleted();
845
846  if (getLangOptions().CPlusPlus)
847    return MergeCXXFunctionDecl(New, Old);
848
849  return false;
850}
851
852/// MergeVarDecl - We just parsed a variable 'New' which has the same name
853/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
854/// situation, merging decls or emitting diagnostics as appropriate.
855///
856/// Tentative definition rules (C99 6.9.2p2) are checked by
857/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
858/// definitions here, since the initializer hasn't been attached.
859///
860bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
861  // Verify the old decl was also a variable.
862  VarDecl *Old = dyn_cast<VarDecl>(OldD);
863  if (!Old) {
864    Diag(New->getLocation(), diag::err_redefinition_different_kind)
865      << New->getDeclName();
866    Diag(OldD->getLocation(), diag::note_previous_definition);
867    return true;
868  }
869
870  MergeAttributes(New, Old, Context);
871
872  // Merge the types
873  QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
874  if (MergedT.isNull()) {
875    Diag(New->getLocation(), diag::err_redefinition_different_type)
876      << New->getDeclName();
877    Diag(Old->getLocation(), diag::note_previous_definition);
878    return true;
879  }
880  New->setType(MergedT);
881
882  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
883  if (New->getStorageClass() == VarDecl::Static &&
884      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
885    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
886    Diag(Old->getLocation(), diag::note_previous_definition);
887    return true;
888  }
889  // C99 6.2.2p4:
890  //   For an identifier declared with the storage-class specifier
891  //   extern in a scope in which a prior declaration of that
892  //   identifier is visible,23) if the prior declaration specifies
893  //   internal or external linkage, the linkage of the identifier at
894  //   the later declaration is the same as the linkage specified at
895  //   the prior declaration. If no prior declaration is visible, or
896  //   if the prior declaration specifies no linkage, then the
897  //   identifier has external linkage.
898  if (New->hasExternalStorage() && Old->hasLinkage())
899    /* Okay */;
900  else if (New->getStorageClass() != VarDecl::Static &&
901           Old->getStorageClass() == VarDecl::Static) {
902    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
903    Diag(Old->getLocation(), diag::note_previous_definition);
904    return true;
905  }
906
907  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
908
909  // FIXME: The test for external storage here seems wrong? We still
910  // need to check for mismatches.
911  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
912      // Don't complain about out-of-line definitions of static members.
913      !(Old->getLexicalDeclContext()->isRecord() &&
914        !New->getLexicalDeclContext()->isRecord())) {
915    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
916    Diag(Old->getLocation(), diag::note_previous_definition);
917    return true;
918  }
919
920  // Keep a chain of previous declarations.
921  New->setPreviousDeclaration(Old);
922
923  return false;
924}
925
926/// CheckParmsForFunctionDef - Check that the parameters of the given
927/// function are appropriate for the definition of a function. This
928/// takes care of any checks that cannot be performed on the
929/// declaration itself, e.g., that the types of each of the function
930/// parameters are complete.
931bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
932  bool HasInvalidParm = false;
933  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
934    ParmVarDecl *Param = FD->getParamDecl(p);
935
936    // C99 6.7.5.3p4: the parameters in a parameter type list in a
937    // function declarator that is part of a function definition of
938    // that function shall not have incomplete type.
939    //
940    // This is also C++ [dcl.fct]p6.
941    if (!Param->isInvalidDecl() &&
942        RequireCompleteType(Param->getLocation(), Param->getType(),
943                               diag::err_typecheck_decl_incomplete_type)) {
944      Param->setInvalidDecl();
945      HasInvalidParm = true;
946    }
947
948    // C99 6.9.1p5: If the declarator includes a parameter type list, the
949    // declaration of each parameter shall include an identifier.
950    if (Param->getIdentifier() == 0 &&
951        !Param->isImplicit() &&
952        !getLangOptions().CPlusPlus)
953      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
954  }
955
956  return HasInvalidParm;
957}
958
959/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
960/// no declarator (e.g. "struct foo;") is parsed.
961Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
962  // FIXME: Error on auto/register at file scope
963  // FIXME: Error on inline/virtual/explicit
964  // FIXME: Error on invalid restrict
965  // FIXME: Warn on useless const/volatile
966  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
967  // FIXME: Warn on useless attributes
968
969  TagDecl *Tag = 0;
970  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
971      DS.getTypeSpecType() == DeclSpec::TST_struct ||
972      DS.getTypeSpecType() == DeclSpec::TST_union ||
973      DS.getTypeSpecType() == DeclSpec::TST_enum)
974    Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
975
976  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
977    if (!Record->getDeclName() && Record->isDefinition() &&
978        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
979      if (getLangOptions().CPlusPlus ||
980          Record->getDeclContext()->isRecord())
981        return BuildAnonymousStructOrUnion(S, DS, Record);
982
983      Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
984        << DS.getSourceRange();
985    }
986
987    // Microsoft allows unnamed struct/union fields. Don't complain
988    // about them.
989    // FIXME: Should we support Microsoft's extensions in this area?
990    if (Record->getDeclName() && getLangOptions().Microsoft)
991      return DeclPtrTy::make(Tag);
992  }
993
994  if (!DS.isMissingDeclaratorOk() &&
995      DS.getTypeSpecType() != DeclSpec::TST_error) {
996    // Warn about typedefs of enums without names, since this is an
997    // extension in both Microsoft an GNU.
998    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
999        Tag && isa<EnumDecl>(Tag)) {
1000      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1001        << DS.getSourceRange();
1002      return DeclPtrTy::make(Tag);
1003    }
1004
1005    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1006      << DS.getSourceRange();
1007    return DeclPtrTy();
1008  }
1009
1010  return DeclPtrTy::make(Tag);
1011}
1012
1013/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1014/// anonymous struct or union AnonRecord into the owning context Owner
1015/// and scope S. This routine will be invoked just after we realize
1016/// that an unnamed union or struct is actually an anonymous union or
1017/// struct, e.g.,
1018///
1019/// @code
1020/// union {
1021///   int i;
1022///   float f;
1023/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1024///    // f into the surrounding scope.x
1025/// @endcode
1026///
1027/// This routine is recursive, injecting the names of nested anonymous
1028/// structs/unions into the owning context and scope as well.
1029bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1030                                               RecordDecl *AnonRecord) {
1031  bool Invalid = false;
1032  for (RecordDecl::field_iterator F = AnonRecord->field_begin(Context),
1033                               FEnd = AnonRecord->field_end(Context);
1034       F != FEnd; ++F) {
1035    if ((*F)->getDeclName()) {
1036      NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
1037                                                LookupOrdinaryName, true);
1038      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
1039        // C++ [class.union]p2:
1040        //   The names of the members of an anonymous union shall be
1041        //   distinct from the names of any other entity in the
1042        //   scope in which the anonymous union is declared.
1043        unsigned diagKind
1044          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
1045                                 : diag::err_anonymous_struct_member_redecl;
1046        Diag((*F)->getLocation(), diagKind)
1047          << (*F)->getDeclName();
1048        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1049        Invalid = true;
1050      } else {
1051        // C++ [class.union]p2:
1052        //   For the purpose of name lookup, after the anonymous union
1053        //   definition, the members of the anonymous union are
1054        //   considered to have been defined in the scope in which the
1055        //   anonymous union is declared.
1056        Owner->makeDeclVisibleInContext(Context, *F);
1057        S->AddDecl(DeclPtrTy::make(*F));
1058        IdResolver.AddDecl(*F);
1059      }
1060    } else if (const RecordType *InnerRecordType
1061                 = (*F)->getType()->getAsRecordType()) {
1062      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1063      if (InnerRecord->isAnonymousStructOrUnion())
1064        Invalid = Invalid ||
1065          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1066    }
1067  }
1068
1069  return Invalid;
1070}
1071
1072/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1073/// anonymous structure or union. Anonymous unions are a C++ feature
1074/// (C++ [class.union]) and a GNU C extension; anonymous structures
1075/// are a GNU C and GNU C++ extension.
1076Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1077                                                  RecordDecl *Record) {
1078  DeclContext *Owner = Record->getDeclContext();
1079
1080  // Diagnose whether this anonymous struct/union is an extension.
1081  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1082    Diag(Record->getLocation(), diag::ext_anonymous_union);
1083  else if (!Record->isUnion())
1084    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1085
1086  // C and C++ require different kinds of checks for anonymous
1087  // structs/unions.
1088  bool Invalid = false;
1089  if (getLangOptions().CPlusPlus) {
1090    const char* PrevSpec = 0;
1091    // C++ [class.union]p3:
1092    //   Anonymous unions declared in a named namespace or in the
1093    //   global namespace shall be declared static.
1094    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1095        (isa<TranslationUnitDecl>(Owner) ||
1096         (isa<NamespaceDecl>(Owner) &&
1097          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1098      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1099      Invalid = true;
1100
1101      // Recover by adding 'static'.
1102      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
1103    }
1104    // C++ [class.union]p3:
1105    //   A storage class is not allowed in a declaration of an
1106    //   anonymous union in a class scope.
1107    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1108             isa<RecordDecl>(Owner)) {
1109      Diag(DS.getStorageClassSpecLoc(),
1110           diag::err_anonymous_union_with_storage_spec);
1111      Invalid = true;
1112
1113      // Recover by removing the storage specifier.
1114      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1115                             PrevSpec);
1116    }
1117
1118    // C++ [class.union]p2:
1119    //   The member-specification of an anonymous union shall only
1120    //   define non-static data members. [Note: nested types and
1121    //   functions cannot be declared within an anonymous union. ]
1122    for (DeclContext::decl_iterator Mem = Record->decls_begin(Context),
1123                                 MemEnd = Record->decls_end(Context);
1124         Mem != MemEnd; ++Mem) {
1125      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1126        // C++ [class.union]p3:
1127        //   An anonymous union shall not have private or protected
1128        //   members (clause 11).
1129        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1130          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1131            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1132          Invalid = true;
1133        }
1134      } else if ((*Mem)->isImplicit()) {
1135        // Any implicit members are fine.
1136      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1137        // This is a type that showed up in an
1138        // elaborated-type-specifier inside the anonymous struct or
1139        // union, but which actually declares a type outside of the
1140        // anonymous struct or union. It's okay.
1141      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1142        if (!MemRecord->isAnonymousStructOrUnion() &&
1143            MemRecord->getDeclName()) {
1144          // This is a nested type declaration.
1145          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1146            << (int)Record->isUnion();
1147          Invalid = true;
1148        }
1149      } else {
1150        // We have something that isn't a non-static data
1151        // member. Complain about it.
1152        unsigned DK = diag::err_anonymous_record_bad_member;
1153        if (isa<TypeDecl>(*Mem))
1154          DK = diag::err_anonymous_record_with_type;
1155        else if (isa<FunctionDecl>(*Mem))
1156          DK = diag::err_anonymous_record_with_function;
1157        else if (isa<VarDecl>(*Mem))
1158          DK = diag::err_anonymous_record_with_static;
1159        Diag((*Mem)->getLocation(), DK)
1160            << (int)Record->isUnion();
1161          Invalid = true;
1162      }
1163    }
1164  }
1165
1166  if (!Record->isUnion() && !Owner->isRecord()) {
1167    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1168      << (int)getLangOptions().CPlusPlus;
1169    Invalid = true;
1170  }
1171
1172  // Create a declaration for this anonymous struct/union.
1173  NamedDecl *Anon = 0;
1174  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1175    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1176                             /*IdentifierInfo=*/0,
1177                             Context.getTypeDeclType(Record),
1178                             /*BitWidth=*/0, /*Mutable=*/false);
1179    Anon->setAccess(AS_public);
1180    if (getLangOptions().CPlusPlus)
1181      FieldCollector->Add(cast<FieldDecl>(Anon));
1182  } else {
1183    VarDecl::StorageClass SC;
1184    switch (DS.getStorageClassSpec()) {
1185    default: assert(0 && "Unknown storage class!");
1186    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1187    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1188    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1189    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1190    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1191    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1192    case DeclSpec::SCS_mutable:
1193      // mutable can only appear on non-static class members, so it's always
1194      // an error here
1195      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1196      Invalid = true;
1197      SC = VarDecl::None;
1198      break;
1199    }
1200
1201    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1202                           /*IdentifierInfo=*/0,
1203                           Context.getTypeDeclType(Record),
1204                           SC, DS.getSourceRange().getBegin());
1205  }
1206  Anon->setImplicit();
1207
1208  // Add the anonymous struct/union object to the current
1209  // context. We'll be referencing this object when we refer to one of
1210  // its members.
1211  Owner->addDecl(Context, Anon);
1212
1213  // Inject the members of the anonymous struct/union into the owning
1214  // context and into the identifier resolver chain for name lookup
1215  // purposes.
1216  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1217    Invalid = true;
1218
1219  // Mark this as an anonymous struct/union type. Note that we do not
1220  // do this until after we have already checked and injected the
1221  // members of this anonymous struct/union type, because otherwise
1222  // the members could be injected twice: once by DeclContext when it
1223  // builds its lookup table, and once by
1224  // InjectAnonymousStructOrUnionMembers.
1225  Record->setAnonymousStructOrUnion(true);
1226
1227  if (Invalid)
1228    Anon->setInvalidDecl();
1229
1230  return DeclPtrTy::make(Anon);
1231}
1232
1233
1234/// GetNameForDeclarator - Determine the full declaration name for the
1235/// given Declarator.
1236DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1237  switch (D.getKind()) {
1238  case Declarator::DK_Abstract:
1239    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1240    return DeclarationName();
1241
1242  case Declarator::DK_Normal:
1243    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1244    return DeclarationName(D.getIdentifier());
1245
1246  case Declarator::DK_Constructor: {
1247    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1248    Ty = Context.getCanonicalType(Ty);
1249    return Context.DeclarationNames.getCXXConstructorName(Ty);
1250  }
1251
1252  case Declarator::DK_Destructor: {
1253    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1254    Ty = Context.getCanonicalType(Ty);
1255    return Context.DeclarationNames.getCXXDestructorName(Ty);
1256  }
1257
1258  case Declarator::DK_Conversion: {
1259    // FIXME: We'd like to keep the non-canonical type for diagnostics!
1260    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1261    Ty = Context.getCanonicalType(Ty);
1262    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1263  }
1264
1265  case Declarator::DK_Operator:
1266    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1267    return Context.DeclarationNames.getCXXOperatorName(
1268                                                D.getOverloadedOperator());
1269  }
1270
1271  assert(false && "Unknown name kind");
1272  return DeclarationName();
1273}
1274
1275/// isNearlyMatchingFunction - Determine whether the C++ functions
1276/// Declaration and Definition are "nearly" matching. This heuristic
1277/// is used to improve diagnostics in the case where an out-of-line
1278/// function definition doesn't match any declaration within
1279/// the class or namespace.
1280static bool isNearlyMatchingFunction(ASTContext &Context,
1281                                     FunctionDecl *Declaration,
1282                                     FunctionDecl *Definition) {
1283  if (Declaration->param_size() != Definition->param_size())
1284    return false;
1285  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1286    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1287    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1288
1289    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1290    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1291    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1292      return false;
1293  }
1294
1295  return true;
1296}
1297
1298Sema::DeclPtrTy
1299Sema::ActOnDeclarator(Scope *S, Declarator &D, bool IsFunctionDefinition) {
1300  DeclarationName Name = GetNameForDeclarator(D);
1301
1302  // All of these full declarators require an identifier.  If it doesn't have
1303  // one, the ParsedFreeStandingDeclSpec action should be used.
1304  if (!Name) {
1305    if (!D.getInvalidType())  // Reject this if we think it is valid.
1306      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1307           diag::err_declarator_need_ident)
1308        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1309    return DeclPtrTy();
1310  }
1311
1312  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1313  // we find one that is.
1314  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1315         (S->getFlags() & Scope::TemplateParamScope) != 0)
1316    S = S->getParent();
1317
1318  DeclContext *DC;
1319  NamedDecl *PrevDecl;
1320  NamedDecl *New;
1321  bool InvalidDecl = false;
1322
1323  QualType R = GetTypeForDeclarator(D, S);
1324  if (R.isNull()) {
1325    InvalidDecl = true;
1326    R = Context.IntTy;
1327    if (IsFunctionDefinition) // int(...)
1328      R = Context.getFunctionType(R, 0, 0, true, 0);
1329
1330  }
1331
1332  // See if this is a redefinition of a variable in the same scope.
1333  if (D.getCXXScopeSpec().isInvalid()) {
1334    DC = CurContext;
1335    PrevDecl = 0;
1336    InvalidDecl = true;
1337  } else if (!D.getCXXScopeSpec().isSet()) {
1338    LookupNameKind NameKind = LookupOrdinaryName;
1339
1340    // If the declaration we're planning to build will be a function
1341    // or object with linkage, then look for another declaration with
1342    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1343    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1344      /* Do nothing*/;
1345    else if (R->isFunctionType()) {
1346      if (CurContext->isFunctionOrMethod())
1347        NameKind = LookupRedeclarationWithLinkage;
1348    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1349      NameKind = LookupRedeclarationWithLinkage;
1350
1351    DC = CurContext;
1352    PrevDecl = LookupName(S, Name, NameKind, true,
1353                          D.getDeclSpec().getStorageClassSpec() !=
1354                            DeclSpec::SCS_static,
1355                          D.getIdentifierLoc());
1356  } else { // Something like "int foo::x;"
1357    DC = computeDeclContext(D.getCXXScopeSpec());
1358    // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
1359    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
1360
1361    // C++ 7.3.1.2p2:
1362    // Members (including explicit specializations of templates) of a named
1363    // namespace can also be defined outside that namespace by explicit
1364    // qualification of the name being defined, provided that the entity being
1365    // defined was already declared in the namespace and the definition appears
1366    // after the point of declaration in a namespace that encloses the
1367    // declarations namespace.
1368    //
1369    // Note that we only check the context at this point. We don't yet
1370    // have enough information to make sure that PrevDecl is actually
1371    // the declaration we want to match. For example, given:
1372    //
1373    //   class X {
1374    //     void f();
1375    //     void f(float);
1376    //   };
1377    //
1378    //   void X::f(int) { } // ill-formed
1379    //
1380    // In this case, PrevDecl will point to the overload set
1381    // containing the two f's declared in X, but neither of them
1382    // matches.
1383
1384    // First check whether we named the global scope.
1385    if (isa<TranslationUnitDecl>(DC)) {
1386      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1387        << Name << D.getCXXScopeSpec().getRange();
1388    } else if (!CurContext->Encloses(DC)) {
1389      // The qualifying scope doesn't enclose the original declaration.
1390      // Emit diagnostic based on current scope.
1391      SourceLocation L = D.getIdentifierLoc();
1392      SourceRange R = D.getCXXScopeSpec().getRange();
1393      if (isa<FunctionDecl>(CurContext))
1394        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1395      else
1396        Diag(L, diag::err_invalid_declarator_scope)
1397          << Name << cast<NamedDecl>(DC) << R;
1398      InvalidDecl = true;
1399    }
1400  }
1401
1402  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1403    // Maybe we will complain about the shadowed template parameter.
1404    InvalidDecl = InvalidDecl
1405      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
1406    // Just pretend that we didn't see the previous declaration.
1407    PrevDecl = 0;
1408  }
1409
1410  // In C++, the previous declaration we find might be a tag type
1411  // (class or enum). In this case, the new declaration will hide the
1412  // tag type. Note that this does does not apply if we're declaring a
1413  // typedef (C++ [dcl.typedef]p4).
1414  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1415      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1416    PrevDecl = 0;
1417
1418  bool Redeclaration = false;
1419  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1420    New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl,
1421                                 InvalidDecl, Redeclaration);
1422  } else if (R->isFunctionType()) {
1423    New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl,
1424                                  IsFunctionDefinition, InvalidDecl,
1425                                  Redeclaration);
1426  } else {
1427    New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl,
1428                                  InvalidDecl, Redeclaration);
1429  }
1430
1431  if (New == 0)
1432    return DeclPtrTy();
1433
1434  // If this has an identifier and is not an invalid redeclaration,
1435  // add it to the scope stack.
1436  if (Name && !(Redeclaration && InvalidDecl))
1437    PushOnScopeChains(New, S);
1438  // If any semantic error occurred, mark the decl as invalid.
1439  if (D.getInvalidType() || InvalidDecl)
1440    New->setInvalidDecl();
1441
1442  return DeclPtrTy::make(New);
1443}
1444
1445/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1446/// types into constant array types in certain situations which would otherwise
1447/// be errors (for GCC compatibility).
1448static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1449                                                    ASTContext &Context,
1450                                                    bool &SizeIsNegative) {
1451  // This method tries to turn a variable array into a constant
1452  // array even when the size isn't an ICE.  This is necessary
1453  // for compatibility with code that depends on gcc's buggy
1454  // constant expression folding, like struct {char x[(int)(char*)2];}
1455  SizeIsNegative = false;
1456
1457  if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1458    QualType Pointee = PTy->getPointeeType();
1459    QualType FixedType =
1460        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1461    if (FixedType.isNull()) return FixedType;
1462    FixedType = Context.getPointerType(FixedType);
1463    FixedType.setCVRQualifiers(T.getCVRQualifiers());
1464    return FixedType;
1465  }
1466
1467  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1468  if (!VLATy)
1469    return QualType();
1470  // FIXME: We should probably handle this case
1471  if (VLATy->getElementType()->isVariablyModifiedType())
1472    return QualType();
1473
1474  Expr::EvalResult EvalResult;
1475  if (!VLATy->getSizeExpr() ||
1476      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1477      !EvalResult.Val.isInt())
1478    return QualType();
1479
1480  llvm::APSInt &Res = EvalResult.Val.getInt();
1481  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1482    return Context.getConstantArrayType(VLATy->getElementType(),
1483                                        Res, ArrayType::Normal, 0);
1484
1485  SizeIsNegative = true;
1486  return QualType();
1487}
1488
1489/// \brief Register the given locally-scoped external C declaration so
1490/// that it can be found later for redeclarations
1491void
1492Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1493                                       Scope *S) {
1494  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1495         "Decl is not a locally-scoped decl!");
1496  // Note that we have a locally-scoped external with this name.
1497  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1498
1499  if (!PrevDecl)
1500    return;
1501
1502  // If there was a previous declaration of this variable, it may be
1503  // in our identifier chain. Update the identifier chain with the new
1504  // declaration.
1505  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
1506    // The previous declaration was found on the identifer resolver
1507    // chain, so remove it from its scope.
1508    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
1509      S = S->getParent();
1510
1511    if (S)
1512      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
1513  }
1514}
1515
1516/// \brief Diagnose function specifiers on a declaration of an identifier that
1517/// does not identify a function.
1518void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
1519  // FIXME: We should probably indicate the identifier in question to avoid
1520  // confusion for constructs like "inline int a(), b;"
1521  if (D.getDeclSpec().isInlineSpecified())
1522    Diag(D.getDeclSpec().getInlineSpecLoc(),
1523         diag::err_inline_non_function);
1524
1525  if (D.getDeclSpec().isVirtualSpecified())
1526    Diag(D.getDeclSpec().getVirtualSpecLoc(),
1527         diag::err_virtual_non_function);
1528
1529  if (D.getDeclSpec().isExplicitSpecified())
1530    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1531         diag::err_explicit_non_function);
1532}
1533
1534NamedDecl*
1535Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1536                             QualType R, Decl* PrevDecl, bool& InvalidDecl,
1537                             bool &Redeclaration) {
1538  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1539  if (D.getCXXScopeSpec().isSet()) {
1540    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1541      << D.getCXXScopeSpec().getRange();
1542    InvalidDecl = true;
1543    // Pretend we didn't see the scope specifier.
1544    DC = 0;
1545  }
1546
1547  if (getLangOptions().CPlusPlus) {
1548    // Check that there are no default arguments (C++ only).
1549    CheckExtraCXXDefaultArguments(D);
1550  }
1551
1552  DiagnoseFunctionSpecifiers(D);
1553
1554  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R);
1555  if (!NewTD) return 0;
1556
1557  // Handle attributes prior to checking for duplicates in MergeVarDecl
1558  ProcessDeclAttributes(NewTD, D);
1559  // Merge the decl with the existing one if appropriate. If the decl is
1560  // in an outer scope, it isn't the same thing.
1561  if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1562    Redeclaration = true;
1563    if (MergeTypeDefDecl(NewTD, PrevDecl))
1564      InvalidDecl = true;
1565  }
1566
1567  if (S->getFnParent() == 0) {
1568    QualType T = NewTD->getUnderlyingType();
1569    // C99 6.7.7p2: If a typedef name specifies a variably modified type
1570    // then it shall have block scope.
1571    if (T->isVariablyModifiedType()) {
1572      bool SizeIsNegative;
1573      QualType FixedTy =
1574          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1575      if (!FixedTy.isNull()) {
1576        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1577        NewTD->setUnderlyingType(FixedTy);
1578      } else {
1579        if (SizeIsNegative)
1580          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1581        else if (T->isVariableArrayType())
1582          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1583        else
1584          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1585        InvalidDecl = true;
1586      }
1587    }
1588  }
1589  return NewTD;
1590}
1591
1592/// \brief Determines whether the given declaration is an out-of-scope
1593/// previous declaration.
1594///
1595/// This routine should be invoked when name lookup has found a
1596/// previous declaration (PrevDecl) that is not in the scope where a
1597/// new declaration by the same name is being introduced. If the new
1598/// declaration occurs in a local scope, previous declarations with
1599/// linkage may still be considered previous declarations (C99
1600/// 6.2.2p4-5, C++ [basic.link]p6).
1601///
1602/// \param PrevDecl the previous declaration found by name
1603/// lookup
1604///
1605/// \param DC the context in which the new declaration is being
1606/// declared.
1607///
1608/// \returns true if PrevDecl is an out-of-scope previous declaration
1609/// for a new delcaration with the same name.
1610static bool
1611isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1612                                ASTContext &Context) {
1613  if (!PrevDecl)
1614    return 0;
1615
1616  // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1617  // case we need to check each of the overloaded functions.
1618  if (!PrevDecl->hasLinkage())
1619    return false;
1620
1621  if (Context.getLangOptions().CPlusPlus) {
1622    // C++ [basic.link]p6:
1623    //   If there is a visible declaration of an entity with linkage
1624    //   having the same name and type, ignoring entities declared
1625    //   outside the innermost enclosing namespace scope, the block
1626    //   scope declaration declares that same entity and receives the
1627    //   linkage of the previous declaration.
1628    DeclContext *OuterContext = DC->getLookupContext();
1629    if (!OuterContext->isFunctionOrMethod())
1630      // This rule only applies to block-scope declarations.
1631      return false;
1632    else {
1633      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1634      if (PrevOuterContext->isRecord())
1635        // We found a member function: ignore it.
1636        return false;
1637      else {
1638        // Find the innermost enclosing namespace for the new and
1639        // previous declarations.
1640        while (!OuterContext->isFileContext())
1641          OuterContext = OuterContext->getParent();
1642        while (!PrevOuterContext->isFileContext())
1643          PrevOuterContext = PrevOuterContext->getParent();
1644
1645        // The previous declaration is in a different namespace, so it
1646        // isn't the same function.
1647        if (OuterContext->getPrimaryContext() !=
1648            PrevOuterContext->getPrimaryContext())
1649          return false;
1650      }
1651    }
1652  }
1653
1654  return true;
1655}
1656
1657NamedDecl*
1658Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1659                              QualType R,NamedDecl* PrevDecl, bool& InvalidDecl,
1660                              bool &Redeclaration) {
1661  DeclarationName Name = GetNameForDeclarator(D);
1662
1663  // Check that there are no default arguments (C++ only).
1664  if (getLangOptions().CPlusPlus)
1665    CheckExtraCXXDefaultArguments(D);
1666
1667  VarDecl *NewVD;
1668  VarDecl::StorageClass SC;
1669  switch (D.getDeclSpec().getStorageClassSpec()) {
1670  default: assert(0 && "Unknown storage class!");
1671  case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1672  case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1673  case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1674  case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1675  case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1676  case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1677  case DeclSpec::SCS_mutable:
1678    // mutable can only appear on non-static class members, so it's always
1679    // an error here
1680    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1681    InvalidDecl = true;
1682    SC = VarDecl::None;
1683    break;
1684  }
1685
1686  IdentifierInfo *II = Name.getAsIdentifierInfo();
1687  if (!II) {
1688    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1689      << Name.getAsString();
1690    return 0;
1691  }
1692
1693  DiagnoseFunctionSpecifiers(D);
1694
1695  bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1696  if (!DC->isRecord() && S->getFnParent() == 0) {
1697    // C99 6.9p2: The storage-class specifiers auto and register shall not
1698    // appear in the declaration specifiers in an external declaration.
1699    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1700      Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1701      InvalidDecl = true;
1702    }
1703  }
1704  if (DC->isRecord() && !CurContext->isRecord()) {
1705    // This is an out-of-line definition of a static data member.
1706    if (SC == VarDecl::Static) {
1707      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1708           diag::err_static_out_of_line)
1709        << CodeModificationHint::CreateRemoval(
1710                       SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
1711    } else if (SC == VarDecl::None)
1712      SC = VarDecl::Static;
1713  }
1714
1715  // The variable can not
1716  NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1717                          II, R, SC,
1718                          // FIXME: Move to DeclGroup...
1719                          D.getDeclSpec().getSourceRange().getBegin());
1720  NewVD->setThreadSpecified(ThreadSpecified);
1721
1722  // Set the lexical context. If the declarator has a C++ scope specifier, the
1723  // lexical context will be different from the semantic context.
1724  NewVD->setLexicalDeclContext(CurContext);
1725
1726  // Handle attributes prior to checking for duplicates in MergeVarDecl
1727  ProcessDeclAttributes(NewVD, D);
1728
1729  // Handle GNU asm-label extension (encoded as an attribute).
1730  if (Expr *E = (Expr*) D.getAsmLabel()) {
1731    // The parser guarantees this is a string.
1732    StringLiteral *SE = cast<StringLiteral>(E);
1733    NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
1734                                                        SE->getByteLength())));
1735  }
1736
1737  // If name lookup finds a previous declaration that is not in the
1738  // same scope as the new declaration, this may still be an
1739  // acceptable redeclaration.
1740  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
1741      !(NewVD->hasLinkage() &&
1742        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
1743    PrevDecl = 0;
1744
1745  // Merge the decl with the existing one if appropriate.
1746  if (PrevDecl) {
1747    if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1748      // The user tried to define a non-static data member
1749      // out-of-line (C++ [dcl.meaning]p1).
1750      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1751        << D.getCXXScopeSpec().getRange();
1752      PrevDecl = 0;
1753      InvalidDecl = true;
1754    }
1755  } else if (D.getCXXScopeSpec().isSet()) {
1756    // No previous declaration in the qualifying scope.
1757    Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1758      << Name << D.getCXXScopeSpec().getRange();
1759    InvalidDecl = true;
1760  }
1761
1762  if (CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration))
1763    InvalidDecl = true;
1764
1765  // If this is a locally-scoped extern C variable, update the map of
1766  // such variables.
1767  if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
1768      !InvalidDecl)
1769    RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
1770
1771  return NewVD;
1772}
1773
1774/// \brief Perform semantic checking on a newly-created variable
1775/// declaration.
1776///
1777/// This routine performs all of the type-checking required for a
1778/// variable declaration once it has been build. It is used both to
1779/// check variables after they have been parsed and their declarators
1780/// have been translated into a declaration, and to check
1781///
1782/// \returns true if an error was encountered, false otherwise.
1783bool Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
1784                                    bool &Redeclaration) {
1785  bool Invalid = false;
1786
1787  QualType T = NewVD->getType();
1788
1789  if (T->isObjCInterfaceType()) {
1790    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
1791    Invalid = true;
1792  }
1793
1794  // The variable can not have an abstract class type.
1795  if (RequireNonAbstractType(NewVD->getLocation(), T,
1796                             diag::err_abstract_type_in_decl,
1797                             AbstractVariableType))
1798    Invalid = true;
1799
1800  // Emit an error if an address space was applied to decl with local storage.
1801  // This includes arrays of objects with address space qualifiers, but not
1802  // automatic variables that point to other address spaces.
1803  // ISO/IEC TR 18037 S5.1.2
1804  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
1805    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
1806    Invalid = true;
1807  }
1808
1809  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
1810      && !NewVD->hasAttr<BlocksAttr>())
1811    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
1812
1813  bool isIllegalVLA = T->isVariableArrayType() && NewVD->hasGlobalStorage();
1814  bool isIllegalVM = T->isVariablyModifiedType() && NewVD->hasLinkage();
1815  if (isIllegalVLA || isIllegalVM) {
1816    bool SizeIsNegative;
1817    QualType FixedTy =
1818        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1819    if (!FixedTy.isNull()) {
1820      Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
1821      NewVD->setType(FixedTy);
1822    } else if (T->isVariableArrayType()) {
1823      Invalid = true;
1824
1825      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
1826      // FIXME: This won't give the correct result for
1827      // int a[10][n];
1828      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
1829
1830      if (NewVD->isFileVarDecl())
1831        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
1832          << SizeRange;
1833      else if (NewVD->getStorageClass() == VarDecl::Static)
1834        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
1835          << SizeRange;
1836      else
1837        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
1838            << SizeRange;
1839    } else {
1840      Invalid = true;
1841
1842      if (NewVD->isFileVarDecl())
1843        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
1844      else
1845        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
1846    }
1847  }
1848
1849  if (!PrevDecl && NewVD->isExternC(Context)) {
1850    // Since we did not find anything by this name and we're declaring
1851    // an extern "C" variable, look for a non-visible extern "C"
1852    // declaration with the same name.
1853    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
1854      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
1855    if (Pos != LocallyScopedExternalDecls.end())
1856      PrevDecl = Pos->second;
1857  }
1858
1859  if (!Invalid && T->isVoidType() && !NewVD->hasExternalStorage()) {
1860    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
1861      << T;
1862    Invalid = true;
1863  }
1864
1865  if (PrevDecl) {
1866    Redeclaration = true;
1867    if (MergeVarDecl(NewVD, PrevDecl))
1868      Invalid = true;
1869  }
1870
1871  return NewVD->isInvalidDecl() || Invalid;
1872}
1873
1874NamedDecl*
1875Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1876                              QualType R, NamedDecl* PrevDecl,
1877                              bool IsFunctionDefinition,
1878                              bool& InvalidDecl, bool &Redeclaration) {
1879  assert(R.getTypePtr()->isFunctionType());
1880
1881  DeclarationName Name = GetNameForDeclarator(D);
1882  FunctionDecl::StorageClass SC = FunctionDecl::None;
1883  switch (D.getDeclSpec().getStorageClassSpec()) {
1884  default: assert(0 && "Unknown storage class!");
1885  case DeclSpec::SCS_auto:
1886  case DeclSpec::SCS_register:
1887  case DeclSpec::SCS_mutable:
1888    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1889         diag::err_typecheck_sclass_func);
1890    InvalidDecl = true;
1891    break;
1892  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1893  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
1894  case DeclSpec::SCS_static: {
1895    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1896      // C99 6.7.1p5:
1897      //   The declaration of an identifier for a function that has
1898      //   block scope shall have no explicit storage-class specifier
1899      //   other than extern
1900      // See also (C++ [dcl.stc]p4).
1901      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1902           diag::err_static_block_func);
1903      SC = FunctionDecl::None;
1904    } else
1905      SC = FunctionDecl::Static;
1906    break;
1907  }
1908  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1909  }
1910
1911  bool isInline = D.getDeclSpec().isInlineSpecified();
1912  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1913  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1914
1915  // Check that the return type is not an abstract class type.
1916  // For record types, this is done by the AbstractClassUsageDiagnoser once
1917  // the class has been completely parsed.
1918  if (!DC->isRecord() &&
1919      RequireNonAbstractType(D.getIdentifierLoc(),
1920                             R->getAsFunctionType()->getResultType(),
1921                             diag::err_abstract_type_in_decl,
1922                             AbstractReturnType))
1923    InvalidDecl = true;
1924
1925  // Do not allow returning a objc interface by-value.
1926  if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) {
1927    Diag(D.getIdentifierLoc(),
1928         diag::err_object_cannot_be_passed_returned_by_value) << 0
1929      << R->getAsFunctionType()->getResultType();
1930    InvalidDecl = true;
1931  }
1932
1933  bool isVirtualOkay = false;
1934  FunctionDecl *NewFD;
1935  if (D.getKind() == Declarator::DK_Constructor) {
1936    // This is a C++ constructor declaration.
1937    assert(DC->isRecord() &&
1938           "Constructors can only be declared in a member context");
1939
1940    InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1941
1942    // Create the new declaration
1943    NewFD = CXXConstructorDecl::Create(Context,
1944                                       cast<CXXRecordDecl>(DC),
1945                                       D.getIdentifierLoc(), Name, R,
1946                                       isExplicit, isInline,
1947                                       /*isImplicitlyDeclared=*/false);
1948
1949    if (InvalidDecl)
1950      NewFD->setInvalidDecl();
1951  } else if (D.getKind() == Declarator::DK_Destructor) {
1952    // This is a C++ destructor declaration.
1953    if (DC->isRecord()) {
1954      InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1955
1956      NewFD = CXXDestructorDecl::Create(Context,
1957                                        cast<CXXRecordDecl>(DC),
1958                                        D.getIdentifierLoc(), Name, R,
1959                                        isInline,
1960                                        /*isImplicitlyDeclared=*/false);
1961
1962      if (InvalidDecl)
1963        NewFD->setInvalidDecl();
1964
1965      isVirtualOkay = true;
1966    } else {
1967      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1968
1969      // Create a FunctionDecl to satisfy the function definition parsing
1970      // code path.
1971      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1972                                   Name, R, SC, isInline,
1973                                   /*hasPrototype=*/true,
1974                                   // FIXME: Move to DeclGroup...
1975                                   D.getDeclSpec().getSourceRange().getBegin());
1976      InvalidDecl = true;
1977      NewFD->setInvalidDecl();
1978    }
1979  } else if (D.getKind() == Declarator::DK_Conversion) {
1980    if (!DC->isRecord()) {
1981      Diag(D.getIdentifierLoc(),
1982           diag::err_conv_function_not_member);
1983      return 0;
1984    } else {
1985      InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1986
1987      NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1988                                        D.getIdentifierLoc(), Name, R,
1989                                        isInline, isExplicit);
1990
1991      if (InvalidDecl)
1992        NewFD->setInvalidDecl();
1993
1994      isVirtualOkay = true;
1995    }
1996  } else if (DC->isRecord()) {
1997    // This is a C++ method declaration.
1998    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1999                                  D.getIdentifierLoc(), Name, R,
2000                                  (SC == FunctionDecl::Static), isInline);
2001
2002    isVirtualOkay = (SC != FunctionDecl::Static);
2003  } else {
2004    // Determine whether the function was written with a
2005    // prototype. This true when:
2006    //   - we're in C++ (where every function has a prototype),
2007    //   - there is a prototype in the declarator, or
2008    //   - the type R of the function is some kind of typedef or other reference
2009    //     to a type name (which eventually refers to a function type).
2010    bool HasPrototype =
2011       getLangOptions().CPlusPlus ||
2012       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2013       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2014
2015    NewFD = FunctionDecl::Create(Context, DC,
2016                                 D.getIdentifierLoc(),
2017                                 Name, R, SC, isInline, HasPrototype,
2018                                 // FIXME: Move to DeclGroup...
2019                                 D.getDeclSpec().getSourceRange().getBegin());
2020  }
2021
2022  // Set the lexical context. If the declarator has a C++
2023  // scope specifier, the lexical context will be different
2024  // from the semantic context.
2025  NewFD->setLexicalDeclContext(CurContext);
2026
2027  // C++ [dcl.fct.spec]p5:
2028  //   The virtual specifier shall only be used in declarations of
2029  //   nonstatic class member functions that appear within a
2030  //   member-specification of a class declaration; see 10.3.
2031  //
2032  // FIXME: Checking the 'virtual' specifier is not sufficient. A
2033  // function is also virtual if it overrides an already virtual
2034  // function. This is important to do here because it's part of the
2035  // declaration.
2036  if (isVirtual && !InvalidDecl) {
2037    if (!isVirtualOkay) {
2038       Diag(D.getDeclSpec().getVirtualSpecLoc(),
2039           diag::err_virtual_non_function);
2040    } else if (!CurContext->isRecord()) {
2041      // 'virtual' was specified outside of the class.
2042      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2043        << CodeModificationHint::CreateRemoval(
2044                             SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
2045    } else {
2046      // Okay: Add virtual to the method.
2047      cast<CXXMethodDecl>(NewFD)->setVirtual();
2048      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2049      CurClass->setAggregate(false);
2050      CurClass->setPOD(false);
2051      CurClass->setPolymorphic(true);
2052      CurClass->setHasTrivialConstructor(false);
2053    }
2054  }
2055
2056  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2057      !CurContext->isRecord()) {
2058    // C++ [class.static]p1:
2059    //   A data or function member of a class may be declared static
2060    //   in a class definition, in which case it is a static member of
2061    //   the class.
2062
2063    // Complain about the 'static' specifier if it's on an out-of-line
2064    // member function definition.
2065    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2066         diag::err_static_out_of_line)
2067      << CodeModificationHint::CreateRemoval(
2068                      SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
2069  }
2070
2071  // Handle GNU asm-label extension (encoded as an attribute).
2072  if (Expr *E = (Expr*) D.getAsmLabel()) {
2073    // The parser guarantees this is a string.
2074    StringLiteral *SE = cast<StringLiteral>(E);
2075    NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
2076                                                        SE->getByteLength())));
2077  }
2078
2079  // Copy the parameter declarations from the declarator D to
2080  // the function declaration NewFD, if they are available.
2081  if (D.getNumTypeObjects() > 0) {
2082    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2083
2084    // Create Decl objects for each parameter, adding them to the
2085    // FunctionDecl.
2086    llvm::SmallVector<ParmVarDecl*, 16> Params;
2087
2088    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2089    // function that takes no arguments, not a function that takes a
2090    // single void argument.
2091    // We let through "const void" here because Sema::GetTypeForDeclarator
2092    // already checks for that case.
2093    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2094        FTI.ArgInfo[0].Param &&
2095        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2096      // empty arg list, don't push any params.
2097      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2098
2099      // In C++, the empty parameter-type-list must be spelled "void"; a
2100      // typedef of void is not permitted.
2101      if (getLangOptions().CPlusPlus &&
2102          Param->getType().getUnqualifiedType() != Context.VoidTy) {
2103        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2104      }
2105    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2106      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2107        Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
2108    }
2109
2110    NewFD->setParams(Context, &Params[0], Params.size());
2111  } else if (R->getAsTypedefType()) {
2112    // When we're declaring a function with a typedef, as in the
2113    // following example, we'll need to synthesize (unnamed)
2114    // parameters for use in the declaration.
2115    //
2116    // @code
2117    // typedef void fn(int);
2118    // fn f;
2119    // @endcode
2120    const FunctionProtoType *FT = R->getAsFunctionProtoType();
2121    if (!FT) {
2122      // This is a typedef of a function with no prototype, so we
2123      // don't need to do anything.
2124    } else if ((FT->getNumArgs() == 0) ||
2125               (FT->getNumArgs() == 1 && !FT->isVariadic() &&
2126                FT->getArgType(0)->isVoidType())) {
2127      // This is a zero-argument function. We don't need to do anything.
2128    } else {
2129      // Synthesize a parameter for each argument type.
2130      llvm::SmallVector<ParmVarDecl*, 16> Params;
2131      for (FunctionProtoType::arg_type_iterator ArgType = FT->arg_type_begin();
2132           ArgType != FT->arg_type_end(); ++ArgType) {
2133        ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
2134                                                 SourceLocation(), 0,
2135                                                 *ArgType, VarDecl::None,
2136                                                 0);
2137        Param->setImplicit();
2138        Params.push_back(Param);
2139      }
2140
2141      NewFD->setParams(Context, &Params[0], Params.size());
2142    }
2143  }
2144
2145  // If name lookup finds a previous declaration that is not in the
2146  // same scope as the new declaration, this may still be an
2147  // acceptable redeclaration.
2148  if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
2149      !(NewFD->hasLinkage() &&
2150        isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
2151    PrevDecl = 0;
2152
2153  // Perform semantic checking on the function declaration.
2154  bool OverloadableAttrRequired = false; // FIXME: HACK!
2155  if (CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration,
2156                               /*FIXME:*/OverloadableAttrRequired))
2157    InvalidDecl = true;
2158
2159  if (D.getCXXScopeSpec().isSet() && !InvalidDecl) {
2160    // An out-of-line member function declaration must also be a
2161    // definition (C++ [dcl.meaning]p1).
2162    if (!IsFunctionDefinition) {
2163      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2164        << D.getCXXScopeSpec().getRange();
2165      InvalidDecl = true;
2166    } else if (!Redeclaration) {
2167      // The user tried to provide an out-of-line definition for a
2168      // function that is a member of a class or namespace, but there
2169      // was no such member function declared (C++ [class.mfct]p2,
2170      // C++ [namespace.memdef]p2). For example:
2171      //
2172      // class X {
2173      //   void f() const;
2174      // };
2175      //
2176      // void X::f() { } // ill-formed
2177      //
2178      // Complain about this problem, and attempt to suggest close
2179      // matches (e.g., those that differ only in cv-qualifiers and
2180      // whether the parameter types are references).
2181      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
2182        << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
2183      InvalidDecl = true;
2184
2185      LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2186                                              true);
2187      assert(!Prev.isAmbiguous() &&
2188             "Cannot have an ambiguity in previous-declaration lookup");
2189      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2190           Func != FuncEnd; ++Func) {
2191        if (isa<FunctionDecl>(*Func) &&
2192            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2193          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
2194      }
2195
2196      PrevDecl = 0;
2197    }
2198  }
2199
2200  // Handle attributes. We need to have merged decls when handling attributes
2201  // (for example to check for conflicts, etc).
2202  // FIXME: This needs to happen before we merge declarations. Then,
2203  // let attribute merging cope with attribute conflicts.
2204  ProcessDeclAttributes(NewFD, D);
2205  AddKnownFunctionAttributes(NewFD);
2206
2207  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2208    // If a function name is overloadable in C, then every function
2209    // with that name must be marked "overloadable".
2210    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
2211      << Redeclaration << NewFD;
2212    if (PrevDecl)
2213      Diag(PrevDecl->getLocation(),
2214           diag::note_attribute_overloadable_prev_overload);
2215    NewFD->addAttr(::new (Context) OverloadableAttr());
2216  }
2217
2218  // If this is a locally-scoped extern C function, update the
2219  // map of such names.
2220  if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context)
2221      && !InvalidDecl)
2222    RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
2223
2224  return NewFD;
2225}
2226
2227/// \brief Perform semantic checking of a new function declaration.
2228///
2229/// Performs semantic analysis of the new function declaration
2230/// NewFD. This routine performs all semantic checking that does not
2231/// require the actual declarator involved in the declaration, and is
2232/// used both for the declaration of functions as they are parsed
2233/// (called via ActOnDeclarator) and for the declaration of functions
2234/// that have been instantiated via C++ template instantiation (called
2235/// via InstantiateDecl).
2236///
2237/// \returns true if there was an error, false otherwise.
2238bool Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl,
2239                                    bool &Redeclaration,
2240                                    bool &OverloadableAttrRequired) {
2241  bool InvalidDecl = false;
2242
2243  // Semantic checking for this function declaration (in isolation).
2244  if (getLangOptions().CPlusPlus) {
2245    // C++-specific checks.
2246    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
2247      InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
2248    else if (isa<CXXDestructorDecl>(NewFD)) {
2249      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
2250      Record->setUserDeclaredDestructor(true);
2251      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
2252      // user-defined destructor.
2253      Record->setPOD(false);
2254
2255      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
2256      // declared destructor.
2257      Record->setHasTrivialDestructor(false);
2258    } else if (CXXConversionDecl *Conversion
2259               = dyn_cast<CXXConversionDecl>(NewFD))
2260      ActOnConversionDeclarator(Conversion);
2261
2262    // Extra checking for C++ overloaded operators (C++ [over.oper]).
2263    if (NewFD->isOverloadedOperator() &&
2264        CheckOverloadedOperatorDeclaration(NewFD))
2265      InvalidDecl = true;
2266  }
2267
2268  // Check for a previous declaration of this name.
2269  if (!PrevDecl && NewFD->isExternC(Context)) {
2270    // Since we did not find anything by this name and we're declaring
2271    // an extern "C" function, look for a non-visible extern "C"
2272    // declaration with the same name.
2273    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2274      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
2275    if (Pos != LocallyScopedExternalDecls.end())
2276      PrevDecl = Pos->second;
2277  }
2278
2279  // Merge or overload the declaration with an existing declaration of
2280  // the same name, if appropriate.
2281  if (PrevDecl) {
2282    // Determine whether NewFD is an overload of PrevDecl or
2283    // a declaration that requires merging. If it's an overload,
2284    // there's no more work to do here; we'll just add the new
2285    // function to the scope.
2286    OverloadedFunctionDecl::function_iterator MatchedDecl;
2287
2288    if (!getLangOptions().CPlusPlus &&
2289        AllowOverloadingOfFunction(PrevDecl, Context)) {
2290      OverloadableAttrRequired = true;
2291
2292      // Functions marked "overloadable" must have a prototype (that
2293      // we can't get through declaration merging).
2294      if (!NewFD->getType()->getAsFunctionProtoType()) {
2295        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
2296          << NewFD;
2297        InvalidDecl = true;
2298        Redeclaration = true;
2299
2300        // Turn this into a variadic function with no parameters.
2301        QualType R = Context.getFunctionType(
2302                       NewFD->getType()->getAsFunctionType()->getResultType(),
2303                       0, 0, true, 0);
2304        NewFD->setType(R);
2305      }
2306    }
2307
2308    if (PrevDecl &&
2309        (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2310         !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
2311      Redeclaration = true;
2312      Decl *OldDecl = PrevDecl;
2313
2314      // If PrevDecl was an overloaded function, extract the
2315      // FunctionDecl that matched.
2316      if (isa<OverloadedFunctionDecl>(PrevDecl))
2317        OldDecl = *MatchedDecl;
2318
2319      // NewFD and OldDecl represent declarations that need to be
2320      // merged.
2321      if (MergeFunctionDecl(NewFD, OldDecl))
2322        InvalidDecl = true;
2323
2324      if (!InvalidDecl)
2325        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
2326    }
2327  }
2328
2329  if (getLangOptions().CPlusPlus && !CurContext->isRecord()) {
2330    // In C++, check default arguments now that we have merged decls. Unless
2331    // the lexical context is the class, because in this case this is done
2332    // during delayed parsing anyway.
2333    CheckCXXDefaultArguments(NewFD);
2334  }
2335
2336  return InvalidDecl || NewFD->isInvalidDecl();
2337}
2338
2339bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2340  // FIXME: Need strict checking.  In C89, we need to check for
2341  // any assignment, increment, decrement, function-calls, or
2342  // commas outside of a sizeof.  In C99, it's the same list,
2343  // except that the aforementioned are allowed in unevaluated
2344  // expressions.  Everything else falls under the
2345  // "may accept other forms of constant expressions" exception.
2346  // (We never end up here for C++, so the constant expression
2347  // rules there don't matter.)
2348  if (Init->isConstantInitializer(Context))
2349    return false;
2350  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2351    << Init->getSourceRange();
2352  return true;
2353}
2354
2355void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
2356  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2357}
2358
2359/// AddInitializerToDecl - Adds the initializer Init to the
2360/// declaration dcl. If DirectInit is true, this is C++ direct
2361/// initialization rather than copy initialization.
2362void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
2363  Decl *RealDecl = dcl.getAs<Decl>();
2364  // If there is no declaration, there was an error parsing it.  Just ignore
2365  // the initializer.
2366  if (RealDecl == 0)
2367    return;
2368
2369  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
2370    // With declarators parsed the way they are, the parser cannot
2371    // distinguish between a normal initializer and a pure-specifier.
2372    // Thus this grotesque test.
2373    IntegerLiteral *IL;
2374    Expr *Init = static_cast<Expr *>(init.get());
2375    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
2376        Context.getCanonicalType(IL->getType()) == Context.IntTy) {
2377      if (Method->isVirtual()) {
2378        Method->setPure();
2379
2380        // A class is abstract if at least one function is pure virtual.
2381        cast<CXXRecordDecl>(CurContext)->setAbstract(true);
2382      } else if (!Method->isInvalidDecl()) {
2383        Diag(Method->getLocation(), diag::err_non_virtual_pure)
2384          << Method->getDeclName() << Init->getSourceRange();
2385        Method->setInvalidDecl();
2386      }
2387    } else {
2388      Diag(Method->getLocation(), diag::err_member_function_initialization)
2389        << Method->getDeclName() << Init->getSourceRange();
2390      Method->setInvalidDecl();
2391    }
2392    return;
2393  }
2394
2395  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2396  if (!VDecl) {
2397    if (getLangOptions().CPlusPlus &&
2398        RealDecl->getLexicalDeclContext()->isRecord() &&
2399        isa<NamedDecl>(RealDecl))
2400      Diag(RealDecl->getLocation(), diag::err_member_initialization)
2401        << cast<NamedDecl>(RealDecl)->getDeclName();
2402    else
2403      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2404    RealDecl->setInvalidDecl();
2405    return;
2406  }
2407
2408  if (!VDecl->getType()->isArrayType() &&
2409      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2410                          diag::err_typecheck_decl_incomplete_type)) {
2411    RealDecl->setInvalidDecl();
2412    return;
2413  }
2414
2415  const VarDecl *Def = 0;
2416  if (VDecl->getDefinition(Def)) {
2417    Diag(VDecl->getLocation(), diag::err_redefinition)
2418      << VDecl->getDeclName();
2419    Diag(Def->getLocation(), diag::note_previous_definition);
2420    VDecl->setInvalidDecl();
2421    return;
2422  }
2423
2424  // Take ownership of the expression, now that we're sure we have somewhere
2425  // to put it.
2426  Expr *Init = static_cast<Expr *>(init.release());
2427  assert(Init && "missing initializer");
2428
2429  // Get the decls type and save a reference for later, since
2430  // CheckInitializerTypes may change it.
2431  QualType DclT = VDecl->getType(), SavT = DclT;
2432  if (VDecl->isBlockVarDecl()) {
2433    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
2434      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2435      VDecl->setInvalidDecl();
2436    } else if (!VDecl->isInvalidDecl()) {
2437      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2438                                VDecl->getDeclName(), DirectInit))
2439        VDecl->setInvalidDecl();
2440
2441      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2442      // Don't check invalid declarations to avoid emitting useless diagnostics.
2443      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
2444        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
2445          CheckForConstantInitializer(Init, DclT);
2446      }
2447    }
2448  } else if (VDecl->isStaticDataMember() &&
2449             VDecl->getLexicalDeclContext()->isRecord()) {
2450    // This is an in-class initialization for a static data member, e.g.,
2451    //
2452    // struct S {
2453    //   static const int value = 17;
2454    // };
2455
2456    // Attach the initializer
2457    VDecl->setInit(Init);
2458
2459    // C++ [class.mem]p4:
2460    //   A member-declarator can contain a constant-initializer only
2461    //   if it declares a static member (9.4) of const integral or
2462    //   const enumeration type, see 9.4.2.
2463    QualType T = VDecl->getType();
2464    if (!T->isDependentType() &&
2465        (!Context.getCanonicalType(T).isConstQualified() ||
2466         !T->isIntegralType())) {
2467      Diag(VDecl->getLocation(), diag::err_member_initialization)
2468        << VDecl->getDeclName() << Init->getSourceRange();
2469      VDecl->setInvalidDecl();
2470    } else {
2471      // C++ [class.static.data]p4:
2472      //   If a static data member is of const integral or const
2473      //   enumeration type, its declaration in the class definition
2474      //   can specify a constant-initializer which shall be an
2475      //   integral constant expression (5.19).
2476      if (!Init->isTypeDependent() &&
2477          !Init->getType()->isIntegralType()) {
2478        // We have a non-dependent, non-integral or enumeration type.
2479        Diag(Init->getSourceRange().getBegin(),
2480             diag::err_in_class_initializer_non_integral_type)
2481          << Init->getType() << Init->getSourceRange();
2482        VDecl->setInvalidDecl();
2483      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
2484        // Check whether the expression is a constant expression.
2485        llvm::APSInt Value;
2486        SourceLocation Loc;
2487        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
2488          Diag(Loc, diag::err_in_class_initializer_non_constant)
2489            << Init->getSourceRange();
2490          VDecl->setInvalidDecl();
2491        } else if (!VDecl->getType()->isDependentType())
2492          ImpCastExprToType(Init, VDecl->getType());
2493      }
2494    }
2495  } else if (VDecl->isFileVarDecl()) {
2496    if (VDecl->getStorageClass() == VarDecl::Extern)
2497      Diag(VDecl->getLocation(), diag::warn_extern_init);
2498    if (!VDecl->isInvalidDecl())
2499      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2500                                VDecl->getDeclName(), DirectInit))
2501        VDecl->setInvalidDecl();
2502
2503    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2504    // Don't check invalid declarations to avoid emitting useless diagnostics.
2505    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
2506      // C99 6.7.8p4. All file scoped initializers need to be constant.
2507      CheckForConstantInitializer(Init, DclT);
2508    }
2509  }
2510  // If the type changed, it means we had an incomplete type that was
2511  // completed by the initializer. For example:
2512  //   int ary[] = { 1, 3, 5 };
2513  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2514  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2515    VDecl->setType(DclT);
2516    Init->setType(DclT);
2517  }
2518
2519  // Attach the initializer to the decl.
2520  VDecl->setInit(Init);
2521  return;
2522}
2523
2524void Sema::ActOnUninitializedDecl(DeclPtrTy dcl) {
2525  Decl *RealDecl = dcl.getAs<Decl>();
2526
2527  // If there is no declaration, there was an error parsing it. Just ignore it.
2528  if (RealDecl == 0)
2529    return;
2530
2531  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2532    QualType Type = Var->getType();
2533    // C++ [dcl.init.ref]p3:
2534    //   The initializer can be omitted for a reference only in a
2535    //   parameter declaration (8.3.5), in the declaration of a
2536    //   function return type, in the declaration of a class member
2537    //   within its class declaration (9.2), and where the extern
2538    //   specifier is explicitly used.
2539    if (Type->isReferenceType() && !Var->hasExternalStorage()) {
2540      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2541        << Var->getDeclName()
2542        << SourceRange(Var->getLocation(), Var->getLocation());
2543      Var->setInvalidDecl();
2544      return;
2545    }
2546
2547    // C++ [dcl.init]p9:
2548    //
2549    //   If no initializer is specified for an object, and the object
2550    //   is of (possibly cv-qualified) non-POD class type (or array
2551    //   thereof), the object shall be default-initialized; if the
2552    //   object is of const-qualified type, the underlying class type
2553    //   shall have a user-declared default constructor.
2554    if (getLangOptions().CPlusPlus) {
2555      QualType InitType = Type;
2556      if (const ArrayType *Array = Context.getAsArrayType(Type))
2557        InitType = Array->getElementType();
2558      if (!Var->hasExternalStorage() && InitType->isRecordType()) {
2559        CXXRecordDecl *RD =
2560          cast<CXXRecordDecl>(InitType->getAsRecordType()->getDecl());
2561        CXXConstructorDecl *Constructor = 0;
2562        if (!RequireCompleteType(Var->getLocation(), InitType,
2563                                    diag::err_invalid_incomplete_type_use))
2564          Constructor
2565            = PerformInitializationByConstructor(InitType, 0, 0,
2566                                                 Var->getLocation(),
2567                                               SourceRange(Var->getLocation(),
2568                                                           Var->getLocation()),
2569                                                 Var->getDeclName(),
2570                                                 IK_Default);
2571        if (!Constructor)
2572          Var->setInvalidDecl();
2573        else if (!RD->hasTrivialConstructor())
2574          InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0);
2575      }
2576    }
2577
2578#if 0
2579    // FIXME: Temporarily disabled because we are not properly parsing
2580    // linkage specifications on declarations, e.g.,
2581    //
2582    //   extern "C" const CGPoint CGPointerZero;
2583    //
2584    // C++ [dcl.init]p9:
2585    //
2586    //     If no initializer is specified for an object, and the
2587    //     object is of (possibly cv-qualified) non-POD class type (or
2588    //     array thereof), the object shall be default-initialized; if
2589    //     the object is of const-qualified type, the underlying class
2590    //     type shall have a user-declared default
2591    //     constructor. Otherwise, if no initializer is specified for
2592    //     an object, the object and its subobjects, if any, have an
2593    //     indeterminate initial value; if the object or any of its
2594    //     subobjects are of const-qualified type, the program is
2595    //     ill-formed.
2596    //
2597    // This isn't technically an error in C, so we don't diagnose it.
2598    //
2599    // FIXME: Actually perform the POD/user-defined default
2600    // constructor check.
2601    if (getLangOptions().CPlusPlus &&
2602        Context.getCanonicalType(Type).isConstQualified() &&
2603        !Var->hasExternalStorage())
2604      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2605        << Var->getName()
2606        << SourceRange(Var->getLocation(), Var->getLocation());
2607#endif
2608  }
2609}
2610
2611Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, DeclPtrTy *Group,
2612                                                   unsigned NumDecls) {
2613  llvm::SmallVector<Decl*, 8> Decls;
2614
2615  for (unsigned i = 0; i != NumDecls; ++i)
2616    if (Decl *D = Group[i].getAs<Decl>())
2617      Decls.push_back(D);
2618
2619  // Perform semantic analysis that depends on having fully processed both
2620  // the declarator and initializer.
2621  for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2622    VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
2623    if (!IDecl)
2624      continue;
2625    QualType T = IDecl->getType();
2626
2627    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2628    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2629    if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
2630      if (!IDecl->isInvalidDecl() &&
2631          RequireCompleteType(IDecl->getLocation(), T,
2632                              diag::err_typecheck_decl_incomplete_type))
2633        IDecl->setInvalidDecl();
2634    }
2635    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2636    // object that has file scope without an initializer, and without a
2637    // storage-class specifier or with the storage-class specifier "static",
2638    // constitutes a tentative definition. Note: A tentative definition with
2639    // external linkage is valid (C99 6.2.2p5).
2640    if (IDecl->isTentativeDefinition(Context)) {
2641      QualType CheckType = T;
2642      unsigned DiagID = diag::err_typecheck_decl_incomplete_type;
2643
2644      const IncompleteArrayType *ArrayT = Context.getAsIncompleteArrayType(T);
2645      if (ArrayT) {
2646        CheckType = ArrayT->getElementType();
2647        DiagID = diag::err_illegal_decl_array_incomplete_type;
2648      }
2649
2650      if (IDecl->isInvalidDecl()) {
2651        // Do nothing with invalid declarations
2652      } else if ((ArrayT || IDecl->getStorageClass() == VarDecl::Static) &&
2653                 RequireCompleteType(IDecl->getLocation(), CheckType, DiagID)) {
2654        // C99 6.9.2p3: If the declaration of an identifier for an object is
2655        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2656        // declared type shall not be an incomplete type.
2657        IDecl->setInvalidDecl();
2658      }
2659    }
2660  }
2661  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
2662                                                   &Decls[0], Decls.size()));
2663}
2664
2665
2666/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2667/// to introduce parameters into function prototype scope.
2668Sema::DeclPtrTy
2669Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2670  const DeclSpec &DS = D.getDeclSpec();
2671
2672  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2673  VarDecl::StorageClass StorageClass = VarDecl::None;
2674  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2675    StorageClass = VarDecl::Register;
2676  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2677    Diag(DS.getStorageClassSpecLoc(),
2678         diag::err_invalid_storage_class_in_func_decl);
2679    D.getMutableDeclSpec().ClearStorageClassSpecs();
2680  }
2681  if (DS.isThreadSpecified()) {
2682    Diag(DS.getThreadSpecLoc(),
2683         diag::err_invalid_storage_class_in_func_decl);
2684    D.getMutableDeclSpec().ClearStorageClassSpecs();
2685  }
2686  DiagnoseFunctionSpecifiers(D);
2687
2688  // Check that there are no default arguments inside the type of this
2689  // parameter (C++ only).
2690  if (getLangOptions().CPlusPlus)
2691    CheckExtraCXXDefaultArguments(D);
2692
2693  // In this context, we *do not* check D.getInvalidType(). If the declarator
2694  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2695  // though it will not reflect the user specified type.
2696  QualType parmDeclType = GetTypeForDeclarator(D, S);
2697  if (parmDeclType.isNull()) {
2698    D.setInvalidType(true);
2699    parmDeclType = Context.IntTy;
2700  }
2701
2702  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2703  // Can this happen for params?  We already checked that they don't conflict
2704  // among each other.  Here they can only shadow globals, which is ok.
2705  IdentifierInfo *II = D.getIdentifier();
2706  if (II) {
2707    if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2708      if (PrevDecl->isTemplateParameter()) {
2709        // Maybe we will complain about the shadowed template parameter.
2710        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2711        // Just pretend that we didn't see the previous declaration.
2712        PrevDecl = 0;
2713      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
2714        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2715
2716        // Recover by removing the name
2717        II = 0;
2718        D.SetIdentifier(0, D.getIdentifierLoc());
2719      }
2720    }
2721  }
2722
2723  // Parameters can not be abstract class types.
2724  // For record types, this is done by the AbstractClassUsageDiagnoser once
2725  // the class has been completely parsed.
2726  if (!CurContext->isRecord() &&
2727      RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
2728                             diag::err_abstract_type_in_decl,
2729                             AbstractParamType))
2730    D.setInvalidType(true);
2731
2732  QualType T = adjustParameterType(parmDeclType);
2733
2734  ParmVarDecl *New;
2735  if (T == parmDeclType) // parameter type did not need adjustment
2736    New = ParmVarDecl::Create(Context, CurContext,
2737                              D.getIdentifierLoc(), II,
2738                              parmDeclType, StorageClass,
2739                              0);
2740  else // keep track of both the adjusted and unadjusted types
2741    New = OriginalParmVarDecl::Create(Context, CurContext,
2742                                      D.getIdentifierLoc(), II, T,
2743                                      parmDeclType, StorageClass, 0);
2744
2745  if (D.getInvalidType())
2746    New->setInvalidDecl();
2747
2748  // Parameter declarators cannot be interface types. All ObjC objects are
2749  // passed by reference.
2750  if (T->isObjCInterfaceType()) {
2751    Diag(D.getIdentifierLoc(),
2752         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
2753    New->setInvalidDecl();
2754  }
2755
2756  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2757  if (D.getCXXScopeSpec().isSet()) {
2758    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2759      << D.getCXXScopeSpec().getRange();
2760    New->setInvalidDecl();
2761  }
2762
2763  // Add the parameter declaration into this scope.
2764  S->AddDecl(DeclPtrTy::make(New));
2765  if (II)
2766    IdResolver.AddDecl(New);
2767
2768  ProcessDeclAttributes(New, D);
2769  return DeclPtrTy::make(New);
2770}
2771
2772void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2773                                           SourceLocation LocAfterDecls) {
2774  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2775         "Not a function declarator!");
2776  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2777
2778  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2779  // for a K&R function.
2780  if (!FTI.hasPrototype) {
2781    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
2782      --i;
2783      if (FTI.ArgInfo[i].Param == 0) {
2784        std::string Code = "  int ";
2785        Code += FTI.ArgInfo[i].Ident->getName();
2786        Code += ";\n";
2787        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2788          << FTI.ArgInfo[i].Ident
2789          << CodeModificationHint::CreateInsertion(LocAfterDecls, Code);
2790
2791        // Implicitly declare the argument as type 'int' for lack of a better
2792        // type.
2793        DeclSpec DS;
2794        const char* PrevSpec; // unused
2795        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2796                           PrevSpec);
2797        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2798        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2799        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
2800      }
2801    }
2802  }
2803}
2804
2805Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
2806                                              Declarator &D) {
2807  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2808  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2809         "Not a function declarator!");
2810  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2811
2812  if (FTI.hasPrototype) {
2813    // FIXME: Diagnose arguments without names in C.
2814  }
2815
2816  Scope *ParentScope = FnBodyScope->getParent();
2817
2818  DeclPtrTy DP = ActOnDeclarator(ParentScope, D, /*IsFunctionDefinition=*/true);
2819  return ActOnStartOfFunctionDef(FnBodyScope, DP);
2820}
2821
2822Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
2823  FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>());
2824
2825  // See if this is a redefinition.
2826  const FunctionDecl *Definition;
2827  if (FD->getBody(Context, Definition)) {
2828    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2829    Diag(Definition->getLocation(), diag::note_previous_definition);
2830  }
2831
2832  // Builtin functions cannot be defined.
2833  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2834    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2835      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
2836      FD->setInvalidDecl();
2837    }
2838  }
2839
2840  // The return type of a function definition must be complete
2841  // (C99 6.9.1p3, C++ [dcl.fct]p6).
2842  QualType ResultType = FD->getResultType();
2843  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
2844      RequireCompleteType(FD->getLocation(), ResultType,
2845                          diag::err_func_def_incomplete_result))
2846    FD->setInvalidDecl();
2847
2848  // GNU warning -Wmissing-prototypes:
2849  //   Warn if a global function is defined without a previous
2850  //   prototype declaration. This warning is issued even if the
2851  //   definition itself provides a prototype. The aim is to detect
2852  //   global functions that fail to be declared in header files.
2853  if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) &&
2854      !FD->isMain()) {
2855    bool MissingPrototype = true;
2856    for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
2857         Prev; Prev = Prev->getPreviousDeclaration()) {
2858      // Ignore any declarations that occur in function or method
2859      // scope, because they aren't visible from the header.
2860      if (Prev->getDeclContext()->isFunctionOrMethod())
2861        continue;
2862
2863      MissingPrototype = !Prev->getType()->isFunctionProtoType();
2864      break;
2865    }
2866
2867    if (MissingPrototype)
2868      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
2869  }
2870
2871  PushDeclContext(FnBodyScope, FD);
2872
2873  // Check the validity of our function parameters
2874  CheckParmsForFunctionDef(FD);
2875
2876  // Introduce our parameters into the function scope
2877  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2878    ParmVarDecl *Param = FD->getParamDecl(p);
2879    Param->setOwningFunction(FD);
2880
2881    // If this has an identifier, add it to the scope stack.
2882    if (Param->getIdentifier())
2883      PushOnScopeChains(Param, FnBodyScope);
2884  }
2885
2886  // Checking attributes of current function definition
2887  // dllimport attribute.
2888  if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2889    // dllimport attribute cannot be applied to definition.
2890    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2891      Diag(FD->getLocation(),
2892           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2893        << "dllimport";
2894      FD->setInvalidDecl();
2895      return DeclPtrTy::make(FD);
2896    } else {
2897      // If a symbol previously declared dllimport is later defined, the
2898      // attribute is ignored in subsequent references, and a warning is
2899      // emitted.
2900      Diag(FD->getLocation(),
2901           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2902        << FD->getNameAsCString() << "dllimport";
2903    }
2904  }
2905  return DeclPtrTy::make(FD);
2906}
2907
2908
2909
2910/// TODO: statement expressions, for (int x[n]; ;), case.
2911/// TODO: check the body of an objc method.
2912
2913// TODO: Consider wording like: "branching bypasses declaration of
2914// variable-length"
2915
2916
2917/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
2918/// into VLA and other protected scopes.  For example, this rejects:
2919///    goto L;
2920///    int a[n];
2921///  L:
2922///
2923namespace {
2924class JumpScopeChecker {
2925  Sema &S;
2926
2927  /// GotoScope - This is a record that we use to keep track of all of the scopes
2928  /// that are introduced by VLAs and other things that scope jumps like gotos.
2929  /// This scope tree has nothing to do with the source scope tree, because you
2930  /// can have multiple VLA scopes per compound statement, and most compound
2931  /// statements don't introduce any scopes.
2932  struct GotoScope {
2933    /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
2934    /// the parent scope is the function body.
2935    unsigned ParentScope;
2936
2937    /// Diag - The diagnostic to emit if there is a jump into this scope.
2938    unsigned Diag;
2939
2940    /// Loc - Location to emit the diagnostic.
2941    SourceLocation Loc;
2942
2943    GotoScope(unsigned parentScope, unsigned diag, SourceLocation L)
2944    : ParentScope(parentScope), Diag(diag), Loc(L) {}
2945  };
2946
2947  llvm::SmallVector<GotoScope, 48> Scopes;
2948  llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
2949  llvm::SmallVector<Stmt*, 16> Jumps;
2950public:
2951  JumpScopeChecker(CompoundStmt *Body, Sema &S);
2952private:
2953  bool StatementCreatesScope(DeclStmt *S, unsigned ParentScope);
2954  void BuildScopeInformation(Stmt *S, unsigned ParentScope);
2955  void VerifyJumps();
2956  void CheckJump(Stmt *S, unsigned JumpTargetScope, unsigned JumpDiag);
2957};
2958} // end anonymous namespace
2959
2960
2961JumpScopeChecker::JumpScopeChecker(CompoundStmt *Body, Sema &s) : S(s) {
2962  // Add a scope entry for function scope.
2963  Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation()));
2964
2965  // Build information for the top level compound statement, so that we have a
2966  // defined scope record for every "goto" and label.
2967  BuildScopeInformation(Body, 0);
2968
2969  // Check that all jumps we saw are kosher.
2970  VerifyJumps();
2971}
2972
2973/// StatementCreatesScope - Return true if the specified statement should start
2974/// a new cleanup scope that cannot be entered with a goto.  When this returns
2975/// true it pushes a new scope onto the top of Scopes, indicating what scope to
2976/// use for sub-statements.
2977bool JumpScopeChecker::StatementCreatesScope(DeclStmt *DS,
2978                                             unsigned ParentScope) {
2979  // The decl statement creates a scope if any of the decls in it are VLAs or
2980  // have the cleanup attribute.
2981  for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
2982       I != E; ++I) {
2983    if (VarDecl *D = dyn_cast<VarDecl>(*I)) {
2984      if (D->getType()->isVariablyModifiedType()) {
2985        Scopes.push_back(GotoScope(ParentScope,
2986                                   diag::note_protected_by_vla,
2987                                   D->getLocation()));
2988        return true;  // FIXME: Handle int X[n], Y[n+1];
2989      }
2990      if (D->hasAttr<CleanupAttr>()) {
2991        Scopes.push_back(GotoScope(ParentScope,
2992                                   diag::note_protected_by_cleanup,
2993                                   D->getLocation()));
2994        return true;
2995      }
2996    } else if (TypedefDecl *D = dyn_cast<TypedefDecl>(*I)) {
2997      if (D->getUnderlyingType()->isVariablyModifiedType()) {
2998        Scopes.push_back(GotoScope(ParentScope,
2999                                   diag::note_protected_by_vla_typedef,
3000                                   D->getLocation()));
3001        return true;
3002      }
3003    }
3004  }
3005  return false;
3006}
3007
3008
3009/// BuildScopeInformation - The statements from CI to CE are known to form a
3010/// coherent VLA scope with a specified parent node.  Walk through the
3011/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
3012/// walking the AST as needed.
3013void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
3014
3015  // If we found a label, remember that it is in ParentScope scope.
3016  if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) {
3017    LabelAndGotoScopes[S] = ParentScope;
3018  } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) ||
3019             isa<IndirectGotoStmt>(S)) {
3020    // Remember both what scope a goto is in as well as the fact that we have
3021    // it.  This makes the second scan not have to walk the AST again.
3022    LabelAndGotoScopes[S] = ParentScope;
3023    Jumps.push_back(S);
3024  }
3025
3026  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3027       ++CI) {
3028    Stmt *SubStmt = *CI;
3029    if (SubStmt == 0) continue;
3030
3031    // FIXME: diagnose jumps past initialization: required in C++, warning in C.
3032    //     { int X = 4;   L: } goto L;
3033
3034    // If this is a declstmt with a VLA definition, it defines a scope from here
3035    // to the end of the containing context.
3036    if (isa<DeclStmt>(SubStmt) &&
3037        // If StatementCreatesScope returns true, then it pushed a new scope
3038        // onto Scopes.
3039        StatementCreatesScope(cast<DeclStmt>(SubStmt), ParentScope)) {
3040      // FIXME: what about substatements (initializers) of the DeclStmt itself?
3041      // TODO: int x = ({  int x[n]; label: ... });  // decl stmts matter.
3042
3043      // Continue analyzing the remaining statements in this scope with a new
3044      // parent scope ID.
3045      ParentScope = Scopes.size()-1;
3046      continue;
3047    }
3048
3049    // Disallow jumps into any part of an @try statement by pushing a scope and
3050    // walking all sub-stmts in that scope.
3051    if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
3052      Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_objc_try,
3053                                 AT->getAtTryLoc()));
3054      // Recursively walk the AST.
3055      BuildScopeInformation(SubStmt, Scopes.size()-1);
3056      continue;
3057    }
3058    // FIXME: what about jumps into C++ catch blocks, what are the rules?
3059
3060    // Recursively walk the AST.
3061    BuildScopeInformation(SubStmt, ParentScope);
3062  }
3063}
3064
3065void JumpScopeChecker::VerifyJumps() {
3066  while (!Jumps.empty()) {
3067    Stmt *Jump = Jumps.pop_back_val();
3068
3069    if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
3070      assert(LabelAndGotoScopes.count(GS->getLabel()) && "Label not visited?");
3071      CheckJump(GS, LabelAndGotoScopes[GS->getLabel()],
3072                diag::err_goto_into_protected_scope);
3073    } else if (isa<SwitchStmt>(Jump)) {
3074      // FIXME: Handle this.
3075      continue;
3076    } else {
3077      assert(isa<IndirectGotoStmt>(Jump));
3078      // FIXME: Emit an error on indirect gotos when not in scope 0.
3079      continue;
3080    }
3081  }
3082}
3083
3084/// CheckJump - Validate that the specified jump statement is valid: that it is
3085/// jumping within or out of its current scope, not into a deeper one.
3086void JumpScopeChecker::CheckJump(Stmt *Jump, unsigned JumpTargetScope,
3087                                 unsigned JumpDiag) {
3088  assert(LabelAndGotoScopes.count(Jump) && "Jump didn't get added to scopes?");
3089  unsigned JumpScope = LabelAndGotoScopes[Jump];
3090
3091  // Common case: exactly the same scope, which is fine.
3092  if (JumpScope == JumpTargetScope) return;
3093
3094  // The only valid mismatch jump case happens when the jump is more deeply
3095  // nested inside the jump target.  Do a quick scan to see if the jump is valid
3096  // because valid code is more common than invalid code.
3097  unsigned TestScope = Scopes[JumpScope].ParentScope;
3098  while (TestScope != ~0U) {
3099    // If we found the jump target, then we're jumping out of our current scope,
3100    // which is perfectly fine.
3101    if (TestScope == JumpTargetScope) return;
3102
3103    // Otherwise, scan up the hierarchy.
3104    TestScope = Scopes[TestScope].ParentScope;
3105  }
3106
3107  // If we get here, then we know we have invalid code.  Diagnose the bad jump,
3108  // and then emit a note at each VLA being jumped out of.
3109  S.Diag(Jump->getLocStart(), JumpDiag);
3110
3111  // FIXME: This is N^2 and silly.
3112  while (1) {
3113    // Diagnose that the jump jumps over this declaration.
3114    const GotoScope &TargetScope = Scopes[JumpTargetScope];
3115    S.Diag(TargetScope.Loc, TargetScope.Diag);
3116
3117    // Walk out one level.
3118    JumpTargetScope = Scopes[JumpTargetScope].ParentScope;
3119    assert(JumpTargetScope != ~0U && "Didn't find top-level function scope?");
3120
3121    // Check to see if the jump is valid now.
3122    unsigned TestScope = JumpScope;
3123    while (TestScope != ~0U) {
3124      // If we found the jump target, the the jump became valid.
3125      if (TestScope == JumpTargetScope) return;
3126
3127      // Otherwise, scan up the hierarchy.
3128      TestScope = Scopes[TestScope].ParentScope;
3129    }
3130  }
3131}
3132
3133
3134Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
3135  Decl *dcl = D.getAs<Decl>();
3136  CompoundStmt *Body =cast<CompoundStmt>(static_cast<Stmt*>(BodyArg.release()));
3137  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
3138    FD->setBody(Body);
3139    assert(FD == getCurFunctionDecl() && "Function parsing confused");
3140  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
3141    assert(MD == getCurMethodDecl() && "Method parsing confused");
3142    MD->setBody(Body);
3143  } else {
3144    Body->Destroy(Context);
3145    return DeclPtrTy();
3146  }
3147  PopDeclContext();
3148  // Verify and clean out per-function state.
3149
3150  bool HaveLabels = !LabelMap.empty();
3151  // Check goto/label use.
3152  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3153       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
3154    LabelStmt *L = I->second;
3155
3156    // Verify that we have no forward references left.  If so, there was a goto
3157    // or address of a label taken, but no definition of it.  Label fwd
3158    // definitions are indicated with a null substmt.
3159    if (L->getSubStmt() != 0)
3160      continue;
3161
3162    // Emit error.
3163    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
3164
3165    // At this point, we have gotos that use the bogus label.  Stitch it into
3166    // the function body so that they aren't leaked and that the AST is well
3167    // formed.
3168    if (Body == 0) {
3169      // The whole function wasn't parsed correctly, just delete this.
3170      L->Destroy(Context);
3171      continue;
3172    }
3173
3174    // Otherwise, the body is valid: we want to stitch the label decl into the
3175    // function somewhere so that it is properly owned and so that the goto
3176    // has a valid target.  Do this by creating a new compound stmt with the
3177    // label in it.
3178
3179    // Give the label a sub-statement.
3180    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3181
3182    std::vector<Stmt*> Elements(Body->body_begin(), Body->body_end());
3183    Elements.push_back(L);
3184    Body->setStmts(Context, &Elements[0], Elements.size());
3185  }
3186  LabelMap.clear();
3187
3188  if (!Body) return D;
3189
3190  // If we have labels, verify that goto doesn't jump into scopes illegally.
3191  if (HaveLabels)
3192    JumpScopeChecker(Body, *this);
3193
3194  return D;
3195}
3196
3197/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3198/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
3199NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3200                                          IdentifierInfo &II, Scope *S) {
3201  // Before we produce a declaration for an implicitly defined
3202  // function, see whether there was a locally-scoped declaration of
3203  // this name as a function or variable. If so, use that
3204  // (non-visible) declaration, and complain about it.
3205  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3206    = LocallyScopedExternalDecls.find(&II);
3207  if (Pos != LocallyScopedExternalDecls.end()) {
3208    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
3209    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
3210    return Pos->second;
3211  }
3212
3213  // Extension in C99.  Legal in C90, but warn about it.
3214  if (getLangOptions().C99)
3215    Diag(Loc, diag::ext_implicit_function_decl) << &II;
3216  else
3217    Diag(Loc, diag::warn_implicit_function_decl) << &II;
3218
3219  // FIXME: handle stuff like:
3220  // void foo() { extern float X(); }
3221  // void bar() { X(); }  <-- implicit decl for X in another scope.
3222
3223  // Set a Declarator for the implicit definition: int foo();
3224  const char *Dummy;
3225  DeclSpec DS;
3226  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
3227  Error = Error; // Silence warning.
3228  assert(!Error && "Error setting up implicit decl!");
3229  Declarator D(DS, Declarator::BlockContext);
3230  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(),
3231                                             0, 0, 0, Loc, D),
3232                SourceLocation());
3233  D.SetIdentifier(&II, Loc);
3234
3235  // Insert this function into translation-unit scope.
3236
3237  DeclContext *PrevDC = CurContext;
3238  CurContext = Context.getTranslationUnitDecl();
3239
3240  FunctionDecl *FD =
3241 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D, DeclPtrTy()).getAs<Decl>());
3242  FD->setImplicit();
3243
3244  CurContext = PrevDC;
3245
3246  AddKnownFunctionAttributes(FD);
3247
3248  return FD;
3249}
3250
3251/// \brief Adds any function attributes that we know a priori based on
3252/// the declaration of this function.
3253///
3254/// These attributes can apply both to implicitly-declared builtins
3255/// (like __builtin___printf_chk) or to library-declared functions
3256/// like NSLog or printf.
3257void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3258  if (FD->isInvalidDecl())
3259    return;
3260
3261  // If this is a built-in function, map its builtin attributes to
3262  // actual attributes.
3263  if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3264    // Handle printf-formatting attributes.
3265    unsigned FormatIdx;
3266    bool HasVAListArg;
3267    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3268      if (!FD->getAttr<FormatAttr>())
3269        FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
3270                                               FormatIdx + 2));
3271    }
3272
3273    // Mark const if we don't care about errno and that is the only
3274    // thing preventing the function from being const. This allows
3275    // IRgen to use LLVM intrinsics for such functions.
3276    if (!getLangOptions().MathErrno &&
3277        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3278      if (!FD->getAttr<ConstAttr>())
3279        FD->addAttr(::new (Context) ConstAttr());
3280    }
3281  }
3282
3283  IdentifierInfo *Name = FD->getIdentifier();
3284  if (!Name)
3285    return;
3286  if ((!getLangOptions().CPlusPlus &&
3287       FD->getDeclContext()->isTranslationUnit()) ||
3288      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3289       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3290       LinkageSpecDecl::lang_c)) {
3291    // Okay: this could be a libc/libm/Objective-C function we know
3292    // about.
3293  } else
3294    return;
3295
3296  unsigned KnownID;
3297  for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
3298    if (KnownFunctionIDs[KnownID] == Name)
3299      break;
3300
3301  switch (KnownID) {
3302  case id_NSLog:
3303  case id_NSLogv:
3304    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3305      // FIXME: We known better than our headers.
3306      const_cast<FormatAttr *>(Format)->setType("printf");
3307    } else
3308      FD->addAttr(::new (Context) FormatAttr("printf", 1, 2));
3309    break;
3310
3311  case id_asprintf:
3312  case id_vasprintf:
3313    if (!FD->getAttr<FormatAttr>())
3314      FD->addAttr(::new (Context) FormatAttr("printf", 2, 3));
3315    break;
3316
3317  default:
3318    // Unknown function or known function without any attributes to
3319    // add. Do nothing.
3320    break;
3321  }
3322}
3323
3324TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) {
3325  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
3326  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3327
3328  // Scope manipulation handled by caller.
3329  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3330                                           D.getIdentifierLoc(),
3331                                           D.getIdentifier(),
3332                                           T);
3333
3334  if (TagType *TT = dyn_cast<TagType>(T)) {
3335    TagDecl *TD = TT->getDecl();
3336
3337    // If the TagDecl that the TypedefDecl points to is an anonymous decl
3338    // keep track of the TypedefDecl.
3339    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
3340      TD->setTypedefForAnonDecl(NewTD);
3341  }
3342
3343  if (D.getInvalidType())
3344    NewTD->setInvalidDecl();
3345  return NewTD;
3346}
3347
3348/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
3349/// former case, Name will be non-null.  In the later case, Name will be null.
3350/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
3351/// reference/declaration/definition of a tag.
3352Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
3353                               SourceLocation KWLoc, const CXXScopeSpec &SS,
3354                               IdentifierInfo *Name, SourceLocation NameLoc,
3355                               AttributeList *Attr, AccessSpecifier AS) {
3356  // If this is not a definition, it must have a name.
3357  assert((Name != 0 || TK == TK_Definition) &&
3358         "Nameless record must be a definition!");
3359
3360  TagDecl::TagKind Kind;
3361  switch (TagSpec) {
3362  default: assert(0 && "Unknown tag type!");
3363  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3364  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3365  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3366  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
3367  }
3368
3369  DeclContext *SearchDC = CurContext;
3370  DeclContext *DC = CurContext;
3371  NamedDecl *PrevDecl = 0;
3372
3373  bool Invalid = false;
3374
3375  if (Name && SS.isNotEmpty()) {
3376    // We have a nested-name tag ('struct foo::bar').
3377
3378    // Check for invalid 'foo::'.
3379    if (SS.isInvalid()) {
3380      Name = 0;
3381      goto CreateNewDecl;
3382    }
3383
3384    // FIXME: RequireCompleteDeclContext(SS)?
3385    DC = computeDeclContext(SS);
3386    SearchDC = DC;
3387    // Look-up name inside 'foo::'.
3388    PrevDecl = dyn_cast_or_null<TagDecl>(
3389                 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
3390
3391    // A tag 'foo::bar' must already exist.
3392    if (PrevDecl == 0) {
3393      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
3394      Name = 0;
3395      goto CreateNewDecl;
3396    }
3397  } else if (Name) {
3398    // If this is a named struct, check to see if there was a previous forward
3399    // declaration or definition.
3400    // FIXME: We're looking into outer scopes here, even when we
3401    // shouldn't be. Doing so can result in ambiguities that we
3402    // shouldn't be diagnosing.
3403    LookupResult R = LookupName(S, Name, LookupTagName,
3404                                /*RedeclarationOnly=*/(TK != TK_Reference));
3405    if (R.isAmbiguous()) {
3406      DiagnoseAmbiguousLookup(R, Name, NameLoc);
3407      // FIXME: This is not best way to recover from case like:
3408      //
3409      // struct S s;
3410      //
3411      // causes needless "incomplete type" error later.
3412      Name = 0;
3413      PrevDecl = 0;
3414      Invalid = true;
3415    }
3416    else
3417      PrevDecl = R;
3418
3419    if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3420      // FIXME: This makes sure that we ignore the contexts associated
3421      // with C structs, unions, and enums when looking for a matching
3422      // tag declaration or definition. See the similar lookup tweak
3423      // in Sema::LookupName; is there a better way to deal with this?
3424      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3425        SearchDC = SearchDC->getParent();
3426    }
3427  }
3428
3429  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3430    // Maybe we will complain about the shadowed template parameter.
3431    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3432    // Just pretend that we didn't see the previous declaration.
3433    PrevDecl = 0;
3434  }
3435
3436  if (PrevDecl) {
3437    // Check whether the previous declaration is usable.
3438    (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
3439
3440    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
3441      // If this is a use of a previous tag, or if the tag is already declared
3442      // in the same scope (so that the definition/declaration completes or
3443      // rementions the tag), reuse the decl.
3444      if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
3445        // Make sure that this wasn't declared as an enum and now used as a
3446        // struct or something similar.
3447        if (PrevTagDecl->getTagKind() != Kind) {
3448          bool SafeToContinue
3449            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
3450               Kind != TagDecl::TK_enum);
3451          if (SafeToContinue)
3452            Diag(KWLoc, diag::err_use_with_wrong_tag)
3453              << Name
3454              << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
3455                                                  PrevTagDecl->getKindName());
3456          else
3457            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
3458          Diag(PrevDecl->getLocation(), diag::note_previous_use);
3459
3460          if (SafeToContinue)
3461            Kind = PrevTagDecl->getTagKind();
3462          else {
3463            // Recover by making this an anonymous redefinition.
3464            Name = 0;
3465            PrevDecl = 0;
3466            Invalid = true;
3467          }
3468        }
3469
3470        if (!Invalid) {
3471          // If this is a use, just return the declaration we found.
3472
3473          // FIXME: In the future, return a variant or some other clue
3474          // for the consumer of this Decl to know it doesn't own it.
3475          // For our current ASTs this shouldn't be a problem, but will
3476          // need to be changed with DeclGroups.
3477          if (TK == TK_Reference)
3478            return DeclPtrTy::make(PrevDecl);
3479
3480          // Diagnose attempts to redefine a tag.
3481          if (TK == TK_Definition) {
3482            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3483              Diag(NameLoc, diag::err_redefinition) << Name;
3484              Diag(Def->getLocation(), diag::note_previous_definition);
3485              // If this is a redefinition, recover by making this
3486              // struct be anonymous, which will make any later
3487              // references get the previous definition.
3488              Name = 0;
3489              PrevDecl = 0;
3490              Invalid = true;
3491            } else {
3492              // If the type is currently being defined, complain
3493              // about a nested redefinition.
3494              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3495              if (Tag->isBeingDefined()) {
3496                Diag(NameLoc, diag::err_nested_redefinition) << Name;
3497                Diag(PrevTagDecl->getLocation(),
3498                     diag::note_previous_definition);
3499                Name = 0;
3500                PrevDecl = 0;
3501                Invalid = true;
3502              }
3503            }
3504
3505            // Okay, this is definition of a previously declared or referenced
3506            // tag PrevDecl. We're going to create a new Decl for it.
3507          }
3508        }
3509        // If we get here we have (another) forward declaration or we
3510        // have a definition.  Just create a new decl.
3511      } else {
3512        // If we get here, this is a definition of a new tag type in a nested
3513        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3514        // new decl/type.  We set PrevDecl to NULL so that the entities
3515        // have distinct types.
3516        PrevDecl = 0;
3517      }
3518      // If we get here, we're going to create a new Decl. If PrevDecl
3519      // is non-NULL, it's a definition of the tag declared by
3520      // PrevDecl. If it's NULL, we have a new definition.
3521    } else {
3522      // PrevDecl is a namespace, template, or anything else
3523      // that lives in the IDNS_Tag identifier namespace.
3524      if (isDeclInScope(PrevDecl, SearchDC, S)) {
3525        // The tag name clashes with a namespace name, issue an error and
3526        // recover by making this tag be anonymous.
3527        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
3528        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3529        Name = 0;
3530        PrevDecl = 0;
3531        Invalid = true;
3532      } else {
3533        // The existing declaration isn't relevant to us; we're in a
3534        // new scope, so clear out the previous declaration.
3535        PrevDecl = 0;
3536      }
3537    }
3538  } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3539             (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
3540    // C.scope.pdecl]p5:
3541    //   -- for an elaborated-type-specifier of the form
3542    //
3543    //          class-key identifier
3544    //
3545    //      if the elaborated-type-specifier is used in the
3546    //      decl-specifier-seq or parameter-declaration-clause of a
3547    //      function defined in namespace scope, the identifier is
3548    //      declared as a class-name in the namespace that contains
3549    //      the declaration; otherwise, except as a friend
3550    //      declaration, the identifier is declared in the smallest
3551    //      non-class, non-function-prototype scope that contains the
3552    //      declaration.
3553    //
3554    // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3555    // C structs and unions.
3556    //
3557    // GNU C also supports this behavior as part of its incomplete
3558    // enum types extension, while GNU C++ does not.
3559    //
3560    // Find the context where we'll be declaring the tag.
3561    // FIXME: We would like to maintain the current DeclContext as the
3562    // lexical context,
3563    while (SearchDC->isRecord())
3564      SearchDC = SearchDC->getParent();
3565
3566    // Find the scope where we'll be declaring the tag.
3567    while (S->isClassScope() ||
3568           (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
3569           ((S->getFlags() & Scope::DeclScope) == 0) ||
3570           (S->getEntity() &&
3571            ((DeclContext *)S->getEntity())->isTransparentContext()))
3572      S = S->getParent();
3573  }
3574
3575CreateNewDecl:
3576
3577  // If there is an identifier, use the location of the identifier as the
3578  // location of the decl, otherwise use the location of the struct/union
3579  // keyword.
3580  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3581
3582  // Otherwise, create a new declaration. If there is a previous
3583  // declaration of the same entity, the two will be linked via
3584  // PrevDecl.
3585  TagDecl *New;
3586
3587  if (Kind == TagDecl::TK_enum) {
3588    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3589    // enum X { A, B, C } D;    D should chain to X.
3590    New = EnumDecl::Create(Context, SearchDC, Loc, Name,
3591                           cast_or_null<EnumDecl>(PrevDecl));
3592    // If this is an undefined enum, warn.
3593    if (TK != TK_Definition && !Invalid)  {
3594      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
3595                                              : diag::ext_forward_ref_enum;
3596      Diag(Loc, DK);
3597    }
3598  } else {
3599    // struct/union/class
3600
3601    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3602    // struct X { int A; } D;    D should chain to X.
3603    if (getLangOptions().CPlusPlus)
3604      // FIXME: Look for a way to use RecordDecl for simple structs.
3605      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3606                                  cast_or_null<CXXRecordDecl>(PrevDecl));
3607    else
3608      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
3609                               cast_or_null<RecordDecl>(PrevDecl));
3610  }
3611
3612  if (Kind != TagDecl::TK_enum) {
3613    // Handle #pragma pack: if the #pragma pack stack has non-default
3614    // alignment, make up a packed attribute for this decl. These
3615    // attributes are checked when the ASTContext lays out the
3616    // structure.
3617    //
3618    // It is important for implementing the correct semantics that this
3619    // happen here (in act on tag decl). The #pragma pack stack is
3620    // maintained as a result of parser callbacks which can occur at
3621    // many points during the parsing of a struct declaration (because
3622    // the #pragma tokens are effectively skipped over during the
3623    // parsing of the struct).
3624    if (unsigned Alignment = getPragmaPackAlignment())
3625      New->addAttr(::new (Context) PackedAttr(Alignment * 8));
3626  }
3627
3628  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3629    // C++ [dcl.typedef]p3:
3630    //   [...] Similarly, in a given scope, a class or enumeration
3631    //   shall not be declared with the same name as a typedef-name
3632    //   that is declared in that scope and refers to a type other
3633    //   than the class or enumeration itself.
3634    LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
3635    TypedefDecl *PrevTypedef = 0;
3636    if (Lookup.getKind() == LookupResult::Found)
3637      PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3638
3639    if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3640        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3641          Context.getCanonicalType(Context.getTypeDeclType(New))) {
3642      Diag(Loc, diag::err_tag_definition_of_typedef)
3643        << Context.getTypeDeclType(New)
3644        << PrevTypedef->getUnderlyingType();
3645      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3646      Invalid = true;
3647    }
3648  }
3649
3650  if (Invalid)
3651    New->setInvalidDecl();
3652
3653  if (Attr)
3654    ProcessDeclAttributeList(New, Attr);
3655
3656  // If we're declaring or defining a tag in function prototype scope
3657  // in C, note that this type can only be used within the function.
3658  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3659    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3660
3661  // Set the lexical context. If the tag has a C++ scope specifier, the
3662  // lexical context will be different from the semantic context.
3663  New->setLexicalDeclContext(CurContext);
3664
3665  // Set the access specifier.
3666  SetMemberAccessSpecifier(New, PrevDecl, AS);
3667
3668  if (TK == TK_Definition)
3669    New->startDefinition();
3670
3671  // If this has an identifier, add it to the scope stack.
3672  if (Name) {
3673    S = getNonFieldDeclScope(S);
3674    PushOnScopeChains(New, S);
3675  } else {
3676    CurContext->addDecl(Context, New);
3677  }
3678
3679  return DeclPtrTy::make(New);
3680}
3681
3682void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
3683  AdjustDeclIfTemplate(TagD);
3684  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3685
3686  // Enter the tag context.
3687  PushDeclContext(S, Tag);
3688
3689  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3690    FieldCollector->StartClass();
3691
3692    if (Record->getIdentifier()) {
3693      // C++ [class]p2:
3694      //   [...] The class-name is also inserted into the scope of the
3695      //   class itself; this is known as the injected-class-name. For
3696      //   purposes of access checking, the injected-class-name is treated
3697      //   as if it were a public member name.
3698      CXXRecordDecl *InjectedClassName
3699        = CXXRecordDecl::Create(Context, Record->getTagKind(),
3700                                CurContext, Record->getLocation(),
3701                                Record->getIdentifier(), Record);
3702      InjectedClassName->setImplicit();
3703      InjectedClassName->setAccess(AS_public);
3704      if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
3705        InjectedClassName->setDescribedClassTemplate(Template);
3706      PushOnScopeChains(InjectedClassName, S);
3707      assert(InjectedClassName->isInjectedClassName() &&
3708             "Broken injected-class-name");
3709    }
3710  }
3711}
3712
3713void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD) {
3714  AdjustDeclIfTemplate(TagD);
3715  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3716
3717  if (isa<CXXRecordDecl>(Tag))
3718    FieldCollector->FinishClass();
3719
3720  // Exit this scope of this tag's definition.
3721  PopDeclContext();
3722
3723  // Notify the consumer that we've defined a tag.
3724  Consumer.HandleTagDeclDefinition(Tag);
3725}
3726
3727bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
3728                          QualType FieldTy, const Expr *BitWidth) {
3729  // C99 6.7.2.1p4 - verify the field type.
3730  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3731  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
3732    // Handle incomplete types with specific error.
3733    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
3734      return true;
3735    return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
3736      << FieldName << FieldTy << BitWidth->getSourceRange();
3737  }
3738
3739  // If the bit-width is type- or value-dependent, don't try to check
3740  // it now.
3741  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
3742    return false;
3743
3744  llvm::APSInt Value;
3745  if (VerifyIntegerConstantExpression(BitWidth, &Value))
3746    return true;
3747
3748  // Zero-width bitfield is ok for anonymous field.
3749  if (Value == 0 && FieldName)
3750    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3751
3752  if (Value.isSigned() && Value.isNegative())
3753    return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
3754             << FieldName << Value.toString(10);
3755
3756  if (!FieldTy->isDependentType()) {
3757    uint64_t TypeSize = Context.getTypeSize(FieldTy);
3758    // FIXME: We won't need the 0 size once we check that the field type is valid.
3759    if (TypeSize && Value.getZExtValue() > TypeSize)
3760      return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3761        << FieldName << (unsigned)TypeSize;
3762  }
3763
3764  return false;
3765}
3766
3767/// ActOnField - Each field of a struct/union/class is passed into this in order
3768/// to create a FieldDecl object for it.
3769Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
3770                                 SourceLocation DeclStart,
3771                                 Declarator &D, ExprTy *BitfieldWidth) {
3772  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
3773                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
3774                               AS_public);
3775  return DeclPtrTy::make(Res);
3776}
3777
3778/// HandleField - Analyze a field of a C struct or a C++ data member.
3779///
3780FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
3781                             SourceLocation DeclStart,
3782                             Declarator &D, Expr *BitWidth,
3783                             AccessSpecifier AS) {
3784  IdentifierInfo *II = D.getIdentifier();
3785  SourceLocation Loc = DeclStart;
3786  if (II) Loc = D.getIdentifierLoc();
3787
3788  QualType T = GetTypeForDeclarator(D, S);
3789  if (getLangOptions().CPlusPlus)
3790    CheckExtraCXXDefaultArguments(D);
3791
3792  DiagnoseFunctionSpecifiers(D);
3793
3794  NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3795  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
3796    PrevDecl = 0;
3797
3798  FieldDecl *NewFD
3799    = CheckFieldDecl(II, T, Record, Loc,
3800               D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable,
3801                     BitWidth, AS, PrevDecl, &D);
3802  if (NewFD->isInvalidDecl() && PrevDecl) {
3803    // Don't introduce NewFD into scope; there's already something
3804    // with the same name in the same scope.
3805  } else if (II) {
3806    PushOnScopeChains(NewFD, S);
3807  } else
3808    Record->addDecl(Context, NewFD);
3809
3810  return NewFD;
3811}
3812
3813/// \brief Build a new FieldDecl and check its well-formedness.
3814///
3815/// This routine builds a new FieldDecl given the fields name, type,
3816/// record, etc. \p PrevDecl should refer to any previous declaration
3817/// with the same name and in the same scope as the field to be
3818/// created.
3819///
3820/// \returns a new FieldDecl.
3821///
3822/// \todo The Declarator argument is a hack. It will be removed once
3823FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
3824                                RecordDecl *Record, SourceLocation Loc,
3825                                bool Mutable, Expr *BitWidth,
3826                                AccessSpecifier AS, NamedDecl *PrevDecl,
3827                                Declarator *D) {
3828  IdentifierInfo *II = Name.getAsIdentifierInfo();
3829  bool InvalidDecl = false;
3830
3831  // If we receive a broken type, recover by assuming 'int' and
3832  // marking this declaration as invalid.
3833  if (T.isNull()) {
3834    InvalidDecl = true;
3835    T = Context.IntTy;
3836  }
3837
3838  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3839  // than a variably modified type.
3840  if (T->isVariablyModifiedType()) {
3841    bool SizeIsNegative;
3842    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
3843                                                           SizeIsNegative);
3844    if (!FixedTy.isNull()) {
3845      Diag(Loc, diag::warn_illegal_constant_array_size);
3846      T = FixedTy;
3847    } else {
3848      if (SizeIsNegative)
3849        Diag(Loc, diag::err_typecheck_negative_array_size);
3850      else
3851        Diag(Loc, diag::err_typecheck_field_variable_size);
3852      T = Context.IntTy;
3853      InvalidDecl = true;
3854    }
3855  }
3856
3857  // Fields can not have abstract class types
3858  if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl,
3859                             AbstractFieldType))
3860    InvalidDecl = true;
3861
3862  // If this is declared as a bit-field, check the bit-field.
3863  if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) {
3864    InvalidDecl = true;
3865    DeleteExpr(BitWidth);
3866    BitWidth = 0;
3867  }
3868
3869  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth,
3870                                       Mutable);
3871
3872  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
3873    Diag(Loc, diag::err_duplicate_member) << II;
3874    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3875    NewFD->setInvalidDecl();
3876    Record->setInvalidDecl();
3877  }
3878
3879  if (getLangOptions().CPlusPlus && !T->isPODType())
3880    cast<CXXRecordDecl>(Record)->setPOD(false);
3881
3882  // FIXME: We need to pass in the attributes given an AST
3883  // representation, not a parser representation.
3884  if (D)
3885    ProcessDeclAttributes(NewFD, *D);
3886
3887  if (T.isObjCGCWeak())
3888    Diag(Loc, diag::warn_attribute_weak_on_field);
3889
3890  if (InvalidDecl)
3891    NewFD->setInvalidDecl();
3892
3893  NewFD->setAccess(AS);
3894
3895  // C++ [dcl.init.aggr]p1:
3896  //   An aggregate is an array or a class (clause 9) with [...] no
3897  //   private or protected non-static data members (clause 11).
3898  // A POD must be an aggregate.
3899  if (getLangOptions().CPlusPlus &&
3900      (AS == AS_private || AS == AS_protected)) {
3901    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
3902    CXXRecord->setAggregate(false);
3903    CXXRecord->setPOD(false);
3904  }
3905
3906  return NewFD;
3907}
3908
3909/// TranslateIvarVisibility - Translate visibility from a token ID to an
3910///  AST enum value.
3911static ObjCIvarDecl::AccessControl
3912TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
3913  switch (ivarVisibility) {
3914  default: assert(0 && "Unknown visitibility kind");
3915  case tok::objc_private: return ObjCIvarDecl::Private;
3916  case tok::objc_public: return ObjCIvarDecl::Public;
3917  case tok::objc_protected: return ObjCIvarDecl::Protected;
3918  case tok::objc_package: return ObjCIvarDecl::Package;
3919  }
3920}
3921
3922/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3923/// in order to create an IvarDecl object for it.
3924Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
3925                                SourceLocation DeclStart,
3926                                Declarator &D, ExprTy *BitfieldWidth,
3927                                tok::ObjCKeywordKind Visibility) {
3928
3929  IdentifierInfo *II = D.getIdentifier();
3930  Expr *BitWidth = (Expr*)BitfieldWidth;
3931  SourceLocation Loc = DeclStart;
3932  if (II) Loc = D.getIdentifierLoc();
3933
3934  // FIXME: Unnamed fields can be handled in various different ways, for
3935  // example, unnamed unions inject all members into the struct namespace!
3936
3937  QualType T = GetTypeForDeclarator(D, S);
3938  bool InvalidDecl = false;
3939  if (T.isNull()) {
3940    InvalidDecl = true;
3941    T = Context.IntTy;
3942  }
3943
3944  if (BitWidth) {
3945    // 6.7.2.1p3, 6.7.2.1p4
3946    if (VerifyBitField(Loc, II, T, BitWidth)) {
3947      InvalidDecl = true;
3948      DeleteExpr(BitWidth);
3949      BitWidth = 0;
3950    }
3951  } else {
3952    // Not a bitfield.
3953
3954    // validate II.
3955
3956  }
3957
3958  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3959  // than a variably modified type.
3960  if (T->isVariablyModifiedType()) {
3961    Diag(Loc, diag::err_typecheck_ivar_variable_size);
3962    InvalidDecl = true;
3963  }
3964
3965  // Get the visibility (access control) for this ivar.
3966  ObjCIvarDecl::AccessControl ac =
3967    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3968                                        : ObjCIvarDecl::None;
3969
3970  // Construct the decl.
3971  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac,
3972                                             (Expr *)BitfieldWidth);
3973
3974  if (II) {
3975    NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3976    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3977        && !isa<TagDecl>(PrevDecl)) {
3978      Diag(Loc, diag::err_duplicate_member) << II;
3979      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3980      NewID->setInvalidDecl();
3981    }
3982  }
3983
3984  // Process attributes attached to the ivar.
3985  ProcessDeclAttributes(NewID, D);
3986
3987  if (D.getInvalidType() || InvalidDecl)
3988    NewID->setInvalidDecl();
3989
3990  if (II) {
3991    // FIXME: When interfaces are DeclContexts, we'll need to add
3992    // these to the interface.
3993    S->AddDecl(DeclPtrTy::make(NewID));
3994    IdResolver.AddDecl(NewID);
3995  }
3996
3997  return DeclPtrTy::make(NewID);
3998}
3999
4000void Sema::ActOnFields(Scope* S,
4001                       SourceLocation RecLoc, DeclPtrTy RecDecl,
4002                       DeclPtrTy *Fields, unsigned NumFields,
4003                       SourceLocation LBrac, SourceLocation RBrac,
4004                       AttributeList *Attr) {
4005  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
4006  assert(EnclosingDecl && "missing record or interface decl");
4007
4008  // If the decl this is being inserted into is invalid, then it may be a
4009  // redeclaration or some other bogus case.  Don't try to add fields to it.
4010  if (EnclosingDecl->isInvalidDecl()) {
4011    // FIXME: Deallocate fields?
4012    return;
4013  }
4014
4015
4016  // Verify that all the fields are okay.
4017  unsigned NumNamedMembers = 0;
4018  llvm::SmallVector<FieldDecl*, 32> RecFields;
4019
4020  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
4021  for (unsigned i = 0; i != NumFields; ++i) {
4022    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
4023
4024    // Get the type for the field.
4025    Type *FDTy = FD->getType().getTypePtr();
4026
4027    if (!FD->isAnonymousStructOrUnion()) {
4028      // Remember all fields written by the user.
4029      RecFields.push_back(FD);
4030    }
4031
4032    // If the field is already invalid for some reason, don't emit more
4033    // diagnostics about it.
4034    if (FD->isInvalidDecl())
4035      continue;
4036
4037    // C99 6.7.2.1p2:
4038    //   A structure or union shall not contain a member with
4039    //   incomplete or function type (hence, a structure shall not
4040    //   contain an instance of itself, but may contain a pointer to
4041    //   an instance of itself), except that the last member of a
4042    //   structure with more than one named member may have incomplete
4043    //   array type; such a structure (and any union containing,
4044    //   possibly recursively, a member that is such a structure)
4045    //   shall not be a member of a structure or an element of an
4046    //   array.
4047    if (FDTy->isFunctionType()) {
4048      // Field declared as a function.
4049      Diag(FD->getLocation(), diag::err_field_declared_as_function)
4050        << FD->getDeclName();
4051      FD->setInvalidDecl();
4052      EnclosingDecl->setInvalidDecl();
4053      continue;
4054    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
4055               Record && Record->isStruct()) {
4056      // Flexible array member.
4057      if (NumNamedMembers < 1) {
4058        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
4059          << FD->getDeclName();
4060        FD->setInvalidDecl();
4061        EnclosingDecl->setInvalidDecl();
4062        continue;
4063      }
4064      // Okay, we have a legal flexible array member at the end of the struct.
4065      if (Record)
4066        Record->setHasFlexibleArrayMember(true);
4067    } else if (!FDTy->isDependentType() &&
4068               RequireCompleteType(FD->getLocation(), FD->getType(),
4069                                   diag::err_field_incomplete)) {
4070      // Incomplete type
4071      FD->setInvalidDecl();
4072      EnclosingDecl->setInvalidDecl();
4073      continue;
4074    } else if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
4075      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
4076        // If this is a member of a union, then entire union becomes "flexible".
4077        if (Record && Record->isUnion()) {
4078          Record->setHasFlexibleArrayMember(true);
4079        } else {
4080          // If this is a struct/class and this is not the last element, reject
4081          // it.  Note that GCC supports variable sized arrays in the middle of
4082          // structures.
4083          if (i != NumFields-1)
4084            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
4085              << FD->getDeclName();
4086          else {
4087            // We support flexible arrays at the end of structs in
4088            // other structs as an extension.
4089            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
4090              << FD->getDeclName();
4091            if (Record)
4092              Record->setHasFlexibleArrayMember(true);
4093          }
4094        }
4095      }
4096    } else if (FDTy->isObjCInterfaceType()) {
4097      /// A field cannot be an Objective-c object
4098      Diag(FD->getLocation(), diag::err_statically_allocated_object);
4099      FD->setInvalidDecl();
4100      EnclosingDecl->setInvalidDecl();
4101      continue;
4102    }
4103    // Keep track of the number of named members.
4104    if (FD->getIdentifier())
4105      ++NumNamedMembers;
4106  }
4107
4108  // Okay, we successfully defined 'Record'.
4109  if (Record) {
4110    Record->completeDefinition(Context);
4111  } else {
4112    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
4113    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
4114      ID->setIVarList(ClsFields, RecFields.size(), Context);
4115      ID->setLocEnd(RBrac);
4116
4117      // Must enforce the rule that ivars in the base classes may not be
4118      // duplicates.
4119      if (ID->getSuperClass()) {
4120        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
4121             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
4122          ObjCIvarDecl* Ivar = (*IVI);
4123          IdentifierInfo *II = Ivar->getIdentifier();
4124          ObjCIvarDecl* prevIvar =
4125            ID->getSuperClass()->lookupInstanceVariable(Context, II);
4126          if (prevIvar) {
4127            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
4128            Diag(prevIvar->getLocation(), diag::note_previous_declaration);
4129          }
4130        }
4131      }
4132    } else if (ObjCImplementationDecl *IMPDecl =
4133                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
4134      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
4135      IMPDecl->setIVarList(ClsFields, RecFields.size(), Context);
4136      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
4137    }
4138  }
4139
4140  if (Attr)
4141    ProcessDeclAttributeList(Record, Attr);
4142}
4143
4144EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
4145                                          EnumConstantDecl *LastEnumConst,
4146                                          SourceLocation IdLoc,
4147                                          IdentifierInfo *Id,
4148                                          ExprArg val) {
4149  Expr *Val = (Expr *)val.get();
4150
4151  llvm::APSInt EnumVal(32);
4152  QualType EltTy;
4153  if (Val && !Val->isTypeDependent()) {
4154    // Make sure to promote the operand type to int.
4155    UsualUnaryConversions(Val);
4156    if (Val != val.get()) {
4157      val.release();
4158      val = Val;
4159    }
4160
4161    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
4162    SourceLocation ExpLoc;
4163    if (!Val->isValueDependent() &&
4164        VerifyIntegerConstantExpression(Val, &EnumVal)) {
4165      Val = 0;
4166    } else {
4167      EltTy = Val->getType();
4168    }
4169  }
4170
4171  if (!Val) {
4172    if (LastEnumConst) {
4173      // Assign the last value + 1.
4174      EnumVal = LastEnumConst->getInitVal();
4175      ++EnumVal;
4176
4177      // Check for overflow on increment.
4178      if (EnumVal < LastEnumConst->getInitVal())
4179        Diag(IdLoc, diag::warn_enum_value_overflow);
4180
4181      EltTy = LastEnumConst->getType();
4182    } else {
4183      // First value, set to zero.
4184      EltTy = Context.IntTy;
4185      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
4186    }
4187  }
4188
4189  val.release();
4190  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
4191                                  Val, EnumVal);
4192}
4193
4194
4195Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
4196                                        DeclPtrTy lastEnumConst,
4197                                        SourceLocation IdLoc,
4198                                        IdentifierInfo *Id,
4199                                        SourceLocation EqualLoc, ExprTy *val) {
4200  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
4201  EnumConstantDecl *LastEnumConst =
4202    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
4203  Expr *Val = static_cast<Expr*>(val);
4204
4205  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4206  // we find one that is.
4207  S = getNonFieldDeclScope(S);
4208
4209  // Verify that there isn't already something declared with this name in this
4210  // scope.
4211  NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
4212  if (PrevDecl && PrevDecl->isTemplateParameter()) {
4213    // Maybe we will complain about the shadowed template parameter.
4214    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
4215    // Just pretend that we didn't see the previous declaration.
4216    PrevDecl = 0;
4217  }
4218
4219  if (PrevDecl) {
4220    // When in C++, we may get a TagDecl with the same name; in this case the
4221    // enum constant will 'hide' the tag.
4222    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
4223           "Received TagDecl when not in C++!");
4224    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
4225      if (isa<EnumConstantDecl>(PrevDecl))
4226        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
4227      else
4228        Diag(IdLoc, diag::err_redefinition) << Id;
4229      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4230      if (Val) Val->Destroy(Context);
4231      return DeclPtrTy();
4232    }
4233  }
4234
4235  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
4236                                            IdLoc, Id, Owned(Val));
4237
4238  // Register this decl in the current scope stack.
4239  if (New)
4240    PushOnScopeChains(New, S);
4241
4242  return DeclPtrTy::make(New);
4243}
4244
4245// FIXME: For consistency with ActOnFields(), we should have the parser
4246// pass in the source location for the left/right braces.
4247void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclPtrTy EnumDeclX,
4248                         DeclPtrTy *Elements, unsigned NumElements) {
4249  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
4250  QualType EnumType = Context.getTypeDeclType(Enum);
4251
4252  // TODO: If the result value doesn't fit in an int, it must be a long or long
4253  // long value.  ISO C does not support this, but GCC does as an extension,
4254  // emit a warning.
4255  unsigned IntWidth = Context.Target.getIntWidth();
4256
4257  // Verify that all the values are okay, compute the size of the values, and
4258  // reverse the list.
4259  unsigned NumNegativeBits = 0;
4260  unsigned NumPositiveBits = 0;
4261
4262  // Keep track of whether all elements have type int.
4263  bool AllElementsInt = true;
4264
4265  for (unsigned i = 0; i != NumElements; ++i) {
4266    EnumConstantDecl *ECD =
4267      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
4268    if (!ECD) continue;  // Already issued a diagnostic.
4269
4270    // If the enum value doesn't fit in an int, emit an extension warning.
4271    const llvm::APSInt &InitVal = ECD->getInitVal();
4272    assert(InitVal.getBitWidth() >= IntWidth &&
4273           "Should have promoted value to int");
4274    if (InitVal.getBitWidth() > IntWidth) {
4275      llvm::APSInt V(InitVal);
4276      V.trunc(IntWidth);
4277      V.extend(InitVal.getBitWidth());
4278      if (V != InitVal)
4279        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
4280          << InitVal.toString(10);
4281    }
4282
4283    // Keep track of the size of positive and negative values.
4284    if (InitVal.isUnsigned() || InitVal.isNonNegative())
4285      NumPositiveBits = std::max(NumPositiveBits,
4286                                 (unsigned)InitVal.getActiveBits());
4287    else
4288      NumNegativeBits = std::max(NumNegativeBits,
4289                                 (unsigned)InitVal.getMinSignedBits());
4290
4291    // Keep track of whether every enum element has type int (very commmon).
4292    if (AllElementsInt)
4293      AllElementsInt = ECD->getType() == Context.IntTy;
4294  }
4295
4296  // Figure out the type that should be used for this enum.
4297  // FIXME: Support attribute(packed) on enums and -fshort-enums.
4298  QualType BestType;
4299  unsigned BestWidth;
4300
4301  if (NumNegativeBits) {
4302    // If there is a negative value, figure out the smallest integer type (of
4303    // int/long/longlong) that fits.
4304    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
4305      BestType = Context.IntTy;
4306      BestWidth = IntWidth;
4307    } else {
4308      BestWidth = Context.Target.getLongWidth();
4309
4310      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
4311        BestType = Context.LongTy;
4312      else {
4313        BestWidth = Context.Target.getLongLongWidth();
4314
4315        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
4316          Diag(Enum->getLocation(), diag::warn_enum_too_large);
4317        BestType = Context.LongLongTy;
4318      }
4319    }
4320  } else {
4321    // If there is no negative value, figure out which of uint, ulong, ulonglong
4322    // fits.
4323    if (NumPositiveBits <= IntWidth) {
4324      BestType = Context.UnsignedIntTy;
4325      BestWidth = IntWidth;
4326    } else if (NumPositiveBits <=
4327               (BestWidth = Context.Target.getLongWidth())) {
4328      BestType = Context.UnsignedLongTy;
4329    } else {
4330      BestWidth = Context.Target.getLongLongWidth();
4331      assert(NumPositiveBits <= BestWidth &&
4332             "How could an initializer get larger than ULL?");
4333      BestType = Context.UnsignedLongLongTy;
4334    }
4335  }
4336
4337  // Loop over all of the enumerator constants, changing their types to match
4338  // the type of the enum if needed.
4339  for (unsigned i = 0; i != NumElements; ++i) {
4340    EnumConstantDecl *ECD =
4341      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
4342    if (!ECD) continue;  // Already issued a diagnostic.
4343
4344    // Standard C says the enumerators have int type, but we allow, as an
4345    // extension, the enumerators to be larger than int size.  If each
4346    // enumerator value fits in an int, type it as an int, otherwise type it the
4347    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
4348    // that X has type 'int', not 'unsigned'.
4349    if (ECD->getType() == Context.IntTy) {
4350      // Make sure the init value is signed.
4351      llvm::APSInt IV = ECD->getInitVal();
4352      IV.setIsSigned(true);
4353      ECD->setInitVal(IV);
4354
4355      if (getLangOptions().CPlusPlus)
4356        // C++ [dcl.enum]p4: Following the closing brace of an
4357        // enum-specifier, each enumerator has the type of its
4358        // enumeration.
4359        ECD->setType(EnumType);
4360      continue;  // Already int type.
4361    }
4362
4363    // Determine whether the value fits into an int.
4364    llvm::APSInt InitVal = ECD->getInitVal();
4365    bool FitsInInt;
4366    if (InitVal.isUnsigned() || !InitVal.isNegative())
4367      FitsInInt = InitVal.getActiveBits() < IntWidth;
4368    else
4369      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
4370
4371    // If it fits into an integer type, force it.  Otherwise force it to match
4372    // the enum decl type.
4373    QualType NewTy;
4374    unsigned NewWidth;
4375    bool NewSign;
4376    if (FitsInInt) {
4377      NewTy = Context.IntTy;
4378      NewWidth = IntWidth;
4379      NewSign = true;
4380    } else if (ECD->getType() == BestType) {
4381      // Already the right type!
4382      if (getLangOptions().CPlusPlus)
4383        // C++ [dcl.enum]p4: Following the closing brace of an
4384        // enum-specifier, each enumerator has the type of its
4385        // enumeration.
4386        ECD->setType(EnumType);
4387      continue;
4388    } else {
4389      NewTy = BestType;
4390      NewWidth = BestWidth;
4391      NewSign = BestType->isSignedIntegerType();
4392    }
4393
4394    // Adjust the APSInt value.
4395    InitVal.extOrTrunc(NewWidth);
4396    InitVal.setIsSigned(NewSign);
4397    ECD->setInitVal(InitVal);
4398
4399    // Adjust the Expr initializer and type.
4400    if (ECD->getInitExpr())
4401      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
4402                                                      /*isLvalue=*/false));
4403    if (getLangOptions().CPlusPlus)
4404      // C++ [dcl.enum]p4: Following the closing brace of an
4405      // enum-specifier, each enumerator has the type of its
4406      // enumeration.
4407      ECD->setType(EnumType);
4408    else
4409      ECD->setType(NewTy);
4410  }
4411
4412  Enum->completeDefinition(Context, BestType);
4413}
4414
4415Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
4416                                            ExprArg expr) {
4417  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
4418
4419  return DeclPtrTy::make(FileScopeAsmDecl::Create(Context, CurContext,
4420                                                  Loc, AsmString));
4421}
4422
4423