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