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