SemaDecl.cpp revision 72de6676bd30f9081ee4166bbe07b4c270258ce6
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/ExprCXX.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/STLExtras.h"
29#include <algorithm>
30#include <functional>
31
32using namespace clang;
33
34Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
35                               const CXXScopeSpec *SS) {
36  DeclContext *DC = 0;
37  if (SS) {
38    if (SS->isInvalid())
39      return 0;
40    DC = static_cast<DeclContext*>(SS->getScopeRep());
41  }
42  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
43
44  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45                 isa<ObjCInterfaceDecl>(IIDecl) ||
46                 isa<TagDecl>(IIDecl) ||
47		 isa<TemplateTypeParmDecl>(IIDecl)))
48    return IIDecl;
49  return 0;
50}
51
52DeclContext *Sema::getContainingDC(DeclContext *DC) {
53  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
54    // A C++ out-of-line method will return to the file declaration context.
55    if (MD->isOutOfLineDefinition())
56      return MD->getLexicalDeclContext();
57
58    // A C++ inline method is parsed *after* the topmost class it was declared in
59    // is fully parsed (it's "complete").
60    // The parsing of a C++ inline method happens at the declaration context of
61    // the topmost (non-nested) class it is lexically declared in.
62    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63    DC = MD->getParent();
64    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
65      DC = RD;
66
67    // Return the declaration context of the topmost class the inline method is
68    // declared in.
69    return DC;
70  }
71
72  if (isa<ObjCMethodDecl>(DC))
73    return Context.getTranslationUnitDecl();
74
75  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76    return SD->getLexicalDeclContext();
77
78  return DC->getLexicalParent();
79}
80
81void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
82  assert(getContainingDC(DC) == CurContext &&
83      "The next DeclContext should be lexically contained in the current one.");
84  CurContext = DC;
85  S->setEntity(DC);
86}
87
88void Sema::PopDeclContext() {
89  assert(CurContext && "DeclContext imbalance!");
90
91  CurContext = getContainingDC(CurContext);
92}
93
94/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
96  // Move up the scope chain until we find the nearest enclosing
97  // non-transparent context. The declaration will be introduced into this
98  // scope.
99  while (S->getEntity() &&
100         ((DeclContext *)S->getEntity())->isTransparentContext())
101    S = S->getParent();
102
103  S->AddDecl(D);
104
105  // Add scoped declarations into their context, so that they can be
106  // found later. Declarations without a context won't be inserted
107  // into any context.
108  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
109    CurContext->addDecl(Context, SD);
110
111  // C++ [basic.scope]p4:
112  //   -- exactly one declaration shall declare a class name or
113  //   enumeration name that is not a typedef name and the other
114  //   declarations shall all refer to the same object or
115  //   enumerator, or all refer to functions and function templates;
116  //   in this case the class name or enumeration name is hidden.
117  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118    // We are pushing the name of a tag (enum or class).
119    if (CurContext->getLookupContext()
120          == TD->getDeclContext()->getLookupContext()) {
121      // We're pushing the tag into the current context, which might
122      // require some reshuffling in the identifier resolver.
123      IdentifierResolver::iterator
124        I = IdResolver.begin(TD->getDeclName(), CurContext,
125                             false/*LookInParentCtx*/),
126        IEnd = IdResolver.end();
127      if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128        NamedDecl *PrevDecl = *I;
129        for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130             PrevDecl = *I, ++I) {
131          if (TD->declarationReplaces(*I)) {
132            // This is a redeclaration. Remove it from the chain and
133            // break out, so that we'll add in the shadowed
134            // declaration.
135            S->RemoveDecl(*I);
136            if (PrevDecl == *I) {
137              IdResolver.RemoveDecl(*I);
138              IdResolver.AddDecl(TD);
139              return;
140            } else {
141              IdResolver.RemoveDecl(*I);
142              break;
143            }
144          }
145        }
146
147        // There is already a declaration with the same name in the same
148        // scope, which is not a tag declaration. It must be found
149        // before we find the new declaration, so insert the new
150        // declaration at the end of the chain.
151        IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153        return;
154      }
155    }
156  } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
157    // We are pushing the name of a function, which might be an
158    // overloaded name.
159    FunctionDecl *FD = cast<FunctionDecl>(D);
160    DeclContext *DC = FD->getDeclContext()->getLookupContext();
161    IdentifierResolver::iterator Redecl
162      = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
163                                      false/*LookInParentCtx*/),
164                     IdResolver.end(),
165                     std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166                                  FD));
167    if (Redecl != IdResolver.end()) {
168      // There is already a declaration of a function on our
169      // IdResolver chain. Replace it with this declaration.
170      S->RemoveDecl(*Redecl);
171      IdResolver.RemoveDecl(*Redecl);
172    }
173  }
174
175  IdResolver.AddDecl(D);
176}
177
178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
179  if (S->decl_empty()) return;
180  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181	 "Scope shouldn't contain decls!");
182
183  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184       I != E; ++I) {
185    Decl *TmpD = static_cast<Decl*>(*I);
186    assert(TmpD && "This decl didn't get pushed??");
187
188    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189    NamedDecl *D = cast<NamedDecl>(TmpD);
190
191    if (!D->getDeclName()) continue;
192
193    // Remove this name from our lexical scope.
194    IdResolver.RemoveDecl(D);
195  }
196}
197
198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
201  // The third "scope" argument is 0 since we aren't enabling lazy built-in
202  // creation from this context.
203  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
204
205  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
206}
207
208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
219template<typename DeclIterator>
220static Decl *
221MaybeConstructOverloadSet(ASTContext &Context,
222                          DeclIterator I, DeclIterator IEnd) {
223  assert(I != IEnd && "Iterator range cannot be empty");
224  assert(!isa<OverloadedFunctionDecl>(*I) &&
225         "Cannot have an overloaded function");
226
227  if (isa<FunctionDecl>(*I)) {
228    // If we found a function, there might be more functions. If
229    // so, collect them into an overload set.
230    DeclIterator Last = I;
231    OverloadedFunctionDecl *Ovl = 0;
232    for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233      if (!Ovl) {
234        // FIXME: We leak this overload set. Eventually, we want to
235        // stop building the declarations for these overload sets, so
236        // there will be nothing to leak.
237        Ovl = OverloadedFunctionDecl::Create(Context,
238                                         cast<ScopedDecl>(*I)->getDeclContext(),
239                                             (*I)->getDeclName());
240        Ovl->addOverload(cast<FunctionDecl>(*I));
241      }
242      Ovl->addOverload(cast<FunctionDecl>(*Last));
243    }
244
245    // If we had more than one function, we built an overload
246    // set. Return it.
247    if (Ovl)
248      return Ovl;
249  }
250
251  return *I;
252}
253
254/// LookupDecl - Look up the inner-most declaration in the specified
255/// namespace. NamespaceNameOnly - during lookup only namespace names
256/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
257/// 'When looking up a namespace-name in a using-directive or
258/// namespace-alias-definition, only namespace names are considered.'
259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
260                       const DeclContext *LookupCtx,
261                       bool enableLazyBuiltinCreation,
262                       bool LookInParent,
263                       bool NamespaceNameOnly) {
264  if (!Name) return 0;
265  unsigned NS = NSI;
266
267  // In C++, ordinary and member lookup will always find all
268  // kinds of names.
269  if (getLangOptions().CPlusPlus &&
270      (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Member)))
271    NS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Ordinary;
272
273  if (LookupCtx == 0 && !getLangOptions().CPlusPlus) {
274    // Unqualified name lookup in C/Objective-C is purely lexical, so
275    // search in the declarations attached to the name.
276    assert(!LookupCtx && "Can't perform qualified name lookup here");
277    assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
278
279    // For the purposes of unqualified name lookup, structs and unions
280    // don't have scopes at all. For example:
281    //
282    //   struct X {
283    //     struct T { int i; } x;
284    //   };
285    //
286    //   void f() {
287    //     struct T t; // okay: T is defined lexically within X, but
288    //                 // semantically at global scope
289    //   };
290    //
291    // FIXME: Is there a better way to deal with this?
292    DeclContext *SearchCtx = CurContext;
293    while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
294      SearchCtx = SearchCtx->getParent();
295    IdentifierResolver::iterator I
296      = IdResolver.begin(Name, SearchCtx, LookInParent);
297
298    // Scan up the scope chain looking for a decl that matches this
299    // identifier that is in the appropriate namespace.  This search
300    // should not take long, as shadowing of names is uncommon, and
301    // deep shadowing is extremely uncommon.
302    for (; I != IdResolver.end(); ++I)
303      if ((*I)->isInIdentifierNamespace(NS))
304        return *I;
305  } else if (LookupCtx) {
306    // If we're performing qualified name lookup (e.g., lookup into a
307    // struct), find fields as part of ordinary name lookup.
308    if (NS & Decl::IDNS_Ordinary)
309      NS |= Decl::IDNS_Member;
310
311    // Perform qualified name lookup into the LookupCtx.
312    // FIXME: Will need to look into base classes and such.
313    DeclContext::lookup_const_iterator I, E;
314    for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
315      if ((*I)->isInIdentifierNamespace(NS)) {
316        // Ignore non-namespace names if we're only looking for namespaces.
317        if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
318
319        return MaybeConstructOverloadSet(Context, I, E);
320      }
321  } else {
322    // Name lookup for ordinary names and tag names in C++ requires
323    // looking into scopes that aren't strictly lexical, and
324    // therefore we walk through the context as well as walking
325    // through the scopes.
326    IdentifierResolver::iterator
327      I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
328      IEnd = IdResolver.end();
329    for (; S; S = S->getParent()) {
330      // Check whether the IdResolver has anything in this scope.
331      // FIXME: The isDeclScope check could be expensive. Can we do better?
332      for (; I != IEnd && S->isDeclScope(*I); ++I) {
333        if ((*I)->isInIdentifierNamespace(NS)) {
334          // Ignore non-namespace names if we're only looking for namespaces.
335          if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
336            continue;
337
338          // We found something.  Look for anything else in our scope
339          // with this same name and in an acceptable identifier
340          // namespace, so that we can construct an overload set if we
341          // need to.
342          IdentifierResolver::iterator LastI = I;
343          for (++LastI; LastI != IEnd; ++LastI) {
344            if (!(*LastI)->isInIdentifierNamespace(NS) ||
345                !S->isDeclScope(*LastI))
346              break;
347          }
348          return MaybeConstructOverloadSet(Context, I, LastI);
349        }
350      }
351
352      // If there is an entity associated with this scope, it's a
353      // DeclContext. We might need to perform qualified lookup into
354      // it.
355      DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
356      while (Ctx && Ctx->isFunctionOrMethod())
357        Ctx = Ctx->getParent();
358      while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
359        // Look for declarations of this name in this scope.
360        DeclContext::lookup_const_iterator I, E;
361        for (llvm::tie(I, E) = Ctx->lookup(Name); I != E; ++I) {
362          // FIXME: Cache this result in the IdResolver
363          if ((*I)->isInIdentifierNamespace(NS)) {
364            if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
365              continue;
366            return MaybeConstructOverloadSet(Context, I, E);
367          }
368        }
369
370        if (!LookInParent && !Ctx->isTransparentContext())
371          return 0;
372
373        Ctx = Ctx->getParent();
374      }
375    }
376  }
377
378  // If we didn't find a use of this identifier, and if the identifier
379  // corresponds to a compiler builtin, create the decl object for the builtin
380  // now, injecting it into translation unit scope, and return it.
381  if (NS & Decl::IDNS_Ordinary) {
382    IdentifierInfo *II = Name.getAsIdentifierInfo();
383    if (enableLazyBuiltinCreation && II &&
384        (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
385      // If this is a builtin on this (or all) targets, create the decl.
386      if (unsigned BuiltinID = II->getBuiltinID())
387        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
388    }
389    if (getLangOptions().ObjC1 && II) {
390      // @interface and @compatibility_alias introduce typedef-like names.
391      // Unlike typedef's, they can only be introduced at file-scope (and are
392      // therefore not scoped decls). They can, however, be shadowed by
393      // other names in IDNS_Ordinary.
394      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
395      if (IDI != ObjCInterfaceDecls.end())
396        return IDI->second;
397      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
398      if (I != ObjCAliasDecls.end())
399        return I->second->getClassInterface();
400    }
401  }
402  return 0;
403}
404
405void Sema::InitBuiltinVaListType() {
406  if (!Context.getBuiltinVaListType().isNull())
407    return;
408
409  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
410  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
411  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
412  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
413}
414
415/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
416/// lazily create a decl for it.
417ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
418                                      Scope *S) {
419  Builtin::ID BID = (Builtin::ID)bid;
420
421  if (Context.BuiltinInfo.hasVAListUse(BID))
422    InitBuiltinVaListType();
423
424  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
425  FunctionDecl *New = FunctionDecl::Create(Context,
426                                           Context.getTranslationUnitDecl(),
427                                           SourceLocation(), II, R,
428                                           FunctionDecl::Extern, false, 0);
429
430  // Create Decl objects for each parameter, adding them to the
431  // FunctionDecl.
432  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
433    llvm::SmallVector<ParmVarDecl*, 16> Params;
434    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
435      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
436                                           FT->getArgType(i), VarDecl::None, 0,
437                                           0));
438    New->setParams(&Params[0], Params.size());
439  }
440
441
442
443  // TUScope is the translation-unit scope to insert this function into.
444  PushOnScopeChains(New, TUScope);
445  return New;
446}
447
448/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
449/// everything from the standard library is defined.
450NamespaceDecl *Sema::GetStdNamespace() {
451  if (!StdNamespace) {
452    IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
453    DeclContext *Global = Context.getTranslationUnitDecl();
454    Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
455                           0, Global, /*enableLazyBuiltinCreation=*/false);
456    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
457  }
458  return StdNamespace;
459}
460
461/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
462/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
463/// situation, merging decls or emitting diagnostics as appropriate.
464///
465TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
466  // Allow multiple definitions for ObjC built-in typedefs.
467  // FIXME: Verify the underlying types are equivalent!
468  if (getLangOptions().ObjC1) {
469    const IdentifierInfo *TypeID = New->getIdentifier();
470    switch (TypeID->getLength()) {
471    default: break;
472    case 2:
473      if (!TypeID->isStr("id"))
474        break;
475      Context.setObjCIdType(New);
476      return New;
477    case 5:
478      if (!TypeID->isStr("Class"))
479        break;
480      Context.setObjCClassType(New);
481      return New;
482    case 3:
483      if (!TypeID->isStr("SEL"))
484        break;
485      Context.setObjCSelType(New);
486      return New;
487    case 8:
488      if (!TypeID->isStr("Protocol"))
489        break;
490      Context.setObjCProtoType(New->getUnderlyingType());
491      return New;
492    }
493    // Fall through - the typedef name was not a builtin type.
494  }
495  // Verify the old decl was also a typedef.
496  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
497  if (!Old) {
498    Diag(New->getLocation(), diag::err_redefinition_different_kind)
499      << New->getDeclName();
500    Diag(OldD->getLocation(), diag::note_previous_definition);
501    return New;
502  }
503
504  // If the typedef types are not identical, reject them in all languages and
505  // with any extensions enabled.
506  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
507      Context.getCanonicalType(Old->getUnderlyingType()) !=
508      Context.getCanonicalType(New->getUnderlyingType())) {
509    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
510      << New->getUnderlyingType() << Old->getUnderlyingType();
511    Diag(Old->getLocation(), diag::note_previous_definition);
512    return Old;
513  }
514
515  if (getLangOptions().Microsoft) return New;
516
517  // C++ [dcl.typedef]p2:
518  //   In a given non-class scope, a typedef specifier can be used to
519  //   redefine the name of any type declared in that scope to refer
520  //   to the type to which it already refers.
521  if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
522    return New;
523
524  // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
525  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
526  // *either* declaration is in a system header. The code below implements
527  // this adhoc compatibility rule. FIXME: The following code will not
528  // work properly when compiling ".i" files (containing preprocessed output).
529  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
530    SourceManager &SrcMgr = Context.getSourceManager();
531    if (SrcMgr.isInSystemHeader(Old->getLocation()))
532      return New;
533    if (SrcMgr.isInSystemHeader(New->getLocation()))
534      return New;
535  }
536
537  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
538  Diag(Old->getLocation(), diag::note_previous_definition);
539  return New;
540}
541
542/// DeclhasAttr - returns true if decl Declaration already has the target
543/// attribute.
544static bool DeclHasAttr(const Decl *decl, const Attr *target) {
545  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
546    if (attr->getKind() == target->getKind())
547      return true;
548
549  return false;
550}
551
552/// MergeAttributes - append attributes from the Old decl to the New one.
553static void MergeAttributes(Decl *New, Decl *Old) {
554  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
555
556  while (attr) {
557     tmp = attr;
558     attr = attr->getNext();
559
560    if (!DeclHasAttr(New, tmp)) {
561       tmp->setInherited(true);
562       New->addAttr(tmp);
563    } else {
564       tmp->setNext(0);
565       delete(tmp);
566    }
567  }
568
569  Old->invalidateAttrs();
570}
571
572/// MergeFunctionDecl - We just parsed a function 'New' from
573/// declarator D which has the same name and scope as a previous
574/// declaration 'Old'.  Figure out how to resolve this situation,
575/// merging decls or emitting diagnostics as appropriate.
576/// Redeclaration will be set true if this New is a redeclaration OldD.
577///
578/// In C++, New and Old must be declarations that are not
579/// overloaded. Use IsOverload to determine whether New and Old are
580/// overloaded, and to select the Old declaration that New should be
581/// merged with.
582FunctionDecl *
583Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
584  assert(!isa<OverloadedFunctionDecl>(OldD) &&
585         "Cannot merge with an overloaded function declaration");
586
587  Redeclaration = false;
588  // Verify the old decl was also a function.
589  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
590  if (!Old) {
591    Diag(New->getLocation(), diag::err_redefinition_different_kind)
592      << New->getDeclName();
593    Diag(OldD->getLocation(), diag::note_previous_definition);
594    return New;
595  }
596
597  // Determine whether the previous declaration was a definition,
598  // implicit declaration, or a declaration.
599  diag::kind PrevDiag;
600  if (Old->isThisDeclarationADefinition())
601    PrevDiag = diag::note_previous_definition;
602  else if (Old->isImplicit())
603    PrevDiag = diag::note_previous_implicit_declaration;
604  else
605    PrevDiag = diag::note_previous_declaration;
606
607  QualType OldQType = Context.getCanonicalType(Old->getType());
608  QualType NewQType = Context.getCanonicalType(New->getType());
609
610  if (getLangOptions().CPlusPlus) {
611    // (C++98 13.1p2):
612    //   Certain function declarations cannot be overloaded:
613    //     -- Function declarations that differ only in the return type
614    //        cannot be overloaded.
615    QualType OldReturnType
616      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
617    QualType NewReturnType
618      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
619    if (OldReturnType != NewReturnType) {
620      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
621      Diag(Old->getLocation(), PrevDiag);
622      Redeclaration = true;
623      return New;
624    }
625
626    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
627    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
628    if (OldMethod && NewMethod) {
629      //    -- Member function declarations with the same name and the
630      //       same parameter types cannot be overloaded if any of them
631      //       is a static member function declaration.
632      if (OldMethod->isStatic() || NewMethod->isStatic()) {
633        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
634        Diag(Old->getLocation(), PrevDiag);
635        return New;
636      }
637
638      // C++ [class.mem]p1:
639      //   [...] A member shall not be declared twice in the
640      //   member-specification, except that a nested class or member
641      //   class template can be declared and then later defined.
642      if (OldMethod->getLexicalDeclContext() ==
643            NewMethod->getLexicalDeclContext()) {
644        unsigned NewDiag;
645        if (isa<CXXConstructorDecl>(OldMethod))
646          NewDiag = diag::err_constructor_redeclared;
647        else if (isa<CXXDestructorDecl>(NewMethod))
648          NewDiag = diag::err_destructor_redeclared;
649        else if (isa<CXXConversionDecl>(NewMethod))
650          NewDiag = diag::err_conv_function_redeclared;
651        else
652          NewDiag = diag::err_member_redeclared;
653
654        Diag(New->getLocation(), NewDiag);
655        Diag(Old->getLocation(), PrevDiag);
656      }
657    }
658
659    // (C++98 8.3.5p3):
660    //   All declarations for a function shall agree exactly in both the
661    //   return type and the parameter-type-list.
662    if (OldQType == NewQType) {
663      // We have a redeclaration.
664      MergeAttributes(New, Old);
665      Redeclaration = true;
666      return MergeCXXFunctionDecl(New, Old);
667    }
668
669    // Fall through for conflicting redeclarations and redefinitions.
670  }
671
672  // C: Function types need to be compatible, not identical. This handles
673  // duplicate function decls like "void f(int); void f(enum X);" properly.
674  if (!getLangOptions().CPlusPlus &&
675      Context.typesAreCompatible(OldQType, NewQType)) {
676    MergeAttributes(New, Old);
677    Redeclaration = true;
678    return New;
679  }
680
681  // A function that has already been declared has been redeclared or defined
682  // with a different type- show appropriate diagnostic
683
684  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
685  // TODO: This is totally simplistic.  It should handle merging functions
686  // together etc, merging extern int X; int X; ...
687  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
688  Diag(Old->getLocation(), PrevDiag);
689  return New;
690}
691
692/// Predicate for C "tentative" external object definitions (C99 6.9.2).
693static bool isTentativeDefinition(VarDecl *VD) {
694  if (VD->isFileVarDecl())
695    return (!VD->getInit() &&
696            (VD->getStorageClass() == VarDecl::None ||
697             VD->getStorageClass() == VarDecl::Static));
698  return false;
699}
700
701/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
702/// when dealing with C "tentative" external object definitions (C99 6.9.2).
703void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
704  bool VDIsTentative = isTentativeDefinition(VD);
705  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
706
707  // FIXME: I don't think this will actually see all of the
708  // redefinitions. Can't we check this property on-the-fly?
709  for (IdentifierResolver::iterator
710       I = IdResolver.begin(VD->getIdentifier(),
711                            VD->getDeclContext(), false/*LookInParentCtx*/),
712       E = IdResolver.end(); I != E; ++I) {
713    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
714      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
715
716      // Handle the following case:
717      //   int a[10];
718      //   int a[];   - the code below makes sure we set the correct type.
719      //   int a[11]; - this is an error, size isn't 10.
720      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
721          OldDecl->getType()->isConstantArrayType())
722        VD->setType(OldDecl->getType());
723
724      // Check for "tentative" definitions. We can't accomplish this in
725      // MergeVarDecl since the initializer hasn't been attached.
726      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
727        continue;
728
729      // Handle __private_extern__ just like extern.
730      if (OldDecl->getStorageClass() != VarDecl::Extern &&
731          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
732          VD->getStorageClass() != VarDecl::Extern &&
733          VD->getStorageClass() != VarDecl::PrivateExtern) {
734        Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
735        Diag(OldDecl->getLocation(), diag::note_previous_definition);
736      }
737    }
738  }
739}
740
741/// MergeVarDecl - We just parsed a variable 'New' which has the same name
742/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
743/// situation, merging decls or emitting diagnostics as appropriate.
744///
745/// Tentative definition rules (C99 6.9.2p2) are checked by
746/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
747/// definitions here, since the initializer hasn't been attached.
748///
749VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
750  // Verify the old decl was also a variable.
751  VarDecl *Old = dyn_cast<VarDecl>(OldD);
752  if (!Old) {
753    Diag(New->getLocation(), diag::err_redefinition_different_kind)
754      << New->getDeclName();
755    Diag(OldD->getLocation(), diag::note_previous_definition);
756    return New;
757  }
758
759  MergeAttributes(New, Old);
760
761  // Verify the types match.
762  QualType OldCType = Context.getCanonicalType(Old->getType());
763  QualType NewCType = Context.getCanonicalType(New->getType());
764  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
765    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
766    Diag(Old->getLocation(), diag::note_previous_definition);
767    return New;
768  }
769  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
770  if (New->getStorageClass() == VarDecl::Static &&
771      (Old->getStorageClass() == VarDecl::None ||
772       Old->getStorageClass() == VarDecl::Extern)) {
773    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
774    Diag(Old->getLocation(), diag::note_previous_definition);
775    return New;
776  }
777  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
778  if (New->getStorageClass() != VarDecl::Static &&
779      Old->getStorageClass() == VarDecl::Static) {
780    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
781    Diag(Old->getLocation(), diag::note_previous_definition);
782    return New;
783  }
784  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
785  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
786    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
787    Diag(Old->getLocation(), diag::note_previous_definition);
788  }
789  return New;
790}
791
792/// CheckParmsForFunctionDef - Check that the parameters of the given
793/// function are appropriate for the definition of a function. This
794/// takes care of any checks that cannot be performed on the
795/// declaration itself, e.g., that the types of each of the function
796/// parameters are complete.
797bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
798  bool HasInvalidParm = false;
799  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
800    ParmVarDecl *Param = FD->getParamDecl(p);
801
802    // C99 6.7.5.3p4: the parameters in a parameter type list in a
803    // function declarator that is part of a function definition of
804    // that function shall not have incomplete type.
805    if (Param->getType()->isIncompleteType() &&
806        !Param->isInvalidDecl()) {
807      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
808        << Param->getType();
809      Param->setInvalidDecl();
810      HasInvalidParm = true;
811    }
812
813    // C99 6.9.1p5: If the declarator includes a parameter type list, the
814    // declaration of each parameter shall include an identifier.
815    if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
816      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
817  }
818
819  return HasInvalidParm;
820}
821
822/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
823/// no declarator (e.g. "struct foo;") is parsed.
824Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
825  // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
826  if (!DS.isMissingDeclaratorOk()) {
827    // FIXME: This diagnostic is emitted even when various previous
828    // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
829    // DeclSpec has no means of communicating this information, and the
830    // responsible parser functions are quite far apart.
831    Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
832      << DS.getSourceRange();
833    return 0;
834  }
835
836  TagDecl *Tag
837    = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
838  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
839    if (!Record->getDeclName() && Record->isDefinition() &&
840        !Record->isInvalidDecl())
841      return BuildAnonymousStructOrUnion(S, DS, Record);
842  }
843
844  return Tag;
845}
846
847/// InjectAnonymousStructOrUnionMembers - Inject the members of the
848/// anonymous struct or union AnonRecord into the owning context Owner
849/// and scope S. This routine will be invoked just after we realize
850/// that an unnamed union or struct is actually an anonymous union or
851/// struct, e.g.,
852///
853/// @code
854/// union {
855///   int i;
856///   float f;
857/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
858///    // f into the surrounding scope.x
859/// @endcode
860///
861/// This routine is recursive, injecting the names of nested anonymous
862/// structs/unions into the owning context and scope as well.
863bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
864                                               RecordDecl *AnonRecord) {
865  bool Invalid = false;
866  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
867                               FEnd = AnonRecord->field_end();
868       F != FEnd; ++F) {
869    if ((*F)->getDeclName()) {
870      Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
871                                  S, Owner, false, false, false);
872      if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
873        // C++ [class.union]p2:
874        //   The names of the members of an anonymous union shall be
875        //   distinct from the names of any other entity in the
876        //   scope in which the anonymous union is declared.
877        unsigned diagKind
878          = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
879                                 : diag::err_anonymous_struct_member_redecl;
880        Diag((*F)->getLocation(), diagKind)
881          << (*F)->getDeclName();
882        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
883        Invalid = true;
884      } else {
885        // C++ [class.union]p2:
886        //   For the purpose of name lookup, after the anonymous union
887        //   definition, the members of the anonymous union are
888        //   considered to have been defined in the scope in which the
889        //   anonymous union is declared.
890        Owner->insert(Context, *F);
891        S->AddDecl(*F);
892        IdResolver.AddDecl(*F);
893      }
894    } else if (const RecordType *InnerRecordType
895                 = (*F)->getType()->getAsRecordType()) {
896      RecordDecl *InnerRecord = InnerRecordType->getDecl();
897      if (InnerRecord->isAnonymousStructOrUnion())
898        Invalid = Invalid ||
899          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
900    }
901  }
902
903  return Invalid;
904}
905
906/// ActOnAnonymousStructOrUnion - Handle the declaration of an
907/// anonymous structure or union. Anonymous unions are a C++ feature
908/// (C++ [class.union]) and a GNU C extension; anonymous structures
909/// are a GNU C and GNU C++ extension.
910Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
911                                                RecordDecl *Record) {
912  DeclContext *Owner = Record->getDeclContext();
913
914  // Diagnose whether this anonymous struct/union is an extension.
915  if (Record->isUnion() && !getLangOptions().CPlusPlus)
916    Diag(Record->getLocation(), diag::ext_anonymous_union);
917  else if (!Record->isUnion())
918    Diag(Record->getLocation(), diag::ext_anonymous_struct);
919
920  // C and C++ require different kinds of checks for anonymous
921  // structs/unions.
922  bool Invalid = false;
923  if (getLangOptions().CPlusPlus) {
924    const char* PrevSpec = 0;
925    // C++ [class.union]p3:
926    //   Anonymous unions declared in a named namespace or in the
927    //   global namespace shall be declared static.
928    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
929        (isa<TranslationUnitDecl>(Owner) ||
930         (isa<NamespaceDecl>(Owner) &&
931          cast<NamespaceDecl>(Owner)->getDeclName()))) {
932      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
933      Invalid = true;
934
935      // Recover by adding 'static'.
936      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
937    }
938    // C++ [class.union]p3:
939    //   A storage class is not allowed in a declaration of an
940    //   anonymous union in a class scope.
941    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
942             isa<RecordDecl>(Owner)) {
943      Diag(DS.getStorageClassSpecLoc(),
944           diag::err_anonymous_union_with_storage_spec);
945      Invalid = true;
946
947      // Recover by removing the storage specifier.
948      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
949                             PrevSpec);
950    }
951
952    // C++ [class.union]p2:
953    //   The member-specification of an anonymous union shall only
954    //   define non-static data members. [Note: nested types and
955    //   functions cannot be declared within an anonymous union. ]
956    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
957                                 MemEnd = Record->decls_end();
958         Mem != MemEnd; ++Mem) {
959      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
960        // C++ [class.union]p3:
961        //   An anonymous union shall not have private or protected
962        //   members (clause 11).
963        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
964          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
965            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
966          Invalid = true;
967        }
968      } else if ((*Mem)->isImplicit()) {
969        // Any implicit members are fine.
970      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
971        if (!MemRecord->isAnonymousStructOrUnion() &&
972            MemRecord->getDeclName()) {
973          // This is a nested type declaration.
974          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
975            << (int)Record->isUnion();
976          Invalid = true;
977        }
978      } else {
979        // We have something that isn't a non-static data
980        // member. Complain about it.
981        unsigned DK = diag::err_anonymous_record_bad_member;
982        if (isa<TypeDecl>(*Mem))
983          DK = diag::err_anonymous_record_with_type;
984        else if (isa<FunctionDecl>(*Mem))
985          DK = diag::err_anonymous_record_with_function;
986        else if (isa<VarDecl>(*Mem))
987          DK = diag::err_anonymous_record_with_static;
988        Diag((*Mem)->getLocation(), DK)
989            << (int)Record->isUnion();
990          Invalid = true;
991      }
992    }
993  } else {
994    // FIXME: Check GNU C semantics
995  }
996
997  if (!Record->isUnion() && !Owner->isRecord()) {
998    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
999    Invalid = true;
1000  }
1001
1002  // Create a declaration for this anonymous struct/union.
1003  ScopedDecl *Anon = 0;
1004  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1005    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1006                             /*IdentifierInfo=*/0,
1007                             Context.getTypeDeclType(Record),
1008                             /*BitWidth=*/0, /*Mutable=*/false,
1009                             /*PrevDecl=*/0);
1010    Anon->setAccess(AS_public);
1011    if (getLangOptions().CPlusPlus)
1012      FieldCollector->Add(cast<FieldDecl>(Anon));
1013  } else {
1014    VarDecl::StorageClass SC;
1015    switch (DS.getStorageClassSpec()) {
1016    default: assert(0 && "Unknown storage class!");
1017    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1018    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1019    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1020    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1021    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1022    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1023    case DeclSpec::SCS_mutable:
1024      // mutable can only appear on non-static class members, so it's always
1025      // an error here
1026      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1027      Invalid = true;
1028      SC = VarDecl::None;
1029      break;
1030    }
1031
1032    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1033                           /*IdentifierInfo=*/0,
1034                           Context.getTypeDeclType(Record),
1035                           SC, /*FIXME:LastDeclarator=*/0,
1036                           DS.getSourceRange().getBegin());
1037  }
1038  Anon->setImplicit();
1039
1040  // Add the anonymous struct/union object to the current
1041  // context. We'll be referencing this object when we refer to one of
1042  // its members.
1043  Owner->addDecl(Context, Anon);
1044
1045  // Inject the members of the anonymous struct/union into the owning
1046  // context and into the identifier resolver chain for name lookup
1047  // purposes.
1048  Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1049
1050  // Mark this as an anonymous struct/union type. Note that we do not
1051  // do this until after we have already checked and injected the
1052  // members of this anonymous struct/union type, because otherwise
1053  // the members could be injected twice: once by DeclContext when it
1054  // builds its lookup table, and once by
1055  // InjectAnonymousStructOrUnionMembers.
1056  Record->setAnonymousStructOrUnion(true);
1057
1058  if (Invalid)
1059    Anon->setInvalidDecl();
1060
1061  return Anon;
1062}
1063
1064bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
1065  // Get the type before calling CheckSingleAssignmentConstraints(), since
1066  // it can promote the expression.
1067  QualType InitType = Init->getType();
1068
1069  if (getLangOptions().CPlusPlus)
1070    return PerformCopyInitialization(Init, DeclType, "initializing");
1071
1072  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1073  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1074                                  InitType, Init, "initializing");
1075}
1076
1077bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
1078  const ArrayType *AT = Context.getAsArrayType(DeclT);
1079
1080  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
1081    // C99 6.7.8p14. We have an array of character type with unknown size
1082    // being initialized to a string literal.
1083    llvm::APSInt ConstVal(32);
1084    ConstVal = strLiteral->getByteLength() + 1;
1085    // Return a new array type (C99 6.7.8p22).
1086    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
1087                                         ArrayType::Normal, 0);
1088  } else {
1089    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
1090    // C99 6.7.8p14. We have an array of character type with known size.
1091    // FIXME: Avoid truncation for 64-bit length strings.
1092    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
1093      Diag(strLiteral->getSourceRange().getBegin(),
1094           diag::warn_initializer_string_for_char_array_too_long)
1095        << strLiteral->getSourceRange();
1096  }
1097  // Set type from "char *" to "constant array of char".
1098  strLiteral->setType(DeclT);
1099  // For now, we always return false (meaning success).
1100  return false;
1101}
1102
1103StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
1104  const ArrayType *AT = Context.getAsArrayType(DeclType);
1105  if (AT && AT->getElementType()->isCharType()) {
1106    return dyn_cast<StringLiteral>(Init);
1107  }
1108  return 0;
1109}
1110
1111bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1112                                 SourceLocation InitLoc,
1113                                 DeclarationName InitEntity) {
1114  if (DeclType->isDependentType() || Init->isTypeDependent())
1115    return false;
1116
1117  // C++ [dcl.init.ref]p1:
1118  //   A variable declared to be a T&, that is "reference to type T"
1119  //   (8.3.2), shall be initialized by an object, or function, of
1120  //   type T or by an object that can be converted into a T.
1121  if (DeclType->isReferenceType())
1122    return CheckReferenceInit(Init, DeclType);
1123
1124  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1125  // of unknown size ("[]") or an object type that is not a variable array type.
1126  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
1127    return Diag(InitLoc,  diag::err_variable_object_no_init)
1128      << VAT->getSizeExpr()->getSourceRange();
1129
1130  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1131  if (!InitList) {
1132    // FIXME: Handle wide strings
1133    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1134      return CheckStringLiteralInit(strLiteral, DeclType);
1135
1136    // C++ [dcl.init]p14:
1137    //   -- If the destination type is a (possibly cv-qualified) class
1138    //      type:
1139    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1140      QualType DeclTypeC = Context.getCanonicalType(DeclType);
1141      QualType InitTypeC = Context.getCanonicalType(Init->getType());
1142
1143      //   -- If the initialization is direct-initialization, or if it is
1144      //      copy-initialization where the cv-unqualified version of the
1145      //      source type is the same class as, or a derived class of, the
1146      //      class of the destination, constructors are considered.
1147      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1148          IsDerivedFrom(InitTypeC, DeclTypeC)) {
1149        CXXConstructorDecl *Constructor
1150          = PerformInitializationByConstructor(DeclType, &Init, 1,
1151                                               InitLoc, Init->getSourceRange(),
1152                                               InitEntity, IK_Copy);
1153        return Constructor == 0;
1154      }
1155
1156      //   -- Otherwise (i.e., for the remaining copy-initialization
1157      //      cases), user-defined conversion sequences that can
1158      //      convert from the source type to the destination type or
1159      //      (when a conversion function is used) to a derived class
1160      //      thereof are enumerated as described in 13.3.1.4, and the
1161      //      best one is chosen through overload resolution
1162      //      (13.3). If the conversion cannot be done or is
1163      //      ambiguous, the initialization is ill-formed. The
1164      //      function selected is called with the initializer
1165      //      expression as its argument; if the function is a
1166      //      constructor, the call initializes a temporary of the
1167      //      destination type.
1168      // FIXME: We're pretending to do copy elision here; return to
1169      // this when we have ASTs for such things.
1170      if (!PerformImplicitConversion(Init, DeclType, "initializing"))
1171        return false;
1172
1173      if (InitEntity)
1174        return Diag(InitLoc, diag::err_cannot_initialize_decl)
1175          << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1176          << Init->getType() << Init->getSourceRange();
1177      else
1178        return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1179          << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1180          << Init->getType() << Init->getSourceRange();
1181    }
1182
1183    // C99 6.7.8p16.
1184    if (DeclType->isArrayType())
1185      return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1186        << Init->getSourceRange();
1187
1188    return CheckSingleInitializer(Init, DeclType);
1189  } else if (getLangOptions().CPlusPlus) {
1190    // C++ [dcl.init]p14:
1191    //   [...] If the class is an aggregate (8.5.1), and the initializer
1192    //   is a brace-enclosed list, see 8.5.1.
1193    //
1194    // Note: 8.5.1 is handled below; here, we diagnose the case where
1195    // we have an initializer list and a destination type that is not
1196    // an aggregate.
1197    // FIXME: In C++0x, this is yet another form of initialization.
1198    if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1199      const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1200      if (!ClassDecl->isAggregate())
1201        return Diag(InitLoc, diag::err_init_non_aggr_init_list)
1202           << DeclType << Init->getSourceRange();
1203    }
1204  }
1205
1206  InitListChecker CheckInitList(this, InitList, DeclType);
1207  return CheckInitList.HadError();
1208}
1209
1210/// GetNameForDeclarator - Determine the full declaration name for the
1211/// given Declarator.
1212DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1213  switch (D.getKind()) {
1214  case Declarator::DK_Abstract:
1215    assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1216    return DeclarationName();
1217
1218  case Declarator::DK_Normal:
1219    assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1220    return DeclarationName(D.getIdentifier());
1221
1222  case Declarator::DK_Constructor: {
1223    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1224    Ty = Context.getCanonicalType(Ty);
1225    return Context.DeclarationNames.getCXXConstructorName(Ty);
1226  }
1227
1228  case Declarator::DK_Destructor: {
1229    QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1230    Ty = Context.getCanonicalType(Ty);
1231    return Context.DeclarationNames.getCXXDestructorName(Ty);
1232  }
1233
1234  case Declarator::DK_Conversion: {
1235    QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1236    Ty = Context.getCanonicalType(Ty);
1237    return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1238  }
1239
1240  case Declarator::DK_Operator:
1241    assert(D.getIdentifier() == 0 && "operator names have no identifier");
1242    return Context.DeclarationNames.getCXXOperatorName(
1243                                                D.getOverloadedOperator());
1244  }
1245
1246  assert(false && "Unknown name kind");
1247  return DeclarationName();
1248}
1249
1250/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1251/// functions Declaration and Definition are "nearly" matching. This
1252/// heuristic is used to improve diagnostics in the case where an
1253/// out-of-line member function definition doesn't match any
1254/// declaration within the class.
1255static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1256                                           FunctionDecl *Declaration,
1257                                           FunctionDecl *Definition) {
1258  if (Declaration->param_size() != Definition->param_size())
1259    return false;
1260  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1261    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1262    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1263
1264    DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1265    DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1266    if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1267      return false;
1268  }
1269
1270  return true;
1271}
1272
1273Sema::DeclTy *
1274Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1275                      bool IsFunctionDefinition) {
1276  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
1277  DeclarationName Name = GetNameForDeclarator(D);
1278
1279  // All of these full declarators require an identifier.  If it doesn't have
1280  // one, the ParsedFreeStandingDeclSpec action should be used.
1281  if (!Name) {
1282    if (!D.getInvalidType())  // Reject this if we think it is valid.
1283      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1284           diag::err_declarator_need_ident)
1285        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1286    return 0;
1287  }
1288
1289  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1290  // we find one that is.
1291  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1292        (S->getFlags() & Scope::TemplateParamScope) != 0)
1293    S = S->getParent();
1294
1295  DeclContext *DC;
1296  Decl *PrevDecl;
1297  ScopedDecl *New;
1298  bool InvalidDecl = false;
1299
1300  // See if this is a redefinition of a variable in the same scope.
1301  if (!D.getCXXScopeSpec().isSet()) {
1302    DC = CurContext;
1303    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
1304  } else { // Something like "int foo::x;"
1305    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
1306    PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1307
1308    // C++ 7.3.1.2p2:
1309    // Members (including explicit specializations of templates) of a named
1310    // namespace can also be defined outside that namespace by explicit
1311    // qualification of the name being defined, provided that the entity being
1312    // defined was already declared in the namespace and the definition appears
1313    // after the point of declaration in a namespace that encloses the
1314    // declarations namespace.
1315    //
1316    // Note that we only check the context at this point. We don't yet
1317    // have enough information to make sure that PrevDecl is actually
1318    // the declaration we want to match. For example, given:
1319    //
1320    //   class X {
1321    //     void f();
1322    //     void f(float);
1323    //   };
1324    //
1325    //   void X::f(int) { } // ill-formed
1326    //
1327    // In this case, PrevDecl will point to the overload set
1328    // containing the two f's declared in X, but neither of them
1329    // matches.
1330    if (!CurContext->Encloses(DC)) {
1331      // The qualifying scope doesn't enclose the original declaration.
1332      // Emit diagnostic based on current scope.
1333      SourceLocation L = D.getIdentifierLoc();
1334      SourceRange R = D.getCXXScopeSpec().getRange();
1335      if (isa<FunctionDecl>(CurContext)) {
1336        Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1337      } else {
1338        Diag(L, diag::err_invalid_declarator_scope)
1339          << Name << cast<NamedDecl>(DC)->getDeclName() << R;
1340      }
1341      InvalidDecl = true;
1342    }
1343  }
1344
1345  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1346    // Maybe we will complain about the shadowed template parameter.
1347    InvalidDecl = InvalidDecl
1348      || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
1349    // Just pretend that we didn't see the previous declaration.
1350    PrevDecl = 0;
1351  }
1352
1353  // In C++, the previous declaration we find might be a tag type
1354  // (class or enum). In this case, the new declaration will hide the
1355  // tag type.
1356  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1357    PrevDecl = 0;
1358
1359  QualType R = GetTypeForDeclarator(D, S);
1360  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1361
1362  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1363    // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1364    if (D.getCXXScopeSpec().isSet()) {
1365      Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1366        << D.getCXXScopeSpec().getRange();
1367      InvalidDecl = true;
1368      // Pretend we didn't see the scope specifier.
1369      DC = 0;
1370    }
1371
1372    // Check that there are no default arguments (C++ only).
1373    if (getLangOptions().CPlusPlus)
1374      CheckExtraCXXDefaultArguments(D);
1375
1376    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1377    if (!NewTD) return 0;
1378
1379    // Handle attributes prior to checking for duplicates in MergeVarDecl
1380    ProcessDeclAttributes(NewTD, D);
1381    // Merge the decl with the existing one if appropriate. If the decl is
1382    // in an outer scope, it isn't the same thing.
1383    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1384      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1385      if (NewTD == 0) return 0;
1386    }
1387    New = NewTD;
1388    if (S->getFnParent() == 0) {
1389      // C99 6.7.7p2: If a typedef name specifies a variably modified type
1390      // then it shall have block scope.
1391      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1392        if (NewTD->getUnderlyingType()->isVariableArrayType())
1393          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1394        else
1395          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1396
1397        InvalidDecl = true;
1398      }
1399    }
1400  } else if (R.getTypePtr()->isFunctionType()) {
1401    FunctionDecl::StorageClass SC = FunctionDecl::None;
1402    switch (D.getDeclSpec().getStorageClassSpec()) {
1403      default: assert(0 && "Unknown storage class!");
1404      case DeclSpec::SCS_auto:
1405      case DeclSpec::SCS_register:
1406      case DeclSpec::SCS_mutable:
1407        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1408        InvalidDecl = true;
1409        break;
1410      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1411      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
1412      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
1413      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1414    }
1415
1416    bool isInline = D.getDeclSpec().isInlineSpecified();
1417    // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1418    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1419
1420    FunctionDecl *NewFD;
1421    if (D.getKind() == Declarator::DK_Constructor) {
1422      // This is a C++ constructor declaration.
1423      assert(DC->isRecord() &&
1424             "Constructors can only be declared in a member context");
1425
1426      InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1427
1428      // Create the new declaration
1429      NewFD = CXXConstructorDecl::Create(Context,
1430                                         cast<CXXRecordDecl>(DC),
1431                                         D.getIdentifierLoc(), Name, R,
1432                                         isExplicit, isInline,
1433                                         /*isImplicitlyDeclared=*/false);
1434
1435      if (InvalidDecl)
1436        NewFD->setInvalidDecl();
1437    } else if (D.getKind() == Declarator::DK_Destructor) {
1438      // This is a C++ destructor declaration.
1439      if (DC->isRecord()) {
1440        InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1441
1442        NewFD = CXXDestructorDecl::Create(Context,
1443                                          cast<CXXRecordDecl>(DC),
1444                                          D.getIdentifierLoc(), Name, R,
1445                                          isInline,
1446                                          /*isImplicitlyDeclared=*/false);
1447
1448        if (InvalidDecl)
1449          NewFD->setInvalidDecl();
1450      } else {
1451        Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1452
1453        // Create a FunctionDecl to satisfy the function definition parsing
1454        // code path.
1455        NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1456                                     Name, R, SC, isInline, LastDeclarator,
1457                                     // FIXME: Move to DeclGroup...
1458                                   D.getDeclSpec().getSourceRange().getBegin());
1459        InvalidDecl = true;
1460        NewFD->setInvalidDecl();
1461      }
1462    } else if (D.getKind() == Declarator::DK_Conversion) {
1463      if (!DC->isRecord()) {
1464        Diag(D.getIdentifierLoc(),
1465             diag::err_conv_function_not_member);
1466        return 0;
1467      } else {
1468        InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1469
1470        NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1471                                          D.getIdentifierLoc(), Name, R,
1472                                          isInline, isExplicit);
1473
1474        if (InvalidDecl)
1475          NewFD->setInvalidDecl();
1476      }
1477    } else if (DC->isRecord()) {
1478      // This is a C++ method declaration.
1479      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1480                                    D.getIdentifierLoc(), Name, R,
1481                                    (SC == FunctionDecl::Static), isInline,
1482                                    LastDeclarator);
1483    } else {
1484      NewFD = FunctionDecl::Create(Context, DC,
1485                                   D.getIdentifierLoc(),
1486                                   Name, R, SC, isInline, LastDeclarator,
1487                                   // FIXME: Move to DeclGroup...
1488                                   D.getDeclSpec().getSourceRange().getBegin());
1489    }
1490
1491    // Set the lexical context. If the declarator has a C++
1492    // scope specifier, the lexical context will be different
1493    // from the semantic context.
1494    NewFD->setLexicalDeclContext(CurContext);
1495
1496    // Handle GNU asm-label extension (encoded as an attribute).
1497    if (Expr *E = (Expr*) D.getAsmLabel()) {
1498      // The parser guarantees this is a string.
1499      StringLiteral *SE = cast<StringLiteral>(E);
1500      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1501                                                  SE->getByteLength())));
1502    }
1503
1504    // Copy the parameter declarations from the declarator D to
1505    // the function declaration NewFD, if they are available.
1506    if (D.getNumTypeObjects() > 0) {
1507      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1508
1509      // Create Decl objects for each parameter, adding them to the
1510      // FunctionDecl.
1511      llvm::SmallVector<ParmVarDecl*, 16> Params;
1512
1513      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1514      // function that takes no arguments, not a function that takes a
1515      // single void argument.
1516      // We let through "const void" here because Sema::GetTypeForDeclarator
1517      // already checks for that case.
1518      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1519          FTI.ArgInfo[0].Param &&
1520          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1521        // empty arg list, don't push any params.
1522        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1523
1524        // In C++, the empty parameter-type-list must be spelled "void"; a
1525        // typedef of void is not permitted.
1526        if (getLangOptions().CPlusPlus &&
1527            Param->getType().getUnqualifiedType() != Context.VoidTy) {
1528          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1529        }
1530      } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1531        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1532          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1533      }
1534
1535      NewFD->setParams(&Params[0], Params.size());
1536    } else if (R->getAsTypedefType()) {
1537      // When we're declaring a function with a typedef, as in the
1538      // following example, we'll need to synthesize (unnamed)
1539      // parameters for use in the declaration.
1540      //
1541      // @code
1542      // typedef void fn(int);
1543      // fn f;
1544      // @endcode
1545      const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1546      if (!FT) {
1547        // This is a typedef of a function with no prototype, so we
1548        // don't need to do anything.
1549      } else if ((FT->getNumArgs() == 0) ||
1550          (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1551           FT->getArgType(0)->isVoidType())) {
1552        // This is a zero-argument function. We don't need to do anything.
1553      } else {
1554        // Synthesize a parameter for each argument type.
1555        llvm::SmallVector<ParmVarDecl*, 16> Params;
1556        for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1557             ArgType != FT->arg_type_end(); ++ArgType) {
1558          Params.push_back(ParmVarDecl::Create(Context, DC,
1559                                               SourceLocation(), 0,
1560                                               *ArgType, VarDecl::None,
1561                                               0, 0));
1562        }
1563
1564        NewFD->setParams(&Params[0], Params.size());
1565      }
1566    }
1567
1568    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1569      InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1570    else if (isa<CXXDestructorDecl>(NewFD)) {
1571      CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1572      Record->setUserDeclaredDestructor(true);
1573      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1574      // user-defined destructor.
1575      Record->setPOD(false);
1576    } else if (CXXConversionDecl *Conversion =
1577               dyn_cast<CXXConversionDecl>(NewFD))
1578      ActOnConversionDeclarator(Conversion);
1579
1580    // Extra checking for C++ overloaded operators (C++ [over.oper]).
1581    if (NewFD->isOverloadedOperator() &&
1582        CheckOverloadedOperatorDeclaration(NewFD))
1583      NewFD->setInvalidDecl();
1584
1585    // Merge the decl with the existing one if appropriate. Since C functions
1586    // are in a flat namespace, make sure we consider decls in outer scopes.
1587    if (PrevDecl &&
1588        (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1589      bool Redeclaration = false;
1590
1591      // If C++, determine whether NewFD is an overload of PrevDecl or
1592      // a declaration that requires merging. If it's an overload,
1593      // there's no more work to do here; we'll just add the new
1594      // function to the scope.
1595      OverloadedFunctionDecl::function_iterator MatchedDecl;
1596      if (!getLangOptions().CPlusPlus ||
1597          !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1598        Decl *OldDecl = PrevDecl;
1599
1600        // If PrevDecl was an overloaded function, extract the
1601        // FunctionDecl that matched.
1602        if (isa<OverloadedFunctionDecl>(PrevDecl))
1603          OldDecl = *MatchedDecl;
1604
1605        // NewFD and PrevDecl represent declarations that need to be
1606        // merged.
1607        NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1608
1609        if (NewFD == 0) return 0;
1610        if (Redeclaration) {
1611          NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1612
1613          // An out-of-line member function declaration must also be a
1614          // definition (C++ [dcl.meaning]p1).
1615          if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1616              !InvalidDecl) {
1617            Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1618              << D.getCXXScopeSpec().getRange();
1619            NewFD->setInvalidDecl();
1620          }
1621        }
1622      }
1623
1624      if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1625        // The user tried to provide an out-of-line definition for a
1626        // member function, but there was no such member function
1627        // declared (C++ [class.mfct]p2). For example:
1628        //
1629        // class X {
1630        //   void f() const;
1631        // };
1632        //
1633        // void X::f() { } // ill-formed
1634        //
1635        // Complain about this problem, and attempt to suggest close
1636        // matches (e.g., those that differ only in cv-qualifiers and
1637        // whether the parameter types are references).
1638        Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1639          << cast<CXXRecordDecl>(DC)->getDeclName()
1640          << D.getCXXScopeSpec().getRange();
1641        InvalidDecl = true;
1642
1643        PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1644        if (!PrevDecl) {
1645          // Nothing to suggest.
1646        } else if (OverloadedFunctionDecl *Ovl
1647                   = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1648          for (OverloadedFunctionDecl::function_iterator
1649                 Func = Ovl->function_begin(),
1650                 FuncEnd = Ovl->function_end();
1651               Func != FuncEnd; ++Func) {
1652            if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1653              Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1654
1655          }
1656        } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1657          // Suggest this no matter how mismatched it is; it's the only
1658          // thing we have.
1659          unsigned diag;
1660          if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1661            diag = diag::note_member_def_close_match;
1662          else if (Method->getBody())
1663            diag = diag::note_previous_definition;
1664          else
1665            diag = diag::note_previous_declaration;
1666          Diag(Method->getLocation(), diag);
1667        }
1668
1669        PrevDecl = 0;
1670      }
1671    }
1672    // Handle attributes. We need to have merged decls when handling attributes
1673    // (for example to check for conflicts, etc).
1674    ProcessDeclAttributes(NewFD, D);
1675    New = NewFD;
1676
1677    if (getLangOptions().CPlusPlus) {
1678      // In C++, check default arguments now that we have merged decls.
1679      CheckCXXDefaultArguments(NewFD);
1680
1681      // An out-of-line member function declaration must also be a
1682      // definition (C++ [dcl.meaning]p1).
1683      if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1684        Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1685          << D.getCXXScopeSpec().getRange();
1686        InvalidDecl = true;
1687      }
1688    }
1689  } else {
1690    // Check that there are no default arguments (C++ only).
1691    if (getLangOptions().CPlusPlus)
1692      CheckExtraCXXDefaultArguments(D);
1693
1694    if (R.getTypePtr()->isObjCInterfaceType()) {
1695      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1696        << D.getIdentifier();
1697      InvalidDecl = true;
1698    }
1699
1700    VarDecl *NewVD;
1701    VarDecl::StorageClass SC;
1702    switch (D.getDeclSpec().getStorageClassSpec()) {
1703    default: assert(0 && "Unknown storage class!");
1704    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1705    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1706    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1707    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1708    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1709    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1710    case DeclSpec::SCS_mutable:
1711      // mutable can only appear on non-static class members, so it's always
1712      // an error here
1713      Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1714      InvalidDecl = true;
1715      SC = VarDecl::None;
1716      break;
1717    }
1718
1719    IdentifierInfo *II = Name.getAsIdentifierInfo();
1720    if (!II) {
1721      Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1722       << Name.getAsString();
1723      return 0;
1724    }
1725
1726    if (DC->isRecord()) {
1727      // This is a static data member for a C++ class.
1728      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1729                                      D.getIdentifierLoc(), II,
1730                                      R, LastDeclarator);
1731    } else {
1732      bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1733      if (S->getFnParent() == 0) {
1734        // C99 6.9p2: The storage-class specifiers auto and register shall not
1735        // appear in the declaration specifiers in an external declaration.
1736        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1737          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1738          InvalidDecl = true;
1739        }
1740      }
1741      NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1742                              II, R, SC, LastDeclarator,
1743                              // FIXME: Move to DeclGroup...
1744                              D.getDeclSpec().getSourceRange().getBegin());
1745      NewVD->setThreadSpecified(ThreadSpecified);
1746    }
1747    // Handle attributes prior to checking for duplicates in MergeVarDecl
1748    ProcessDeclAttributes(NewVD, D);
1749
1750    // Handle GNU asm-label extension (encoded as an attribute).
1751    if (Expr *E = (Expr*) D.getAsmLabel()) {
1752      // The parser guarantees this is a string.
1753      StringLiteral *SE = cast<StringLiteral>(E);
1754      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1755                                                  SE->getByteLength())));
1756    }
1757
1758    // Emit an error if an address space was applied to decl with local storage.
1759    // This includes arrays of objects with address space qualifiers, but not
1760    // automatic variables that point to other address spaces.
1761    // ISO/IEC TR 18037 S5.1.2
1762    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1763      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1764      InvalidDecl = true;
1765    }
1766    // Merge the decl with the existing one if appropriate. If the decl is
1767    // in an outer scope, it isn't the same thing.
1768    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1769      if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1770        // The user tried to define a non-static data member
1771        // out-of-line (C++ [dcl.meaning]p1).
1772        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1773          << D.getCXXScopeSpec().getRange();
1774        NewVD->Destroy(Context);
1775        return 0;
1776      }
1777
1778      NewVD = MergeVarDecl(NewVD, PrevDecl);
1779      if (NewVD == 0) return 0;
1780
1781      if (D.getCXXScopeSpec().isSet()) {
1782        // No previous declaration in the qualifying scope.
1783        Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1784          << Name << D.getCXXScopeSpec().getRange();
1785        InvalidDecl = true;
1786      }
1787    }
1788    New = NewVD;
1789  }
1790
1791  // Set the lexical context. If the declarator has a C++ scope specifier, the
1792  // lexical context will be different from the semantic context.
1793  New->setLexicalDeclContext(CurContext);
1794
1795  // If this has an identifier, add it to the scope stack.
1796  if (Name)
1797    PushOnScopeChains(New, S);
1798  // If any semantic error occurred, mark the decl as invalid.
1799  if (D.getInvalidType() || InvalidDecl)
1800    New->setInvalidDecl();
1801
1802  return New;
1803}
1804
1805void Sema::InitializerElementNotConstant(const Expr *Init) {
1806  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1807    << Init->getSourceRange();
1808}
1809
1810bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1811  switch (Init->getStmtClass()) {
1812  default:
1813    InitializerElementNotConstant(Init);
1814    return true;
1815  case Expr::ParenExprClass: {
1816    const ParenExpr* PE = cast<ParenExpr>(Init);
1817    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1818  }
1819  case Expr::CompoundLiteralExprClass:
1820    return cast<CompoundLiteralExpr>(Init)->isFileScope();
1821  case Expr::DeclRefExprClass:
1822  case Expr::QualifiedDeclRefExprClass: {
1823    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1824    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1825      if (VD->hasGlobalStorage())
1826        return false;
1827      InitializerElementNotConstant(Init);
1828      return true;
1829    }
1830    if (isa<FunctionDecl>(D))
1831      return false;
1832    InitializerElementNotConstant(Init);
1833    return true;
1834  }
1835  case Expr::MemberExprClass: {
1836    const MemberExpr *M = cast<MemberExpr>(Init);
1837    if (M->isArrow())
1838      return CheckAddressConstantExpression(M->getBase());
1839    return CheckAddressConstantExpressionLValue(M->getBase());
1840  }
1841  case Expr::ArraySubscriptExprClass: {
1842    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1843    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1844    return CheckAddressConstantExpression(ASE->getBase()) ||
1845           CheckArithmeticConstantExpression(ASE->getIdx());
1846  }
1847  case Expr::StringLiteralClass:
1848  case Expr::PredefinedExprClass:
1849    return false;
1850  case Expr::UnaryOperatorClass: {
1851    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1852
1853    // C99 6.6p9
1854    if (Exp->getOpcode() == UnaryOperator::Deref)
1855      return CheckAddressConstantExpression(Exp->getSubExpr());
1856
1857    InitializerElementNotConstant(Init);
1858    return true;
1859  }
1860  }
1861}
1862
1863bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1864  switch (Init->getStmtClass()) {
1865  default:
1866    InitializerElementNotConstant(Init);
1867    return true;
1868  case Expr::ParenExprClass:
1869    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
1870  case Expr::StringLiteralClass:
1871  case Expr::ObjCStringLiteralClass:
1872    return false;
1873  case Expr::CallExprClass:
1874  case Expr::CXXOperatorCallExprClass:
1875    // __builtin___CFStringMakeConstantString is a valid constant l-value.
1876    if (cast<CallExpr>(Init)->isBuiltinCall() ==
1877           Builtin::BI__builtin___CFStringMakeConstantString)
1878      return false;
1879
1880    InitializerElementNotConstant(Init);
1881    return true;
1882
1883  case Expr::UnaryOperatorClass: {
1884    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1885
1886    // C99 6.6p9
1887    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1888      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1889
1890    if (Exp->getOpcode() == UnaryOperator::Extension)
1891      return CheckAddressConstantExpression(Exp->getSubExpr());
1892
1893    InitializerElementNotConstant(Init);
1894    return true;
1895  }
1896  case Expr::BinaryOperatorClass: {
1897    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1898    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1899
1900    Expr *PExp = Exp->getLHS();
1901    Expr *IExp = Exp->getRHS();
1902    if (IExp->getType()->isPointerType())
1903      std::swap(PExp, IExp);
1904
1905    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1906    return CheckAddressConstantExpression(PExp) ||
1907           CheckArithmeticConstantExpression(IExp);
1908  }
1909  case Expr::ImplicitCastExprClass:
1910  case Expr::CStyleCastExprClass: {
1911    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1912    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1913      // Check for implicit promotion
1914      if (SubExpr->getType()->isFunctionType() ||
1915          SubExpr->getType()->isArrayType())
1916        return CheckAddressConstantExpressionLValue(SubExpr);
1917    }
1918
1919    // Check for pointer->pointer cast
1920    if (SubExpr->getType()->isPointerType())
1921      return CheckAddressConstantExpression(SubExpr);
1922
1923    if (SubExpr->getType()->isIntegralType()) {
1924      // Check for the special-case of a pointer->int->pointer cast;
1925      // this isn't standard, but some code requires it. See
1926      // PR2720 for an example.
1927      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1928        if (SubCast->getSubExpr()->getType()->isPointerType()) {
1929          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1930          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1931          if (IntWidth >= PointerWidth) {
1932            return CheckAddressConstantExpression(SubCast->getSubExpr());
1933          }
1934        }
1935      }
1936    }
1937    if (SubExpr->getType()->isArithmeticType()) {
1938      return CheckArithmeticConstantExpression(SubExpr);
1939    }
1940
1941    InitializerElementNotConstant(Init);
1942    return true;
1943  }
1944  case Expr::ConditionalOperatorClass: {
1945    // FIXME: Should we pedwarn here?
1946    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1947    if (!Exp->getCond()->getType()->isArithmeticType()) {
1948      InitializerElementNotConstant(Init);
1949      return true;
1950    }
1951    if (CheckArithmeticConstantExpression(Exp->getCond()))
1952      return true;
1953    if (Exp->getLHS() &&
1954        CheckAddressConstantExpression(Exp->getLHS()))
1955      return true;
1956    return CheckAddressConstantExpression(Exp->getRHS());
1957  }
1958  case Expr::AddrLabelExprClass:
1959    return false;
1960  }
1961}
1962
1963static const Expr* FindExpressionBaseAddress(const Expr* E);
1964
1965static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1966  switch (E->getStmtClass()) {
1967  default:
1968    return E;
1969  case Expr::ParenExprClass: {
1970    const ParenExpr* PE = cast<ParenExpr>(E);
1971    return FindExpressionBaseAddressLValue(PE->getSubExpr());
1972  }
1973  case Expr::MemberExprClass: {
1974    const MemberExpr *M = cast<MemberExpr>(E);
1975    if (M->isArrow())
1976      return FindExpressionBaseAddress(M->getBase());
1977    return FindExpressionBaseAddressLValue(M->getBase());
1978  }
1979  case Expr::ArraySubscriptExprClass: {
1980    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1981    return FindExpressionBaseAddress(ASE->getBase());
1982  }
1983  case Expr::UnaryOperatorClass: {
1984    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1985
1986    if (Exp->getOpcode() == UnaryOperator::Deref)
1987      return FindExpressionBaseAddress(Exp->getSubExpr());
1988
1989    return E;
1990  }
1991  }
1992}
1993
1994static const Expr* FindExpressionBaseAddress(const Expr* E) {
1995  switch (E->getStmtClass()) {
1996  default:
1997    return E;
1998  case Expr::ParenExprClass: {
1999    const ParenExpr* PE = cast<ParenExpr>(E);
2000    return FindExpressionBaseAddress(PE->getSubExpr());
2001  }
2002  case Expr::UnaryOperatorClass: {
2003    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2004
2005    // C99 6.6p9
2006    if (Exp->getOpcode() == UnaryOperator::AddrOf)
2007      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2008
2009    if (Exp->getOpcode() == UnaryOperator::Extension)
2010      return FindExpressionBaseAddress(Exp->getSubExpr());
2011
2012    return E;
2013  }
2014  case Expr::BinaryOperatorClass: {
2015    const BinaryOperator *Exp = cast<BinaryOperator>(E);
2016
2017    Expr *PExp = Exp->getLHS();
2018    Expr *IExp = Exp->getRHS();
2019    if (IExp->getType()->isPointerType())
2020      std::swap(PExp, IExp);
2021
2022    return FindExpressionBaseAddress(PExp);
2023  }
2024  case Expr::ImplicitCastExprClass: {
2025    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2026
2027    // Check for implicit promotion
2028    if (SubExpr->getType()->isFunctionType() ||
2029        SubExpr->getType()->isArrayType())
2030      return FindExpressionBaseAddressLValue(SubExpr);
2031
2032    // Check for pointer->pointer cast
2033    if (SubExpr->getType()->isPointerType())
2034      return FindExpressionBaseAddress(SubExpr);
2035
2036    // We assume that we have an arithmetic expression here;
2037    // if we don't, we'll figure it out later
2038    return 0;
2039  }
2040  case Expr::CStyleCastExprClass: {
2041    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2042
2043    // Check for pointer->pointer cast
2044    if (SubExpr->getType()->isPointerType())
2045      return FindExpressionBaseAddress(SubExpr);
2046
2047    // We assume that we have an arithmetic expression here;
2048    // if we don't, we'll figure it out later
2049    return 0;
2050  }
2051  }
2052}
2053
2054bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
2055  switch (Init->getStmtClass()) {
2056  default:
2057    InitializerElementNotConstant(Init);
2058    return true;
2059  case Expr::ParenExprClass: {
2060    const ParenExpr* PE = cast<ParenExpr>(Init);
2061    return CheckArithmeticConstantExpression(PE->getSubExpr());
2062  }
2063  case Expr::FloatingLiteralClass:
2064  case Expr::IntegerLiteralClass:
2065  case Expr::CharacterLiteralClass:
2066  case Expr::ImaginaryLiteralClass:
2067  case Expr::TypesCompatibleExprClass:
2068  case Expr::CXXBoolLiteralExprClass:
2069    return false;
2070  case Expr::CallExprClass:
2071  case Expr::CXXOperatorCallExprClass: {
2072    const CallExpr *CE = cast<CallExpr>(Init);
2073
2074    // Allow any constant foldable calls to builtins.
2075    if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
2076      return false;
2077
2078    InitializerElementNotConstant(Init);
2079    return true;
2080  }
2081  case Expr::DeclRefExprClass:
2082  case Expr::QualifiedDeclRefExprClass: {
2083    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2084    if (isa<EnumConstantDecl>(D))
2085      return false;
2086    InitializerElementNotConstant(Init);
2087    return true;
2088  }
2089  case Expr::CompoundLiteralExprClass:
2090    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2091    // but vectors are allowed to be magic.
2092    if (Init->getType()->isVectorType())
2093      return false;
2094    InitializerElementNotConstant(Init);
2095    return true;
2096  case Expr::UnaryOperatorClass: {
2097    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2098
2099    switch (Exp->getOpcode()) {
2100    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2101    // See C99 6.6p3.
2102    default:
2103      InitializerElementNotConstant(Init);
2104      return true;
2105    case UnaryOperator::OffsetOf:
2106      if (Exp->getSubExpr()->getType()->isConstantSizeType())
2107        return false;
2108      InitializerElementNotConstant(Init);
2109      return true;
2110    case UnaryOperator::Extension:
2111    case UnaryOperator::LNot:
2112    case UnaryOperator::Plus:
2113    case UnaryOperator::Minus:
2114    case UnaryOperator::Not:
2115      return CheckArithmeticConstantExpression(Exp->getSubExpr());
2116    }
2117  }
2118  case Expr::SizeOfAlignOfExprClass: {
2119    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
2120    // Special check for void types, which are allowed as an extension
2121    if (Exp->getTypeOfArgument()->isVoidType())
2122      return false;
2123    // alignof always evaluates to a constant.
2124    // FIXME: is sizeof(int[3.0]) a constant expression?
2125    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
2126      InitializerElementNotConstant(Init);
2127      return true;
2128    }
2129    return false;
2130  }
2131  case Expr::BinaryOperatorClass: {
2132    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2133
2134    if (Exp->getLHS()->getType()->isArithmeticType() &&
2135        Exp->getRHS()->getType()->isArithmeticType()) {
2136      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2137             CheckArithmeticConstantExpression(Exp->getRHS());
2138    }
2139
2140    if (Exp->getLHS()->getType()->isPointerType() &&
2141        Exp->getRHS()->getType()->isPointerType()) {
2142      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2143      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2144
2145      // Only allow a null (constant integer) base; we could
2146      // allow some additional cases if necessary, but this
2147      // is sufficient to cover offsetof-like constructs.
2148      if (!LHSBase && !RHSBase) {
2149        return CheckAddressConstantExpression(Exp->getLHS()) ||
2150               CheckAddressConstantExpression(Exp->getRHS());
2151      }
2152    }
2153
2154    InitializerElementNotConstant(Init);
2155    return true;
2156  }
2157  case Expr::ImplicitCastExprClass:
2158  case Expr::CStyleCastExprClass: {
2159    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
2160    if (SubExpr->getType()->isArithmeticType())
2161      return CheckArithmeticConstantExpression(SubExpr);
2162
2163    if (SubExpr->getType()->isPointerType()) {
2164      const Expr* Base = FindExpressionBaseAddress(SubExpr);
2165      // If the pointer has a null base, this is an offsetof-like construct
2166      if (!Base)
2167        return CheckAddressConstantExpression(SubExpr);
2168    }
2169
2170    InitializerElementNotConstant(Init);
2171    return true;
2172  }
2173  case Expr::ConditionalOperatorClass: {
2174    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2175
2176    // If GNU extensions are disabled, we require all operands to be arithmetic
2177    // constant expressions.
2178    if (getLangOptions().NoExtensions) {
2179      return CheckArithmeticConstantExpression(Exp->getCond()) ||
2180          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2181             CheckArithmeticConstantExpression(Exp->getRHS());
2182    }
2183
2184    // Otherwise, we have to emulate some of the behavior of fold here.
2185    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2186    // because it can constant fold things away.  To retain compatibility with
2187    // GCC code, we see if we can fold the condition to a constant (which we
2188    // should always be able to do in theory).  If so, we only require the
2189    // specified arm of the conditional to be a constant.  This is a horrible
2190    // hack, but is require by real world code that uses __builtin_constant_p.
2191    Expr::EvalResult EvalResult;
2192    if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2193        EvalResult.HasSideEffects) {
2194      // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
2195      // won't be able to either.  Use it to emit the diagnostic though.
2196      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
2197      assert(Res && "Evaluate couldn't evaluate this constant?");
2198      return Res;
2199    }
2200
2201    // Verify that the side following the condition is also a constant.
2202    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
2203    if (EvalResult.Val.getInt() == 0)
2204      std::swap(TrueSide, FalseSide);
2205
2206    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
2207      return true;
2208
2209    // Okay, the evaluated side evaluates to a constant, so we accept this.
2210    // Check to see if the other side is obviously not a constant.  If so,
2211    // emit a warning that this is a GNU extension.
2212    if (FalseSide && !FalseSide->isEvaluatable(Context))
2213      Diag(Init->getExprLoc(),
2214           diag::ext_typecheck_expression_not_constant_but_accepted)
2215        << FalseSide->getSourceRange();
2216    return false;
2217  }
2218  }
2219}
2220
2221bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
2222  Expr::EvalResult Result;
2223
2224  Init = Init->IgnoreParens();
2225
2226  if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2227    return false;
2228
2229  // Look through CXXDefaultArgExprs; they have no meaning in this context.
2230  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2231    return CheckForConstantInitializer(DAE->getExpr(), DclT);
2232
2233  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2234    return CheckForConstantInitializer(e->getInitializer(), DclT);
2235
2236  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2237    unsigned numInits = Exp->getNumInits();
2238    for (unsigned i = 0; i < numInits; i++) {
2239      // FIXME: Need to get the type of the declaration for C++,
2240      // because it could be a reference?
2241      if (CheckForConstantInitializer(Exp->getInit(i),
2242                                      Exp->getInit(i)->getType()))
2243        return true;
2244    }
2245    return false;
2246  }
2247
2248  // FIXME: We can probably remove some of this code below, now that
2249  // Expr::Evaluate is doing the heavy lifting for scalars.
2250
2251  if (Init->isNullPointerConstant(Context))
2252    return false;
2253  if (Init->getType()->isArithmeticType()) {
2254    QualType InitTy = Context.getCanonicalType(Init->getType())
2255                             .getUnqualifiedType();
2256    if (InitTy == Context.BoolTy) {
2257      // Special handling for pointers implicitly cast to bool;
2258      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2259      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2260        Expr* SubE = ICE->getSubExpr();
2261        if (SubE->getType()->isPointerType() ||
2262            SubE->getType()->isArrayType() ||
2263            SubE->getType()->isFunctionType()) {
2264          return CheckAddressConstantExpression(Init);
2265        }
2266      }
2267    } else if (InitTy->isIntegralType()) {
2268      Expr* SubE = 0;
2269      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
2270        SubE = CE->getSubExpr();
2271      // Special check for pointer cast to int; we allow as an extension
2272      // an address constant cast to an integer if the integer
2273      // is of an appropriate width (this sort of code is apparently used
2274      // in some places).
2275      // FIXME: Add pedwarn?
2276      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
2277      if (SubE && (SubE->getType()->isPointerType() ||
2278                   SubE->getType()->isArrayType() ||
2279                   SubE->getType()->isFunctionType())) {
2280        unsigned IntWidth = Context.getTypeSize(Init->getType());
2281        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2282        if (IntWidth >= PointerWidth)
2283          return CheckAddressConstantExpression(Init);
2284      }
2285    }
2286
2287    return CheckArithmeticConstantExpression(Init);
2288  }
2289
2290  if (Init->getType()->isPointerType())
2291    return CheckAddressConstantExpression(Init);
2292
2293  // An array type at the top level that isn't an init-list must
2294  // be a string literal
2295  if (Init->getType()->isArrayType())
2296    return false;
2297
2298  if (Init->getType()->isFunctionType())
2299    return false;
2300
2301  // Allow block exprs at top level.
2302  if (Init->getType()->isBlockPointerType())
2303    return false;
2304
2305  InitializerElementNotConstant(Init);
2306  return true;
2307}
2308
2309void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
2310  Decl *RealDecl = static_cast<Decl *>(dcl);
2311  Expr *Init = static_cast<Expr *>(init.release());
2312  assert(Init && "missing initializer");
2313
2314  // If there is no declaration, there was an error parsing it.  Just ignore
2315  // the initializer.
2316  if (RealDecl == 0) {
2317    delete Init;
2318    return;
2319  }
2320
2321  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2322  if (!VDecl) {
2323    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2324         diag::err_illegal_initializer);
2325    RealDecl->setInvalidDecl();
2326    return;
2327  }
2328  // Get the decls type and save a reference for later, since
2329  // CheckInitializerTypes may change it.
2330  QualType DclT = VDecl->getType(), SavT = DclT;
2331  if (VDecl->isBlockVarDecl()) {
2332    VarDecl::StorageClass SC = VDecl->getStorageClass();
2333    if (SC == VarDecl::Extern) { // C99 6.7.8p5
2334      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
2335      VDecl->setInvalidDecl();
2336    } else if (!VDecl->isInvalidDecl()) {
2337      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2338                                VDecl->getDeclName()))
2339        VDecl->setInvalidDecl();
2340
2341      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2342      if (!getLangOptions().CPlusPlus) {
2343        if (SC == VarDecl::Static) // C99 6.7.8p4.
2344          CheckForConstantInitializer(Init, DclT);
2345      }
2346    }
2347  } else if (VDecl->isFileVarDecl()) {
2348    if (VDecl->getStorageClass() == VarDecl::Extern)
2349      Diag(VDecl->getLocation(), diag::warn_extern_init);
2350    if (!VDecl->isInvalidDecl())
2351      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
2352                                VDecl->getDeclName()))
2353        VDecl->setInvalidDecl();
2354
2355    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2356    if (!getLangOptions().CPlusPlus) {
2357      // C99 6.7.8p4. All file scoped initializers need to be constant.
2358      CheckForConstantInitializer(Init, DclT);
2359    }
2360  }
2361  // If the type changed, it means we had an incomplete type that was
2362  // completed by the initializer. For example:
2363  //   int ary[] = { 1, 3, 5 };
2364  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
2365  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
2366    VDecl->setType(DclT);
2367    Init->setType(DclT);
2368  }
2369
2370  // Attach the initializer to the decl.
2371  VDecl->setInit(Init);
2372  return;
2373}
2374
2375void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2376  Decl *RealDecl = static_cast<Decl *>(dcl);
2377
2378  // If there is no declaration, there was an error parsing it. Just ignore it.
2379  if (RealDecl == 0)
2380    return;
2381
2382  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2383    QualType Type = Var->getType();
2384    // C++ [dcl.init.ref]p3:
2385    //   The initializer can be omitted for a reference only in a
2386    //   parameter declaration (8.3.5), in the declaration of a
2387    //   function return type, in the declaration of a class member
2388    //   within its class declaration (9.2), and where the extern
2389    //   specifier is explicitly used.
2390    if (Type->isReferenceType() &&
2391        Var->getStorageClass() != VarDecl::Extern &&
2392        Var->getStorageClass() != VarDecl::PrivateExtern) {
2393      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
2394        << Var->getDeclName()
2395        << SourceRange(Var->getLocation(), Var->getLocation());
2396      Var->setInvalidDecl();
2397      return;
2398    }
2399
2400    // C++ [dcl.init]p9:
2401    //
2402    //   If no initializer is specified for an object, and the object
2403    //   is of (possibly cv-qualified) non-POD class type (or array
2404    //   thereof), the object shall be default-initialized; if the
2405    //   object is of const-qualified type, the underlying class type
2406    //   shall have a user-declared default constructor.
2407    if (getLangOptions().CPlusPlus) {
2408      QualType InitType = Type;
2409      if (const ArrayType *Array = Context.getAsArrayType(Type))
2410        InitType = Array->getElementType();
2411      if (Var->getStorageClass() != VarDecl::Extern &&
2412          Var->getStorageClass() != VarDecl::PrivateExtern &&
2413          InitType->isRecordType()) {
2414        const CXXConstructorDecl *Constructor
2415          = PerformInitializationByConstructor(InitType, 0, 0,
2416                                               Var->getLocation(),
2417                                               SourceRange(Var->getLocation(),
2418                                                           Var->getLocation()),
2419                                               Var->getDeclName(),
2420                                               IK_Default);
2421        if (!Constructor)
2422          Var->setInvalidDecl();
2423      }
2424    }
2425
2426#if 0
2427    // FIXME: Temporarily disabled because we are not properly parsing
2428    // linkage specifications on declarations, e.g.,
2429    //
2430    //   extern "C" const CGPoint CGPointerZero;
2431    //
2432    // C++ [dcl.init]p9:
2433    //
2434    //     If no initializer is specified for an object, and the
2435    //     object is of (possibly cv-qualified) non-POD class type (or
2436    //     array thereof), the object shall be default-initialized; if
2437    //     the object is of const-qualified type, the underlying class
2438    //     type shall have a user-declared default
2439    //     constructor. Otherwise, if no initializer is specified for
2440    //     an object, the object and its subobjects, if any, have an
2441    //     indeterminate initial value; if the object or any of its
2442    //     subobjects are of const-qualified type, the program is
2443    //     ill-formed.
2444    //
2445    // This isn't technically an error in C, so we don't diagnose it.
2446    //
2447    // FIXME: Actually perform the POD/user-defined default
2448    // constructor check.
2449    if (getLangOptions().CPlusPlus &&
2450        Context.getCanonicalType(Type).isConstQualified() &&
2451        Var->getStorageClass() != VarDecl::Extern)
2452      Diag(Var->getLocation(),  diag::err_const_var_requires_init)
2453        << Var->getName()
2454        << SourceRange(Var->getLocation(), Var->getLocation());
2455#endif
2456  }
2457}
2458
2459/// The declarators are chained together backwards, reverse the list.
2460Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2461  // Often we have single declarators, handle them quickly.
2462  Decl *GroupDecl = static_cast<Decl*>(group);
2463  if (GroupDecl == 0)
2464    return 0;
2465
2466  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2467  ScopedDecl *NewGroup = 0;
2468  if (Group->getNextDeclarator() == 0)
2469    NewGroup = Group;
2470  else { // reverse the list.
2471    while (Group) {
2472      ScopedDecl *Next = Group->getNextDeclarator();
2473      Group->setNextDeclarator(NewGroup);
2474      NewGroup = Group;
2475      Group = Next;
2476    }
2477  }
2478  // Perform semantic analysis that depends on having fully processed both
2479  // the declarator and initializer.
2480  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
2481    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2482    if (!IDecl)
2483      continue;
2484    QualType T = IDecl->getType();
2485
2486    if (T->isVariableArrayType()) {
2487      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2488
2489      // FIXME: This won't give the correct result for
2490      // int a[10][n];
2491      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2492      if (IDecl->isFileVarDecl()) {
2493        Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2494          SizeRange;
2495
2496        IDecl->setInvalidDecl();
2497      } else {
2498        // C99 6.7.5.2p2: If an identifier is declared to be an object with
2499        // static storage duration, it shall not have a variable length array.
2500        if (IDecl->getStorageClass() == VarDecl::Static) {
2501          Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2502            << SizeRange;
2503          IDecl->setInvalidDecl();
2504        } else if (IDecl->getStorageClass() == VarDecl::Extern) {
2505          Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2506            << SizeRange;
2507          IDecl->setInvalidDecl();
2508        }
2509      }
2510    } else if (T->isVariablyModifiedType()) {
2511      if (IDecl->isFileVarDecl()) {
2512        Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2513        IDecl->setInvalidDecl();
2514      } else {
2515        if (IDecl->getStorageClass() == VarDecl::Extern) {
2516          Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2517          IDecl->setInvalidDecl();
2518        }
2519      }
2520    }
2521
2522    // Block scope. C99 6.7p7: If an identifier for an object is declared with
2523    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
2524    if (IDecl->isBlockVarDecl() &&
2525        IDecl->getStorageClass() != VarDecl::Extern) {
2526      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2527        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2528        IDecl->setInvalidDecl();
2529      }
2530    }
2531    // File scope. C99 6.9.2p2: A declaration of an identifier for and
2532    // object that has file scope without an initializer, and without a
2533    // storage-class specifier or with the storage-class specifier "static",
2534    // constitutes a tentative definition. Note: A tentative definition with
2535    // external linkage is valid (C99 6.2.2p5).
2536    if (isTentativeDefinition(IDecl)) {
2537      if (T->isIncompleteArrayType()) {
2538        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2539        // array to be completed. Don't issue a diagnostic.
2540      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
2541        // C99 6.9.2p3: If the declaration of an identifier for an object is
2542        // a tentative definition and has internal linkage (C99 6.2.2p3), the
2543        // declared type shall not be an incomplete type.
2544        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
2545        IDecl->setInvalidDecl();
2546      }
2547    }
2548    if (IDecl->isFileVarDecl())
2549      CheckForFileScopedRedefinitions(S, IDecl);
2550  }
2551  return NewGroup;
2552}
2553
2554/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2555/// to introduce parameters into function prototype scope.
2556Sema::DeclTy *
2557Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
2558  const DeclSpec &DS = D.getDeclSpec();
2559
2560  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
2561  VarDecl::StorageClass StorageClass = VarDecl::None;
2562  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2563    StorageClass = VarDecl::Register;
2564  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2565    Diag(DS.getStorageClassSpecLoc(),
2566         diag::err_invalid_storage_class_in_func_decl);
2567    D.getMutableDeclSpec().ClearStorageClassSpecs();
2568  }
2569  if (DS.isThreadSpecified()) {
2570    Diag(DS.getThreadSpecLoc(),
2571         diag::err_invalid_storage_class_in_func_decl);
2572    D.getMutableDeclSpec().ClearStorageClassSpecs();
2573  }
2574
2575  // Check that there are no default arguments inside the type of this
2576  // parameter (C++ only).
2577  if (getLangOptions().CPlusPlus)
2578    CheckExtraCXXDefaultArguments(D);
2579
2580  // In this context, we *do not* check D.getInvalidType(). If the declarator
2581  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2582  // though it will not reflect the user specified type.
2583  QualType parmDeclType = GetTypeForDeclarator(D, S);
2584
2585  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2586
2587  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2588  // Can this happen for params?  We already checked that they don't conflict
2589  // among each other.  Here they can only shadow globals, which is ok.
2590  IdentifierInfo *II = D.getIdentifier();
2591  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2592    if (PrevDecl->isTemplateParameter()) {
2593      // Maybe we will complain about the shadowed template parameter.
2594      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2595      // Just pretend that we didn't see the previous declaration.
2596      PrevDecl = 0;
2597    } else if (S->isDeclScope(PrevDecl)) {
2598      Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
2599
2600      // Recover by removing the name
2601      II = 0;
2602      D.SetIdentifier(0, D.getIdentifierLoc());
2603    }
2604  }
2605
2606  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2607  // Doing the promotion here has a win and a loss. The win is the type for
2608  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2609  // code generator). The loss is the orginal type isn't preserved. For example:
2610  //
2611  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2612  //    int blockvardecl[5];
2613  //    sizeof(parmvardecl);  // size == 4
2614  //    sizeof(blockvardecl); // size == 20
2615  // }
2616  //
2617  // For expressions, all implicit conversions are captured using the
2618  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2619  //
2620  // FIXME: If a source translation tool needs to see the original type, then
2621  // we need to consider storing both types (in ParmVarDecl)...
2622  //
2623  if (parmDeclType->isArrayType()) {
2624    // int x[restrict 4] ->  int *restrict
2625    parmDeclType = Context.getArrayDecayedType(parmDeclType);
2626  } else if (parmDeclType->isFunctionType())
2627    parmDeclType = Context.getPointerType(parmDeclType);
2628
2629  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2630                                         D.getIdentifierLoc(), II,
2631                                         parmDeclType, StorageClass,
2632                                         0, 0);
2633
2634  if (D.getInvalidType())
2635    New->setInvalidDecl();
2636
2637  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2638  if (D.getCXXScopeSpec().isSet()) {
2639    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2640      << D.getCXXScopeSpec().getRange();
2641    New->setInvalidDecl();
2642  }
2643
2644  // Add the parameter declaration into this scope.
2645  S->AddDecl(New);
2646  if (II)
2647    IdResolver.AddDecl(New);
2648
2649  ProcessDeclAttributes(New, D);
2650  return New;
2651
2652}
2653
2654Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2655  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2656  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2657         "Not a function declarator!");
2658  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2659
2660  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2661  // for a K&R function.
2662  if (!FTI.hasPrototype) {
2663    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2664      if (FTI.ArgInfo[i].Param == 0) {
2665        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2666          << FTI.ArgInfo[i].Ident;
2667        // Implicitly declare the argument as type 'int' for lack of a better
2668        // type.
2669        DeclSpec DS;
2670        const char* PrevSpec; // unused
2671        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2672                           PrevSpec);
2673        Declarator ParamD(DS, Declarator::KNRTypeListContext);
2674        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2675        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
2676      }
2677    }
2678  } else {
2679    // FIXME: Diagnose arguments without names in C.
2680  }
2681
2682  Scope *ParentScope = FnBodyScope->getParent();
2683
2684  return ActOnStartOfFunctionDef(FnBodyScope,
2685                                 ActOnDeclarator(ParentScope, D, 0,
2686                                                 /*IsFunctionDefinition=*/true));
2687}
2688
2689Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2690  Decl *decl = static_cast<Decl*>(D);
2691  FunctionDecl *FD = cast<FunctionDecl>(decl);
2692
2693  // See if this is a redefinition.
2694  const FunctionDecl *Definition;
2695  if (FD->getBody(Definition)) {
2696    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
2697    Diag(Definition->getLocation(), diag::note_previous_definition);
2698  }
2699
2700  PushDeclContext(FnBodyScope, FD);
2701
2702  // Check the validity of our function parameters
2703  CheckParmsForFunctionDef(FD);
2704
2705  // Introduce our parameters into the function scope
2706  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2707    ParmVarDecl *Param = FD->getParamDecl(p);
2708    // If this has an identifier, add it to the scope stack.
2709    if (Param->getIdentifier())
2710      PushOnScopeChains(Param, FnBodyScope);
2711  }
2712
2713  // Checking attributes of current function definition
2714  // dllimport attribute.
2715  if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2716    // dllimport attribute cannot be applied to definition.
2717    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2718      Diag(FD->getLocation(),
2719           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2720        << "dllimport";
2721      FD->setInvalidDecl();
2722      return FD;
2723    } else {
2724      // If a symbol previously declared dllimport is later defined, the
2725      // attribute is ignored in subsequent references, and a warning is
2726      // emitted.
2727      Diag(FD->getLocation(),
2728           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2729        << FD->getNameAsCString() << "dllimport";
2730    }
2731  }
2732  return FD;
2733}
2734
2735Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
2736  Decl *dcl = static_cast<Decl *>(D);
2737  Stmt *Body = static_cast<Stmt*>(BodyArg.release());
2738  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
2739    FD->setBody(Body);
2740    assert(FD == getCurFunctionDecl() && "Function parsing confused");
2741  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
2742    MD->setBody((Stmt*)Body);
2743  } else
2744    return 0;
2745  PopDeclContext();
2746  // Verify and clean out per-function state.
2747
2748  // Check goto/label use.
2749  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2750       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2751    // Verify that we have no forward references left.  If so, there was a goto
2752    // or address of a label taken, but no definition of it.  Label fwd
2753    // definitions are indicated with a null substmt.
2754    if (I->second->getSubStmt() == 0) {
2755      LabelStmt *L = I->second;
2756      // Emit error.
2757      Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
2758
2759      // At this point, we have gotos that use the bogus label.  Stitch it into
2760      // the function body so that they aren't leaked and that the AST is well
2761      // formed.
2762      if (Body) {
2763        L->setSubStmt(new NullStmt(L->getIdentLoc()));
2764        cast<CompoundStmt>(Body)->push_back(L);
2765      } else {
2766        // The whole function wasn't parsed correctly, just delete this.
2767        delete L;
2768      }
2769    }
2770  }
2771  LabelMap.clear();
2772
2773  return D;
2774}
2775
2776/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2777/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
2778ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2779                                           IdentifierInfo &II, Scope *S) {
2780  // Extension in C99.  Legal in C90, but warn about it.
2781  if (getLangOptions().C99)
2782    Diag(Loc, diag::ext_implicit_function_decl) << &II;
2783  else
2784    Diag(Loc, diag::warn_implicit_function_decl) << &II;
2785
2786  // FIXME: handle stuff like:
2787  // void foo() { extern float X(); }
2788  // void bar() { X(); }  <-- implicit decl for X in another scope.
2789
2790  // Set a Declarator for the implicit definition: int foo();
2791  const char *Dummy;
2792  DeclSpec DS;
2793  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2794  Error = Error; // Silence warning.
2795  assert(!Error && "Error setting up implicit decl!");
2796  Declarator D(DS, Declarator::BlockContext);
2797  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
2798  D.SetIdentifier(&II, Loc);
2799
2800  // Insert this function into translation-unit scope.
2801
2802  DeclContext *PrevDC = CurContext;
2803  CurContext = Context.getTranslationUnitDecl();
2804
2805  FunctionDecl *FD =
2806    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
2807  FD->setImplicit();
2808
2809  CurContext = PrevDC;
2810
2811  return FD;
2812}
2813
2814
2815TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2816                                    ScopedDecl *LastDeclarator) {
2817  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
2818  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2819
2820  // Scope manipulation handled by caller.
2821  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2822                                           D.getIdentifierLoc(),
2823                                           D.getIdentifier(),
2824                                           T, LastDeclarator);
2825  if (D.getInvalidType())
2826    NewTD->setInvalidDecl();
2827  return NewTD;
2828}
2829
2830/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
2831/// former case, Name will be non-null.  In the later case, Name will be null.
2832/// TagType indicates what kind of tag this is. TK indicates whether this is a
2833/// reference/declaration/definition of a tag.
2834Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
2835                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2836                             IdentifierInfo *Name, SourceLocation NameLoc,
2837                             AttributeList *Attr,
2838                             MultiTemplateParamsArg TemplateParameterLists) {
2839  // If this is not a definition, it must have a name.
2840  assert((Name != 0 || TK == TK_Definition) &&
2841         "Nameless record must be a definition!");
2842
2843  TagDecl::TagKind Kind;
2844  switch (TagType) {
2845  default: assert(0 && "Unknown tag type!");
2846  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2847  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2848  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2849  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
2850  }
2851
2852  DeclContext *DC = CurContext;
2853  ScopedDecl *PrevDecl = 0;
2854
2855  if (Name && SS.isNotEmpty()) {
2856    // We have a nested-name tag ('struct foo::bar').
2857
2858    // Check for invalid 'foo::'.
2859    if (SS.isInvalid()) {
2860      Name = 0;
2861      goto CreateNewDecl;
2862    }
2863
2864    DC = static_cast<DeclContext*>(SS.getScopeRep());
2865    // Look-up name inside 'foo::'.
2866    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2867
2868    // A tag 'foo::bar' must already exist.
2869    if (PrevDecl == 0) {
2870      Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
2871      Name = 0;
2872      goto CreateNewDecl;
2873    }
2874  } else {
2875    // If this is a named struct, check to see if there was a previous forward
2876    // declaration or definition.
2877    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2878    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2879
2880    if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2881      // FIXME: This makes sure that we ignore the contexts associated
2882      // with C structs, unions, and enums when looking for a matching
2883      // tag declaration or definition. See the similar lookup tweak
2884      // in Sema::LookupDecl; is there a better way to deal with this?
2885      while (isa<RecordDecl>(DC) || isa<EnumDecl>(DC))
2886        DC = DC->getParent();
2887    }
2888  }
2889
2890  if (PrevDecl && PrevDecl->isTemplateParameter()) {
2891    // Maybe we will complain about the shadowed template parameter.
2892    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2893    // Just pretend that we didn't see the previous declaration.
2894    PrevDecl = 0;
2895  }
2896
2897  if (PrevDecl) {
2898    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2899            "unexpected Decl type");
2900    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2901      // If this is a use of a previous tag, or if the tag is already declared
2902      // in the same scope (so that the definition/declaration completes or
2903      // rementions the tag), reuse the decl.
2904      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2905        // Make sure that this wasn't declared as an enum and now used as a
2906        // struct or something similar.
2907        if (PrevTagDecl->getTagKind() != Kind) {
2908          Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
2909          Diag(PrevDecl->getLocation(), diag::note_previous_use);
2910          // Recover by making this an anonymous redefinition.
2911          Name = 0;
2912          PrevDecl = 0;
2913        } else {
2914          // If this is a use, just return the declaration we found.
2915
2916          // FIXME: In the future, return a variant or some other clue
2917          // for the consumer of this Decl to know it doesn't own it.
2918          // For our current ASTs this shouldn't be a problem, but will
2919          // need to be changed with DeclGroups.
2920          if (TK == TK_Reference)
2921            return PrevDecl;
2922
2923          // Diagnose attempts to redefine a tag.
2924          if (TK == TK_Definition) {
2925            if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2926              Diag(NameLoc, diag::err_redefinition) << Name;
2927              Diag(Def->getLocation(), diag::note_previous_definition);
2928              // If this is a redefinition, recover by making this struct be
2929              // anonymous, which will make any later references get the previous
2930              // definition.
2931              Name = 0;
2932              PrevDecl = 0;
2933            }
2934            // Okay, this is definition of a previously declared or referenced
2935            // tag PrevDecl. We're going to create a new Decl for it.
2936          }
2937        }
2938        // If we get here we have (another) forward declaration or we
2939        // have a definition.  Just create a new decl.
2940      } else {
2941        // If we get here, this is a definition of a new tag type in a nested
2942        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2943        // new decl/type.  We set PrevDecl to NULL so that the entities
2944        // have distinct types.
2945        PrevDecl = 0;
2946      }
2947      // If we get here, we're going to create a new Decl. If PrevDecl
2948      // is non-NULL, it's a definition of the tag declared by
2949      // PrevDecl. If it's NULL, we have a new definition.
2950    } else {
2951      // PrevDecl is a namespace.
2952      if (isDeclInScope(PrevDecl, DC, S)) {
2953        // The tag name clashes with a namespace name, issue an error and
2954        // recover by making this tag be anonymous.
2955        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2956        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2957        Name = 0;
2958        PrevDecl = 0;
2959      } else {
2960        // The existing declaration isn't relevant to us; we're in a
2961        // new scope, so clear out the previous declaration.
2962        PrevDecl = 0;
2963      }
2964    }
2965  }
2966
2967CreateNewDecl:
2968
2969  // If there is an identifier, use the location of the identifier as the
2970  // location of the decl, otherwise use the location of the struct/union
2971  // keyword.
2972  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2973
2974  // Otherwise, create a new declaration. If there is a previous
2975  // declaration of the same entity, the two will be linked via
2976  // PrevDecl.
2977  TagDecl *New;
2978
2979  if (Kind == TagDecl::TK_enum) {
2980    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2981    // enum X { A, B, C } D;    D should chain to X.
2982    New = EnumDecl::Create(Context, DC, Loc, Name,
2983                           cast_or_null<EnumDecl>(PrevDecl));
2984    // If this is an undefined enum, warn.
2985    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
2986  } else {
2987    // struct/union/class
2988
2989    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2990    // struct X { int A; } D;    D should chain to X.
2991    if (getLangOptions().CPlusPlus)
2992      // FIXME: Look for a way to use RecordDecl for simple structs.
2993      New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2994                                  cast_or_null<CXXRecordDecl>(PrevDecl));
2995    else
2996      New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2997                               cast_or_null<RecordDecl>(PrevDecl));
2998  }
2999
3000  if (Kind != TagDecl::TK_enum) {
3001    // Handle #pragma pack: if the #pragma pack stack has non-default
3002    // alignment, make up a packed attribute for this decl. These
3003    // attributes are checked when the ASTContext lays out the
3004    // structure.
3005    //
3006    // It is important for implementing the correct semantics that this
3007    // happen here (in act on tag decl). The #pragma pack stack is
3008    // maintained as a result of parser callbacks which can occur at
3009    // many points during the parsing of a struct declaration (because
3010    // the #pragma tokens are effectively skipped over during the
3011    // parsing of the struct).
3012    if (unsigned Alignment = PackContext.getAlignment())
3013      New->addAttr(new PackedAttr(Alignment * 8));
3014  }
3015
3016  if (Attr)
3017    ProcessDeclAttributeList(New, Attr);
3018
3019  // Set the lexical context. If the tag has a C++ scope specifier, the
3020  // lexical context will be different from the semantic context.
3021  New->setLexicalDeclContext(CurContext);
3022
3023  // If this has an identifier, add it to the scope stack.
3024  if (Name) {
3025    // The scope passed in may not be a decl scope.  Zip up the scope tree until
3026    // we find one that is.
3027    while ((S->getFlags() & Scope::DeclScope) == 0)
3028      S = S->getParent();
3029
3030    // Add it to the decl chain.
3031    PushOnScopeChains(New, S);
3032  } else if (getLangOptions().CPlusPlus) {
3033    // FIXME: We also want to do this for C, but if this tag is
3034    // defined within a structure CurContext will point to the context
3035    // enclosing the structure, and we would end up inserting the tag
3036    // type into the wrong place.
3037    CurContext->addDecl(Context, New);
3038  }
3039
3040  return New;
3041}
3042
3043void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3044  TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3045
3046  // Enter the tag context.
3047  PushDeclContext(S, Tag);
3048
3049  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3050    FieldCollector->StartClass();
3051
3052    if (Record->getIdentifier()) {
3053      // C++ [class]p2:
3054      //   [...] The class-name is also inserted into the scope of the
3055      //   class itself; this is known as the injected-class-name. For
3056      //   purposes of access checking, the injected-class-name is treated
3057      //   as if it were a public member name.
3058      RecordDecl *InjectedClassName
3059        = CXXRecordDecl::Create(Context, Record->getTagKind(),
3060                                CurContext, Record->getLocation(),
3061                                Record->getIdentifier(), Record);
3062      InjectedClassName->setImplicit();
3063      PushOnScopeChains(InjectedClassName, S);
3064    }
3065  }
3066}
3067
3068void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3069  TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3070
3071  if (isa<CXXRecordDecl>(Tag))
3072    FieldCollector->FinishClass();
3073
3074  // Exit this scope of this tag's definition.
3075  PopDeclContext();
3076
3077  // Notify the consumer that we've defined a tag.
3078  Consumer.HandleTagDeclDefinition(Tag);
3079}
3080
3081/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3082/// types into constant array types in certain situations which would otherwise
3083/// be errors (for GCC compatibility).
3084static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3085                                                    ASTContext &Context) {
3086  // This method tries to turn a variable array into a constant
3087  // array even when the size isn't an ICE.  This is necessary
3088  // for compatibility with code that depends on gcc's buggy
3089  // constant expression folding, like struct {char x[(int)(char*)2];}
3090  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3091  if (!VLATy) return QualType();
3092
3093  Expr::EvalResult EvalResult;
3094  if (!VLATy->getSizeExpr() ||
3095      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
3096    return QualType();
3097
3098  assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3099  llvm::APSInt &Res = EvalResult.Val.getInt();
3100  if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3101    return Context.getConstantArrayType(VLATy->getElementType(),
3102                                        Res, ArrayType::Normal, 0);
3103  return QualType();
3104}
3105
3106bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
3107                          QualType FieldTy, const Expr *BitWidth) {
3108  // FIXME: 6.7.2.1p4 - verify the field type.
3109
3110  llvm::APSInt Value;
3111  if (VerifyIntegerConstantExpression(BitWidth, &Value))
3112    return true;
3113
3114  // Zero-width bitfield is ok for anonymous field.
3115  if (Value == 0 && FieldName)
3116    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3117
3118  if (Value.isNegative())
3119    return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
3120
3121  uint64_t TypeSize = Context.getTypeSize(FieldTy);
3122  // FIXME: We won't need the 0 size once we check that the field type is valid.
3123  if (TypeSize && Value.getZExtValue() > TypeSize)
3124    return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3125       << FieldName << (unsigned)TypeSize;
3126
3127  return false;
3128}
3129
3130/// ActOnField - Each field of a struct/union/class is passed into this in order
3131/// to create a FieldDecl object for it.
3132Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
3133                               SourceLocation DeclStart,
3134                               Declarator &D, ExprTy *BitfieldWidth) {
3135  IdentifierInfo *II = D.getIdentifier();
3136  Expr *BitWidth = (Expr*)BitfieldWidth;
3137  SourceLocation Loc = DeclStart;
3138  RecordDecl *Record = (RecordDecl *)TagD;
3139  if (II) Loc = D.getIdentifierLoc();
3140
3141  // FIXME: Unnamed fields can be handled in various different ways, for
3142  // example, unnamed unions inject all members into the struct namespace!
3143
3144  QualType T = GetTypeForDeclarator(D, S);
3145  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3146  bool InvalidDecl = false;
3147
3148  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3149  // than a variably modified type.
3150  if (T->isVariablyModifiedType()) {
3151    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
3152    if (!FixedTy.isNull()) {
3153      Diag(Loc, diag::warn_illegal_constant_array_size);
3154      T = FixedTy;
3155    } else {
3156      Diag(Loc, diag::err_typecheck_field_variable_size);
3157      T = Context.IntTy;
3158      InvalidDecl = true;
3159    }
3160  }
3161
3162  if (BitWidth) {
3163    if (VerifyBitField(Loc, II, T, BitWidth))
3164      InvalidDecl = true;
3165  } else {
3166    // Not a bitfield.
3167
3168    // validate II.
3169
3170  }
3171
3172  // FIXME: Chain fielddecls together.
3173  FieldDecl *NewFD;
3174
3175  NewFD = FieldDecl::Create(Context, Record,
3176                            Loc, II, T, BitWidth,
3177                            D.getDeclSpec().getStorageClassSpec() ==
3178                              DeclSpec::SCS_mutable,
3179                            /*PrevDecl=*/0);
3180
3181  if (II) {
3182    Decl *PrevDecl
3183      = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3184    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3185        && !isa<TagDecl>(PrevDecl)) {
3186      Diag(Loc, diag::err_duplicate_member) << II;
3187      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3188      NewFD->setInvalidDecl();
3189      Record->setInvalidDecl();
3190    }
3191  }
3192
3193  if (getLangOptions().CPlusPlus) {
3194    CheckExtraCXXDefaultArguments(D);
3195    if (!T->isPODType())
3196      cast<CXXRecordDecl>(Record)->setPOD(false);
3197  }
3198
3199  ProcessDeclAttributes(NewFD, D);
3200
3201  if (D.getInvalidType() || InvalidDecl)
3202    NewFD->setInvalidDecl();
3203
3204  if (II) {
3205    PushOnScopeChains(NewFD, S);
3206  } else
3207    Record->addDecl(Context, NewFD);
3208
3209  return NewFD;
3210}
3211
3212/// TranslateIvarVisibility - Translate visibility from a token ID to an
3213///  AST enum value.
3214static ObjCIvarDecl::AccessControl
3215TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
3216  switch (ivarVisibility) {
3217  default: assert(0 && "Unknown visitibility kind");
3218  case tok::objc_private: return ObjCIvarDecl::Private;
3219  case tok::objc_public: return ObjCIvarDecl::Public;
3220  case tok::objc_protected: return ObjCIvarDecl::Protected;
3221  case tok::objc_package: return ObjCIvarDecl::Package;
3222  }
3223}
3224
3225/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3226/// in order to create an IvarDecl object for it.
3227Sema::DeclTy *Sema::ActOnIvar(Scope *S,
3228                              SourceLocation DeclStart,
3229                              Declarator &D, ExprTy *BitfieldWidth,
3230                              tok::ObjCKeywordKind Visibility) {
3231
3232  IdentifierInfo *II = D.getIdentifier();
3233  Expr *BitWidth = (Expr*)BitfieldWidth;
3234  SourceLocation Loc = DeclStart;
3235  if (II) Loc = D.getIdentifierLoc();
3236
3237  // FIXME: Unnamed fields can be handled in various different ways, for
3238  // example, unnamed unions inject all members into the struct namespace!
3239
3240  QualType T = GetTypeForDeclarator(D, S);
3241  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3242  bool InvalidDecl = false;
3243
3244  if (BitWidth) {
3245    // TODO: Validate.
3246    //printf("WARNING: BITFIELDS IGNORED!\n");
3247
3248    // 6.7.2.1p3
3249    // 6.7.2.1p4
3250
3251  } else {
3252    // Not a bitfield.
3253
3254    // validate II.
3255
3256  }
3257
3258  // C99 6.7.2.1p8: A member of a structure or union may have any type other
3259  // than a variably modified type.
3260  if (T->isVariablyModifiedType()) {
3261    Diag(Loc, diag::err_typecheck_ivar_variable_size);
3262    InvalidDecl = true;
3263  }
3264
3265  // Get the visibility (access control) for this ivar.
3266  ObjCIvarDecl::AccessControl ac =
3267    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3268                                        : ObjCIvarDecl::None;
3269
3270  // Construct the decl.
3271  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
3272                                             (Expr *)BitfieldWidth);
3273
3274  if (II) {
3275    Decl *PrevDecl
3276      = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3277    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3278        && !isa<TagDecl>(PrevDecl)) {
3279      Diag(Loc, diag::err_duplicate_member) << II;
3280      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3281      NewID->setInvalidDecl();
3282    }
3283  }
3284
3285  // Process attributes attached to the ivar.
3286  ProcessDeclAttributes(NewID, D);
3287
3288  if (D.getInvalidType() || InvalidDecl)
3289    NewID->setInvalidDecl();
3290
3291  if (II) {
3292    // FIXME: When interfaces are DeclContexts, we'll need to add
3293    // these to the interface.
3294    S->AddDecl(NewID);
3295    IdResolver.AddDecl(NewID);
3296  }
3297
3298  return NewID;
3299}
3300
3301void Sema::ActOnFields(Scope* S,
3302                       SourceLocation RecLoc, DeclTy *RecDecl,
3303                       DeclTy **Fields, unsigned NumFields,
3304                       SourceLocation LBrac, SourceLocation RBrac,
3305                       AttributeList *Attr) {
3306  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3307  assert(EnclosingDecl && "missing record or interface decl");
3308  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3309
3310  if (Record) {
3311    QualType RecordType = Context.getTypeDeclType(Record);
3312    if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3313      RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
3314      // Diagnose code like:
3315      //     struct S { struct S {} X; };
3316      // We discover this when we complete the outer S.  Reject and ignore the
3317      // outer S.
3318      Diag(Def->getLocation(), diag::err_nested_redefinition)
3319        << Def->getDeclName();
3320      Diag(RecLoc, diag::note_previous_definition);
3321      Record->setInvalidDecl();
3322      return;
3323    }
3324  }
3325
3326  // Verify that all the fields are okay.
3327  unsigned NumNamedMembers = 0;
3328  llvm::SmallVector<FieldDecl*, 32> RecFields;
3329
3330  for (unsigned i = 0; i != NumFields; ++i) {
3331    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3332    assert(FD && "missing field decl");
3333
3334    // Get the type for the field.
3335    Type *FDTy = FD->getType().getTypePtr();
3336
3337    if (!FD->isAnonymousStructOrUnion()) {
3338      // Remember all fields written by the user.
3339      RecFields.push_back(FD);
3340    }
3341
3342    // C99 6.7.2.1p2 - A field may not be a function type.
3343    if (FDTy->isFunctionType()) {
3344      Diag(FD->getLocation(), diag::err_field_declared_as_function)
3345        << FD->getDeclName();
3346      FD->setInvalidDecl();
3347      EnclosingDecl->setInvalidDecl();
3348      continue;
3349    }
3350    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3351    if (FDTy->isIncompleteType()) {
3352      if (!Record) {  // Incomplete ivar type is always an error.
3353        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
3354        FD->setInvalidDecl();
3355        EnclosingDecl->setInvalidDecl();
3356        continue;
3357      }
3358      if (i != NumFields-1 ||                   // ... that the last member ...
3359          !Record->isStruct() ||  // ... of a structure ...
3360          !FDTy->isArrayType()) {         //... may have incomplete array type.
3361        Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
3362        FD->setInvalidDecl();
3363        EnclosingDecl->setInvalidDecl();
3364        continue;
3365      }
3366      if (NumNamedMembers < 1) {  //... must have more than named member ...
3367        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
3368          << FD->getDeclName();
3369        FD->setInvalidDecl();
3370        EnclosingDecl->setInvalidDecl();
3371        continue;
3372      }
3373      // Okay, we have a legal flexible array member at the end of the struct.
3374      if (Record)
3375        Record->setHasFlexibleArrayMember(true);
3376    }
3377    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3378    /// field of another structure or the element of an array.
3379    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
3380      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3381        // If this is a member of a union, then entire union becomes "flexible".
3382        if (Record && Record->isUnion()) {
3383          Record->setHasFlexibleArrayMember(true);
3384        } else {
3385          // If this is a struct/class and this is not the last element, reject
3386          // it.  Note that GCC supports variable sized arrays in the middle of
3387          // structures.
3388          if (i != NumFields-1) {
3389            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
3390              << FD->getDeclName();
3391            FD->setInvalidDecl();
3392            EnclosingDecl->setInvalidDecl();
3393            continue;
3394          }
3395          // We support flexible arrays at the end of structs in other structs
3396          // as an extension.
3397          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
3398            << FD->getDeclName();
3399          if (Record)
3400            Record->setHasFlexibleArrayMember(true);
3401        }
3402      }
3403    }
3404    /// A field cannot be an Objective-c object
3405    if (FDTy->isObjCInterfaceType()) {
3406      Diag(FD->getLocation(), diag::err_statically_allocated_object)
3407        << FD->getDeclName();
3408      FD->setInvalidDecl();
3409      EnclosingDecl->setInvalidDecl();
3410      continue;
3411    }
3412    // Keep track of the number of named members.
3413    if (FD->getIdentifier())
3414      ++NumNamedMembers;
3415  }
3416
3417  // Okay, we successfully defined 'Record'.
3418  if (Record) {
3419    Record->completeDefinition(Context);
3420  } else {
3421    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3422    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
3423      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3424      // Must enforce the rule that ivars in the base classes may not be
3425      // duplicates.
3426      if (ID->getSuperClass()) {
3427        for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3428             IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3429          ObjCIvarDecl* Ivar = (*IVI);
3430          IdentifierInfo *II = Ivar->getIdentifier();
3431          ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3432          if (prevIvar) {
3433            Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3434            Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3435          }
3436        }
3437      }
3438    }
3439    else if (ObjCImplementationDecl *IMPDecl =
3440               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
3441      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3442      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
3443      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
3444    }
3445  }
3446
3447  if (Attr)
3448    ProcessDeclAttributeList(Record, Attr);
3449}
3450
3451Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
3452                                      DeclTy *lastEnumConst,
3453                                      SourceLocation IdLoc, IdentifierInfo *Id,
3454                                      SourceLocation EqualLoc, ExprTy *val) {
3455  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
3456  EnumConstantDecl *LastEnumConst =
3457    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3458  Expr *Val = static_cast<Expr*>(val);
3459
3460  // The scope passed in may not be a decl scope.  Zip up the scope tree until
3461  // we find one that is.
3462  while ((S->getFlags() & Scope::DeclScope) == 0)
3463    S = S->getParent();
3464
3465  // Verify that there isn't already something declared with this name in this
3466  // scope.
3467  Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
3468  if (PrevDecl && PrevDecl->isTemplateParameter()) {
3469    // Maybe we will complain about the shadowed template parameter.
3470    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3471    // Just pretend that we didn't see the previous declaration.
3472    PrevDecl = 0;
3473  }
3474
3475  if (PrevDecl) {
3476    // When in C++, we may get a TagDecl with the same name; in this case the
3477    // enum constant will 'hide' the tag.
3478    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3479           "Received TagDecl when not in C++!");
3480    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
3481      if (isa<EnumConstantDecl>(PrevDecl))
3482        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
3483      else
3484        Diag(IdLoc, diag::err_redefinition) << Id;
3485      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3486      delete Val;
3487      return 0;
3488    }
3489  }
3490
3491  llvm::APSInt EnumVal(32);
3492  QualType EltTy;
3493  if (Val) {
3494    // Make sure to promote the operand type to int.
3495    UsualUnaryConversions(Val);
3496
3497    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3498    SourceLocation ExpLoc;
3499    if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
3500      delete Val;
3501      Val = 0;  // Just forget about it.
3502    } else {
3503      EltTy = Val->getType();
3504    }
3505  }
3506
3507  if (!Val) {
3508    if (LastEnumConst) {
3509      // Assign the last value + 1.
3510      EnumVal = LastEnumConst->getInitVal();
3511      ++EnumVal;
3512
3513      // Check for overflow on increment.
3514      if (EnumVal < LastEnumConst->getInitVal())
3515        Diag(IdLoc, diag::warn_enum_value_overflow);
3516
3517      EltTy = LastEnumConst->getType();
3518    } else {
3519      // First value, set to zero.
3520      EltTy = Context.IntTy;
3521      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
3522    }
3523  }
3524
3525  EnumConstantDecl *New =
3526    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3527                             Val, EnumVal,
3528                             LastEnumConst);
3529
3530  // Register this decl in the current scope stack.
3531  PushOnScopeChains(New, S);
3532
3533  // Add this enumerator into the enum itself.
3534  // FIXME: This means that the enumerator is stored in two
3535  // DeclContexts. This is not a long-term solution.
3536  New->setLexicalDeclContext(TheEnumDecl);
3537  TheEnumDecl->addDecl(Context, New, true);
3538  return New;
3539}
3540
3541// FIXME: For consistency with ActOnFields(), we should have the parser
3542// pass in the source location for the left/right braces.
3543void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
3544                         DeclTy **Elements, unsigned NumElements) {
3545  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
3546  QualType EnumType = Context.getTypeDeclType(Enum);
3547
3548  if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3549    EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3550    // Diagnose code like:
3551    //   enum e0 {
3552    //     E0 = sizeof(enum e0 { E1 })
3553    //   };
3554    Diag(Def->getLocation(), diag::err_nested_redefinition)
3555      << Enum->getDeclName();
3556    Diag(Enum->getLocation(), diag::note_previous_definition);
3557    Enum->setInvalidDecl();
3558    return;
3559  }
3560
3561  // TODO: If the result value doesn't fit in an int, it must be a long or long
3562  // long value.  ISO C does not support this, but GCC does as an extension,
3563  // emit a warning.
3564  unsigned IntWidth = Context.Target.getIntWidth();
3565
3566  // Verify that all the values are okay, compute the size of the values, and
3567  // reverse the list.
3568  unsigned NumNegativeBits = 0;
3569  unsigned NumPositiveBits = 0;
3570
3571  // Keep track of whether all elements have type int.
3572  bool AllElementsInt = true;
3573
3574  EnumConstantDecl *EltList = 0;
3575  for (unsigned i = 0; i != NumElements; ++i) {
3576    EnumConstantDecl *ECD =
3577      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3578    if (!ECD) continue;  // Already issued a diagnostic.
3579
3580    // If the enum value doesn't fit in an int, emit an extension warning.
3581    const llvm::APSInt &InitVal = ECD->getInitVal();
3582    assert(InitVal.getBitWidth() >= IntWidth &&
3583           "Should have promoted value to int");
3584    if (InitVal.getBitWidth() > IntWidth) {
3585      llvm::APSInt V(InitVal);
3586      V.trunc(IntWidth);
3587      V.extend(InitVal.getBitWidth());
3588      if (V != InitVal)
3589        Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3590          << InitVal.toString(10);
3591    }
3592
3593    // Keep track of the size of positive and negative values.
3594    if (InitVal.isUnsigned() || InitVal.isNonNegative())
3595      NumPositiveBits = std::max(NumPositiveBits,
3596                                 (unsigned)InitVal.getActiveBits());
3597    else
3598      NumNegativeBits = std::max(NumNegativeBits,
3599                                 (unsigned)InitVal.getMinSignedBits());
3600
3601    // Keep track of whether every enum element has type int (very commmon).
3602    if (AllElementsInt)
3603      AllElementsInt = ECD->getType() == Context.IntTy;
3604
3605    ECD->setNextDeclarator(EltList);
3606    EltList = ECD;
3607  }
3608
3609  // Figure out the type that should be used for this enum.
3610  // FIXME: Support attribute(packed) on enums and -fshort-enums.
3611  QualType BestType;
3612  unsigned BestWidth;
3613
3614  if (NumNegativeBits) {
3615    // If there is a negative value, figure out the smallest integer type (of
3616    // int/long/longlong) that fits.
3617    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
3618      BestType = Context.IntTy;
3619      BestWidth = IntWidth;
3620    } else {
3621      BestWidth = Context.Target.getLongWidth();
3622
3623      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
3624        BestType = Context.LongTy;
3625      else {
3626        BestWidth = Context.Target.getLongLongWidth();
3627
3628        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
3629          Diag(Enum->getLocation(), diag::warn_enum_too_large);
3630        BestType = Context.LongLongTy;
3631      }
3632    }
3633  } else {
3634    // If there is no negative value, figure out which of uint, ulong, ulonglong
3635    // fits.
3636    if (NumPositiveBits <= IntWidth) {
3637      BestType = Context.UnsignedIntTy;
3638      BestWidth = IntWidth;
3639    } else if (NumPositiveBits <=
3640               (BestWidth = Context.Target.getLongWidth())) {
3641      BestType = Context.UnsignedLongTy;
3642    } else {
3643      BestWidth = Context.Target.getLongLongWidth();
3644      assert(NumPositiveBits <= BestWidth &&
3645             "How could an initializer get larger than ULL?");
3646      BestType = Context.UnsignedLongLongTy;
3647    }
3648  }
3649
3650  // Loop over all of the enumerator constants, changing their types to match
3651  // the type of the enum if needed.
3652  for (unsigned i = 0; i != NumElements; ++i) {
3653    EnumConstantDecl *ECD =
3654      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3655    if (!ECD) continue;  // Already issued a diagnostic.
3656
3657    // Standard C says the enumerators have int type, but we allow, as an
3658    // extension, the enumerators to be larger than int size.  If each
3659    // enumerator value fits in an int, type it as an int, otherwise type it the
3660    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
3661    // that X has type 'int', not 'unsigned'.
3662    if (ECD->getType() == Context.IntTy) {
3663      // Make sure the init value is signed.
3664      llvm::APSInt IV = ECD->getInitVal();
3665      IV.setIsSigned(true);
3666      ECD->setInitVal(IV);
3667
3668      if (getLangOptions().CPlusPlus)
3669        // C++ [dcl.enum]p4: Following the closing brace of an
3670        // enum-specifier, each enumerator has the type of its
3671        // enumeration.
3672        ECD->setType(EnumType);
3673      continue;  // Already int type.
3674    }
3675
3676    // Determine whether the value fits into an int.
3677    llvm::APSInt InitVal = ECD->getInitVal();
3678    bool FitsInInt;
3679    if (InitVal.isUnsigned() || !InitVal.isNegative())
3680      FitsInInt = InitVal.getActiveBits() < IntWidth;
3681    else
3682      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3683
3684    // If it fits into an integer type, force it.  Otherwise force it to match
3685    // the enum decl type.
3686    QualType NewTy;
3687    unsigned NewWidth;
3688    bool NewSign;
3689    if (FitsInInt) {
3690      NewTy = Context.IntTy;
3691      NewWidth = IntWidth;
3692      NewSign = true;
3693    } else if (ECD->getType() == BestType) {
3694      // Already the right type!
3695      if (getLangOptions().CPlusPlus)
3696        // C++ [dcl.enum]p4: Following the closing brace of an
3697        // enum-specifier, each enumerator has the type of its
3698        // enumeration.
3699        ECD->setType(EnumType);
3700      continue;
3701    } else {
3702      NewTy = BestType;
3703      NewWidth = BestWidth;
3704      NewSign = BestType->isSignedIntegerType();
3705    }
3706
3707    // Adjust the APSInt value.
3708    InitVal.extOrTrunc(NewWidth);
3709    InitVal.setIsSigned(NewSign);
3710    ECD->setInitVal(InitVal);
3711
3712    // Adjust the Expr initializer and type.
3713    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3714                                          /*isLvalue=*/false));
3715    if (getLangOptions().CPlusPlus)
3716      // C++ [dcl.enum]p4: Following the closing brace of an
3717      // enum-specifier, each enumerator has the type of its
3718      // enumeration.
3719      ECD->setType(EnumType);
3720    else
3721      ECD->setType(NewTy);
3722  }
3723
3724  Enum->completeDefinition(Context, BestType);
3725}
3726
3727Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3728                                          ExprArg expr) {
3729  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3730
3731  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
3732}
3733
3734
3735void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3736                           ExprTy *alignment, SourceLocation PragmaLoc,
3737                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
3738  Expr *Alignment = static_cast<Expr *>(alignment);
3739
3740  // If specified then alignment must be a "small" power of two.
3741  unsigned AlignmentVal = 0;
3742  if (Alignment) {
3743    llvm::APSInt Val;
3744    if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3745        !Val.isPowerOf2() ||
3746        Val.getZExtValue() > 16) {
3747      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3748      delete Alignment;
3749      return; // Ignore
3750    }
3751
3752    AlignmentVal = (unsigned) Val.getZExtValue();
3753  }
3754
3755  switch (Kind) {
3756  case Action::PPK_Default: // pack([n])
3757    PackContext.setAlignment(AlignmentVal);
3758    break;
3759
3760  case Action::PPK_Show: // pack(show)
3761    // Show the current alignment, making sure to show the right value
3762    // for the default.
3763    AlignmentVal = PackContext.getAlignment();
3764    // FIXME: This should come from the target.
3765    if (AlignmentVal == 0)
3766      AlignmentVal = 8;
3767    Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
3768    break;
3769
3770  case Action::PPK_Push: // pack(push [, id] [, [n])
3771    PackContext.push(Name);
3772    // Set the new alignment if specified.
3773    if (Alignment)
3774      PackContext.setAlignment(AlignmentVal);
3775    break;
3776
3777  case Action::PPK_Pop: // pack(pop [, id] [,  n])
3778    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3779    // "#pragma pack(pop, identifier, n) is undefined"
3780    if (Alignment && Name)
3781      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3782
3783    // Do the pop.
3784    if (!PackContext.pop(Name)) {
3785      // If a name was specified then failure indicates the name
3786      // wasn't found. Otherwise failure indicates the stack was
3787      // empty.
3788      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3789        << (Name ? "no record matching name" : "stack empty");
3790
3791      // FIXME: Warn about popping named records as MSVC does.
3792    } else {
3793      // Pop succeeded, set the new alignment if specified.
3794      if (Alignment)
3795        PackContext.setAlignment(AlignmentVal);
3796    }
3797    break;
3798
3799  default:
3800    assert(0 && "Invalid #pragma pack kind.");
3801  }
3802}
3803
3804bool PragmaPackStack::pop(IdentifierInfo *Name) {
3805  if (Stack.empty())
3806    return false;
3807
3808  // If name is empty just pop top.
3809  if (!Name) {
3810    Alignment = Stack.back().first;
3811    Stack.pop_back();
3812    return true;
3813  }
3814
3815  // Otherwise, find the named record.
3816  for (unsigned i = Stack.size(); i != 0; ) {
3817    --i;
3818    if (Stack[i].second == Name) {
3819      // Found it, pop up to and including this record.
3820      Alignment = Stack[i].first;
3821      Stack.erase(Stack.begin() + i, Stack.end());
3822      return true;
3823    }
3824  }
3825
3826  return false;
3827}
3828