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