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