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