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