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