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