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